In yii2 framework, RBAC is used to control the permissions of modules, controllers and methods and to use examples of rules

Time:2021-4-4

This paper describes the use of RBAC in yii2 framework to control the authority of modules, controllers and methods and the use of rules. The details are as follows:

When using the RBAC in yii2, you need to configure config first/ web.php :


return [
  // ...
  'components' => [
    'authManager' => [
      'class' => 'yii\rbac\DbManager',
    ],
    // ...
  ],
];

If you need to run Yii migrate to create a table, then/ console.php It also needs to be configured as above.

CMD enters the project directory and runs the following command:


yii migrate [email protected]/rbac/migrations

You will find that four tables are created in the database

auth_ Association table of assignment role and user
auth_ Item stores roles and permissions, which are distinguished by the type field
auth_ item_ Child stores the relationship between roles and permissions
auth_ The rule table is used to extend the permission function

For demonstration, we write four methods under the controller to create permissions, create roles, assign roles, and use rules.

IndexController.php The code is as follows:

<?php

namespace app\controllers;

use YII;
use app\models\MyUserLogin;
use app\rbac\UserUpdSelfRule;
use app\controllers\BaseController;

class IndexController extends BaseController
{

  //Home page
  public function actionIndex()
  {
    $this->renderPartial('index');
  }

  //Landing
  public function actionLogin()
  {
    if (YII::$app->request->isPost) {
      $user = new MyUserLogin();
      $user->load(YII::$app->request->post(), '');

      if ($user->login()) {
        Echo 'login successful';
      } else {
        Echo 'login failed';
      }

    } else {
      return $this->renderPartial('login');
    }
  }

  //For demonstration, here we add a few permissions
  public function actionPer()
  {
    $auth = YII::$app->authManager;
    //Create user delete permission
    $per = $auth->createPermission('user/del');
    $per - > description ='delete user ';
    $auth->add($per);
    //Create user update permissions
    $per = $auth->createPermission('user/upd');
    $per - > description ='update user ';
    $auth->add($per);
    //Create user add permission
    $per = $auth->createPermission('user/add');
    $per - > description ='add user ';
    $auth->add($per);
    //Create user view permissions
    $per = $auth->createPermission('user/list');
    User = $per description '- >;
    $auth->add($per);
  }

  //Add role
  public function actionRole()
  {
    $auth = YII::$app->authManager;

    //Add administrator role
    $admin = $auth->createRole('admin');
    $admin - > description ='administrator ';
    $auth->add($admin);
    //Give administrator permission
    $auth->addChild($admin, $auth->getPermission('user/del'));
    $auth->addChild($admin, $auth->getPermission('user/upd'));
    $auth->addChild($admin, $auth->getPermission('user/add'));
    $auth->addChild($admin, $auth->getPermission('user/list'));

    //Add regular employee role
    $employee = $auth->createRole('employee');
    $employee - > description ='ordinary employee ';
    $auth->add($employee);
    $auth->addChild($employee, $auth->getPermission('user/list'));
    $auth->addChild($employee, $auth->getPermission('user/add'));
  }

  //Assigning roles to users
  public function actionAssign()
  {
    $auth = YII::$app->authManager;

    //Note that 2 is the user's ID, which is the ID in your user table
    //It can also be obtained through Yii:: $app - > User - > ID
    $auth->assign($auth->getRole('admin'), 1);

    $auth->assign($auth->getRole('employee'), 2);
  }

  //Add rule
  public function actionRule()
  {
    $auth = YII::$app->authManager;
    $rule = new UserUpdSelfRule();
    $auth->add($rule);

    //Create permissions, associate with rules
    $per = $auth->createPermission('user/upd/updSelf');
    $per - > Description: 'users can only modify themselves';
    $per->ruleName = $rule->name;
    $auth->add($per);

    //Here, note that the user / UPD / updself permission should be set as the parent of user / UPD
    //Otherwise, ordinary employees will be blocked from accessing the user / UPD method
    $auth->addChild($per, $auth->getPermission('user/upd'));
    //Give ordinary employees user / UPD / updself permission. Note that we don't give employees user / UPD permission here
    $auth->addChild($auth->getRole('employee'), $per);
  }
}

We create the RBAC directory under the project directory and create the UserUpdSelfRule.php To implement the rule that users can only modify their own information.

<?php

//Note that the namespace should correspond to your directory
namespace app\rbac;

use yii\rbac\Rule;

//Must inherit from Yii / RBAC / rule
class UserUpdSelfRule extends Rule
{
  public $name = 'userUpdSelf';

  //You must implement the execute method
  //$user represents the user ID
  //Roles or permissions related to the $item rule
  //Parameters passed by $params
  public function execute($user, $item, $params)
  {
    //If the parameter ID is not set, return true directly
    if (!isset($params['id'])) {
      return true;
    }
    //Determine whether the ID is the current user ID
    return ($params['id'] == $user) ? true : false;
  }
}

We visit index / per to see the changes in the data table.

The results of visiting index / role are as follows:

The results of visiting index / assign are as follows:

The results of visiting index / rule are as follows:

In order to control the permissions of our modules, controllers and methods, we need to create a base class for unified processing. The above controllers are inherited from the base class.

BaseController.php The code is as follows:

<?php

namespace app\controllers;

use YII;
use yii\web\Controller;

class BaseController extends Controller
{
  //No verification required
  protected $noCheckAccess = [
    'index/index',
    'index/per',
    'index/role',
    'index/assign',
    'index/rule',
    'index/login',
  ];

  //You don't need to log in
  protected $noLogin = [
    'index/login',
  ];

  //Verify permissions
  //Note that do not write the module name, controller name, and method name to the init() function, otherwise you cannot get them
  //I've stepped on this pit, so we don't have to step on it any more
  public function beforeAction($action)
  {
    $mid = !empty($this->module->id) ? $this->module->id : '';
    $cid = !empty($this->id) ? $this->id : '';
    $aid = !empty($action->id) ? $action->id : '';

    //If the module is basic, we only verify the controller / method
    if ($mid == 'basic') {
      $per = "{$cid}/{$aid}";
    } else {
      $per = "{$mid}/{$cid}/{$aid}";
    }

    if (!in_array($per, $this->noLogin)) {
      if (!$this->checkOnline()) {
        $this->redirect('index/login');
      }
    }

    if (!in_array($per, $this->noCheckAccess)) {
      if (!YII::$app->user->can($per)) {
        Die ('You don't have permission ');
      }
    }

    return parent::beforeAction($action);
  }

  //Check if it's online
  public function checkOnline()
  {
    return !empty(YII::$app->user->id) ? true : false;
  }
}

To demonstrate, we create a UserController.php The code is as follows:

<?php

namespace app\controllers;

use YII;
use app\controllers\BaseController;

class UserController extends BaseController
{
  public function actionUpd()
  {
    $id = YII::$app->request->get('id', 0);

    echo 'user id : ', YII::$app->user->id, '<br>';

    //First judge whether the user has permission to modify himself
    if (YII::$app->user->can('user/upd/updSelf')) {
      //Then judge whether the modified ID is the same as your own ID, and judge in the userupdself rule
      if (YII::$app->user->can('user/upd/updSelf', ['id' => $id])) {
        Echo 'has the right to modify oneself';
      } else {
        Echo 'you can't modify something other than yourself';
      }
    } else {
      Echo 'modify all';
    }
  }

  public function actionDel()
  {
    echo 'user id : ', YII::$app->user->id, '<br>';
    echo 'user del';
  }

  public function actionList()
  {
    echo 'user id : ', YII::$app->user->id, '<br>';
    echo 'user list';
  }

  public function actionAdd()
  {
    echo 'user id : ', YII::$app->user->id, '<br>';
    echo 'user add';
  }
}

There are two users in my user list

Log in to these two users respectively, and then let them access user / add, user / del, user / list, and user / UPD. The results are as follows:

The admin user status is as follows:

The test user status is as follows:

Test is able to access user / UPD because we set user / UPD / updself as the parent of user / UPD. If it is not set, it will be blocked here.

For more information about Yii, readers who are interested in it can see the following topics: Yii framework introduction and common skills summary, PHP excellent development framework summary, smart template introduction basic course, PHP object-oriented programming introduction course, PHP string usage summary, PHP + MySQL database operation introduction course and PHP common database operation introduction course Summary of writing skills

I hope this article will be helpful to the PHP Programming Based on Yii framework.

Recommended Today

Third party calls wechat payment interface

Step one: preparation 1. Wechat payment interface can only be called if the developer qualification has been authenticated on wechat open platform, so the first thing is to authenticate. It’s very simple, but wechat will charge 300 yuan for audit 2. Set payment directory Login wechat payment merchant platform( pay.weixin.qq . com) — > Product […]