RBAC WITH YII2-USER [QUICK TUTORIAL] (UPDATED)

  • AUTHOR: // CATEGORY: Tutorial

    4 Comments

    NOTE: Yii2 has changed and the authManager (step 1) configuration need to be updated. Read the Notes in the end of the tutorial.

    This tutorial show how to implement, in a easy way, a RBAC system using yii2-user from dektrium in a Yii 2 Advanced Application Template.

    First step is to install the Yii2 Advanced Application Template, then you should install the Yii2-user, use composer to install it is recommended. Here is the documentation for Yii2-user.

    After install it you can create 2 or 3 users and set different user roles from your admin account. This roles will be saves in the role collumn in user table.

    Now lets configure the RBAC:

    1. 1- Configure ‘authManager’ in common/conf/main.php this should be put in components array:
              'authManager' => [
                  'class' => 'yii\rbac\PhpManager',
      	    'defaultRoles' => ['admin','editor','user'], // here define your roles
                  //'authFile' => '@console/data/rbac.php' //the default path for rbac.php | OLD CONFIGURATION
                  'itemFile' => '@console/data/items.php', //Default path to items.php | NEW CONFIGURATIONS
                  'assignmentFile' => '@console/data/assignments.php', //Default path to assignments.php | NEW CONFIGURATIONS
      	     'ruleFile' => '@console/data/rules.php', //Default path to rules.php | NEW CONFIGURATIONS
              ],
    2. 2- Create a Rule to get and use the user role from user table. Create a file named “UserRoleRule.php” (or other name) in folder common/rbac (you need to create it) :
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      
      <?php namespace common\rbac; use yii\rbac\Rule; /**  * Checks if user role matches user passed via params  */ class UserRoleRule extends Rule {     public $name = 'userRole';     public function execute($user, $item, $params)     {         //check the role from table user         if(isset(\Yii::$app->user->identity->role))
      	     $role = \Yii::$app->user->identity->role;
      	else
      	     return false;
       
              if ($item->name === 'admin') {
                  return $role == 'admin';
              } elseif ($item->name === 'editor') {
                  return $role == 'admin' || $role == 'editor'; //editor is a child of admin
              }	elseif ($item->name === 'user') {
                  return $role == 'admin' || $role == 'editor' || $role == 'user'; || $role == NULL; //user is a child of editor and admin, if we have no role defined this is also the default role
              } else {
                  return false;
              }
          }
      }
    3. 3- Create a file carred RbacController.php under console\controllers:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      
      <?php namespace console\controllers; use Yii; use yii\console\Controller; use common\rbac\UserRoleRule; class RbacController extends Controller {     public function actionInit()     {         $auth = Yii::$app->authManager;
      	$auth->removeAll(); //remove previous rbac.php files under console/data
       
              //CREATE PERMISSIONS		
      	//Permission to create users
      	$createUsers = $auth->createPermission('createUsers');
              $createUsers->description = 'Create Users';
              $auth->add($createUsers);
       
      	//Permission to edit user profile
      	$editUserProfile = $auth->createPermission('editUserProfile');
              $editUserProfile->description = 'Edit User Profile';
              $auth->add($editUserProfile);
       
      	//APPLY THE RULE
      	$rule = new UserRoleRule(); //Apply our Rule that use the user roles from user table
      	$auth->add($rule);
       
      	//ROLES AND PERMISSIONS
              //user role
      	$user = $auth->createRole('user');  //user role
      	$user->ruleName = $rule->name;
      	$auth->add($user); 
      	// ... add permissions as children of $user ...
              //none in this example
       
      	//editor role
      	$editor = $auth->createRole('editor');
      	$editor->ruleName = $rule->name;
      	$auth->add($editor);
      	// ... add permissions as children of $editor ..
              $auth->addChild($editor, $user); //user is a child of editor
      	$auth->addChild($editor, $editUserProfile); //editor can edit profiles
       
      	//Admin role
      	$admin = $auth->createRole('admin');
      	$admin->ruleName = $rule->name;
      	$auth->add($admin);
      	$auth->addChild($admin, $editor); //editor is child of admin, for consequence user is also child of admin
      	// ... add permissions as children of $admin ..
      	$auth->addChild($admin, $createUsers); //admin role can create users and also edit users because is parent of editor
          }
      }
    4. 4- Create a data folder under console folder, because the command from step 5 will create a rbac.php file in console/data/
    5. 5- In your terminal go to your yii main forlder, usually inside public_html folder and run the following command:
      php yii rbac/init
    6. 6- Now you can use RBAC in your code, here is an example:
              if(\Yii::$app->user->can('createUser')){
                   //call view with form to create users
              }else{
                   //call view telling the users that can't create users
              }

     

    Now you only need to edit RbacController.php and add new permissions, and then redo the step 5, this will create a new rbac.php file.

    If you want to create new roles you need to add them to your RbacController.php, to your UserRoleRule.php and to defaultRoles array in main.php.

    Go luck…

    PS. If you previously use the file ‘@console/data/rbac.php’, apply the changes described in step 1, then erase rbac.php file and redo step 5.

COMMENTS

4 Responses to RBAC with yii2-user [Quick Tutorial] (Updated)

  • paskuale wrote on Junho 27, 2014 at 5:01 //

    Great, thanks for share it 😉

  • Scott wrote on Julho 10, 2014 at 5:05 //

    Issue with Step 3 at line 39. $publisher variable is not previously defined. I believe it should be $editor.

    • Fábio Ferreira wrote on Julho 10, 2014 at 12:19 //

      Yes you are right!
      I create this example from my code and change the variable names but this line was left untouched 🙁
      Thank you…

  • pep wrote on Abril 29, 2015 at 5:24 //

    Great post! But how can I do the same with DBManager instead of php?