Managing user roles in yii

Now While starting with YII the first issue I faced was of user  roles,

The YII gives access rights directly on user names viz.

array(‘allow’, // allow admin user to perform ‘admin’ and ‘delete’ actions
‘actions’=>array(‘create’,’Admin’,’Add’),
‘users’=>array(‘admin’),
),

So here admin is the user name not the role, so I just tried this work around.

First access userIdentity.php in protected/components

Now

class UserIdentity extends CUserIdentity
{

private $_id;

public function authenticate()
{
$username=strtolower($this->username);
$user=Users::model()->find(‘LOWER(username)=?’,array($username));
if($user===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if(crypt($this->password,’rocker’)!=$user->password)
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$user->id;
$this->username=$user->username;
if($user->privillege==’admin’){
Yii::app()->user->setState(‘role’,’admin’);
}
else if($user->privillege==’dsteam’){
Yii::app()->user->setState(‘role’,’dsteam’);
}
else if($user->privillege==’contentwriter’){
Yii::app()->user->setState(‘role’,’contentwriter’);
}
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode==self::ERROR_NONE;
}

public function getId()
{
return $this->_id;
}
}

 

This will map the user from users table – username and privillege

Now in controller all we have to do is change accessRules function to

public function accessRules()
{
$userRole=Yii::app()->user->getState(‘role’);
if(  $userRole ==”admin”)
{
$arr =array(‘create’,’add’,’update’,’moveBack’);
}else if(  $userRole ==”contentwriter”){
$arr = array(‘write’);
}else {
$arr = array(”);
}

return array(
array(‘allow’,
‘actions’=>array(‘index’),
‘users’=>array(‘*’),
),
array(‘allow’,
‘actions’=>$arr,
‘users’=>array(‘@’),
),
array(‘deny’,
‘users’=>array(‘*’),
),
);
}

 

Thats it !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">