Yii2框架RBAC(Role-Based Access Control)的使用

1、在项目的common/config/main.php文件的components中添加如下代码:

   'authManager' => [
      'class' => 'yii bacDbManager',
      'itemTable' => 'auth_item',
      'assignmentTable' => 'auth_assignment',
      'itemChildTable' => 'auth_item_child',
     ],
Yii2框架RBAC(Role-Based Access Control)的使用
 
2, yii migrate --migrationPath=@yii/rbac/migrations/
    运行此命令生成权限数据表
  Yii2框架RBAC(Role-Based Access Control)的使用
3、配置完毕,下面我们尝试着创建一个 许可 Permiassion,代码如下
 
    public function createPermission($item)
    {
        $auth = Yii::$app->authManager;
 
        $createPost = $auth->createPermission($item);
        $createPost->description = '创建了 ' . $item . ' 许可';
        $auth->add($createPost);
    }
 
4、好的, 许可我们就创建完成了,下面我们创建一个 角色吧 roles
 
public function createRole($item)
    {
        $auth = Yii::$app->authManager;
 
        $role = $auth->createRole($item);
        $role->description = '创建了 ' . $item . ' 角色';
        $auth->add($role);
    }
 
5、给角色分配许可
 
 static public function createEmpowerment($items)
    {
        $auth = Yii::$app->authManager;
 
        $parent = $auth->createRole($items['name']);
        $child = $auth->createPermission($items['description']);
 
        $auth->addChild($parent, $child);
    }
 
6、 分配许可也创建完成了,给角色分配用户
 
 static public function assign($item)
    {
        $auth = Yii::$app->authManager;
        $reader = $auth->createRole($item['name']);
        $auth->assign($reader, $item['description']);
    }
 
 
7、验证用户是否有权限
 
 public function beforeAction($action)
    {
        $action = Yii::$app->controller->action->id;
        if(Yii::$app->user->can($action)){
            return true;
        }else{
            throw new yiiwebUnauthorizedHttpException('对不起,您现在还没获此操作的权限');
        }
    }