Dear Friend,
If you have created user table ,add a column called role (for example).
When user is created or getting registered,You assign a value(admin,manager,agent) inside the role column.
When users login, the roles should be assigned. In order to do that, you have to modify
CUserIdentity::authenticate method in components directory.
I give an example.
public function authenticate()
{ $user=User::model()->find('username=:username',array('username'=>$this->username));
if($user==null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if(!$user->validatePassword($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{Yii::app()->user->setState('role',$user->role);
$this->errorCode=self::ERROR_NONE;
return !$this->errorCode;}
}
Now when user login, you can call the value of his role by calling
Yii::app()->user-role.This is available as far as he gets logged in.
You can call it anywhere.
Now if he is admin,we can allow him to delete a record.
The following code allows only admin to carryout delete action in a controller.
public function actionDelete($id)
{
if(Yii::app()->user->role=='admin')
{
$this->loadModel($id)->delete();
}
else
throw new CHttpException('You are not allowed to do this action');
}
The following code allows both the manager and admin to carryout update action in a controller.
public function actionUpdate($id)
{
$model=$this->loadModel($id);
if(Yii::app()->user->role=='admin'||Yii::app()->user->role=='manager') {
if(isset($_POST['Post']))
{
$model->attributes=$_POST['Post'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
else
throw new CHttpException('You are not allowed to do this action');
}
This is very simple approach of authorization.(for example -blogsite)
Of course you can modify accessRules in the controller for some extra control.