PHP – Yii simple Role Based Access Control

Hey, there are a lot of Yii developer used to try to make a role based access control. But the process is too long and complex. here i am describing a simple role based access process. Here you need to make some changes on the core code.

At first you need to go the “UserIdentity.php” file which can be found in “protected/components/UserIdentity.php” .

then replace the code by

class UserIdentity extends CUserIdentity
{
private $id;
public function authenticate()
{
$record=User::model()->findByAttributes(array('username'=>$this->username));
if($record===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;

else if($record->password!==crypt($this->password,md5(1234))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->id=$record->id;
$this->username = $record->username;
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}

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

 

Here

$this->setState('roles', $record->roles);

This is very much important which is used to set a session as user role. you can get this by

Yii::app()->user->getState('roles');" or "Yii::app()->user->roles

Now Add a simple class “WebUser.php” if you have created once then you have to modify it. you can find this file “protected/components” or you need to create it under this directory.

class WebUser extends CWebUser
{
/**
* Overrides a Yii method that is used for roles in controllers (accessRules).
*
* @param string $operation Name of the operation required (here, a role).
* @param mixed $params (opt) Parameters for this operation, usually the object to access.
* @return bool Permission granted?
*/
public function checkAccess($operation, $params=array())
{
if (empty($this->id)) {
return false;
}
$role = $this->getState("roles");
if ($role === 'admin') {
return true; // admin role is supreme
}
// allow access if the operation request is the current user's role
return ($operation === $role);
}
}

If you wanna make you own logic for checkAccess() you have the authority.

Now dont forget to add this class in the component . Go to the “protected/config/main.php” and

'components' => array(
...
...
'user' => array(
'class' => 'WebUser',
),

...
...

Now you can check the permission in you php code like this

Yii::app()->user->checkAccess('admin') or Yii::app()->user->checkAccess('member') .

 

You can Filter all the authentication in your controller. Simply add the “role” in the accessRules() function.

See Example..

public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations.
// this must exist in the controller
);
}

public function accessRules()
{
return array(
array('allow',
'actions'=>array('admin'),
'roles'=>array('member', 'subscriber'), // these roles are exist in the database table field
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}

Here admin action can perform only for ‘member’ and ‘subscriber’.

You can manipulate manu item according to role

$user = Yii::app()->user; // just a convenience to shorten expressions
$this->widget('zii.widgets.CMenu',array(
'items'=>array(
array('label'=>'Users', 'url'=>array('/manageUser/admin'), 'visible'=>$user->checkAccess('member')),
array('label'=>'Your Ideas', 'url'=>array('/userarea/ideaList'), 'visible'=>$user->checkAccess('subscriber')),
array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>$user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!$user->isGuest)
),
));

You can use this for Content also. This is why CWebUser::checkAccess() has an optional “$param” parameter. Now suppose we want to check is a user has the right to update a Post record. We can write:

Yii::app()->user->checkAccess('subscriber', $post);

Happy Coding …

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s