Tuesday 9 June 2015

Yii: Check roles based access on every page.

in Yii, if you want to restrict users from accessing only actions assigned to them.

Install modules:


Then assign permissions to the specific user roles.

Now, in Main Controller (/protected/components/controller.php),

Add following filter

public function filterAccessControl($filterChain) {
$controller = Yii::app()->controller->id;
$action = Yii::app()->controller->action->id;
//The RBAC admin module I'm using creates entries for operations as, e.g. Post.Create
// You may need to change this to match whatever entry format you have
// in your AuthItem table
$operation = ucfirst($controller) . '.' . ucfirst($action);
Yii::log('Checking auth for user: ' . Yii::app()->user->id. ' to operation: ' . $operation, 'info');
if (Yii::app()->user->checkAccess($operation)) {
Yii::log('User authorised', 'info');
$filterChain->run();
return true;
}
else {
Yii::log('Unauthorised user!!!!!', 'info');
throw new CHttpException(401, 'You are not authorized to perform this action.');
return false;
}
}

If a user visits a page which he does not have permission, following error will be displayed:

Error 401

You are not authorized to perform this action.



No comments:

Post a Comment

Parenting tips to inculcate learning habits in your kid

Parenting tips to inculcate learning habits in your kid Tip #1) Children do not learn things, they emitate. So, try to do things by yours...