Tips and Tricks to Use Yii Rights extension – RBAC (Role based access control )

Rights is a extension module in yii framework which can be used to have a interface for role based access control..

Using rights its very easy to manage various roles and permission in the application, and can be used as a standard for all projects..



Some Codes that people often need but are not documented..

1) To determine if the logged user is superuser

if(Yii::app()->user->isSuperuser)
   echo "I am one of the superuser of application, I have all access to app.";

2) Get all superusers in the application

  var_dump(Yii::app()->getModule("rights")->getAuthorizer()->getSuperusers());

3) Get all roles assigned to the logged-in user

$roles=Rights::getAssignedRoles(Yii::app()->user->Id);
    foreach($roles as $role)
       echo $role->name."<br />";

4) Get all users of a particular role (Lets say there is a DataEntry as a role whose job is to enter data in the system)

$data_entry_users=Yii::app()->getAuthManager()->getAssignmentsByItemName('DataEntry');
$data_entry_users_id=array();
  foreach($data_entry_users as $id=>$assignment)
    $data_entry_users_id[]=$id;

5) Assign a user a role in the system when he signs-up..

 if(Yii::app()->user->isSuperuser)
    $type=$_POST['Type'];</div>
 else
   $type='User';
 
$authorizer = Yii::app()->getModule("rights")->getAuthorizer(); 
$authorizer->authManager->assign($type, $model->id);;

Case: When superuser is creating the user he has a drop-down List of all roles in the system and he can select a role for the new user..
but if a person normally signs-up he doesn’t has that choice, he must be give User role.. Where $model->id is the id of new created user..

 6) Generate drop-down of all available roles in the application for a superuser so that he can select a role while user creation..

<?php
if (Yii::app()->user->isSuperuser) {
  $all_roles = new RAuthItemDataProvider('roles', array( 
            'type'=>2,
            ));
  $data = $all_roles->fetchData();
?>
<div>
<label for="type_id">Type</label>
<?php echo CHtml::dropDownList("Type",'',CHtml::listData($data,'name','name'));?></div>
<?php
}
?>

Tidak ada komentar

Diberdayakan oleh Blogger.