如何在用户和角色表加入cakephp 3中创建用户角色明智的访问控制?

时间:2017-08-06 12:58:23

标签: cakephp access-control cakephp-3.x rbac

用户表

enter image description here

角色表

enter image description here

我只想允许对角色表集进行访问控制,如:ctrl_view = 1表示此角色可以查看任何控制器视图。

如何设置不同角色的不同动作?

1 个答案:

答案 0 :(得分:0)

关注conventions,user_role_id应命名为“role_id”,role_id只能命名为“id”,user_name应为“username”,或者在Auth configuration内更改默认字段名称用于连接表单。< / p>

public function initialize() 
    {
//...
    $this->loadComponent('Auth', [
              'loginRedirect' => [
                'controller' => 'Pages',
                'action' => 'welcome',
                'prefix' => 'admin' 
              ],
              'logoutRedirect' => [
                'controller' => 'Users',
                'action' => 'login',
                'prefix' => false
              ],
              'authError' => 'Unauthorized access...',
              'authenticate' => [
                'Form' => [
                  'fields' => ['username' => 'user_name', 'password' => 'password']
                ]
              ],
              'authorize' => 'Controller',
              'unauthorizedRedirect' => [
                  'controller' => 'Pages',
                  'action' => 'unauthorized'
                ],
            ]);
// ...
}

并在Appcontroller内部进行像这样的somtehing

 public function isAuthorized($user)
      {

          if(!is_null($this->Auth->user())): // if user is logged

            $action = $this->request->getParam('action'); // get name action

            $this->loadModel('Roles'); // load your model Roles
            $query = $this->Authorizations->find() // find inside Roles
            ->where([
            'Roles.role_id IN' => $user['user_role_id'], // where role_id is like user_role_id of current user
            'Roles.ctl_'.$action => 1 // and where ctl_[action] is set to 1
            ])->toArray();

            if (!empty($query)): // if we find an occurence, we allow the action
              return true;
            else: // else we don't authorize
              return false,
            endif;

            /* previous lines can be change with this  ----> return (!empty($query)); */
          else: // if user is not connected we don't allow action
            return false
          endif;
    }

并且完成,我认为最好使用“前缀”,前缀u可以简化您的授权过程(我将不允许前缀,前缀i检查我的角色表),为此你必须简单地添加这些行在你的isAuthorized函数的开头:

if (!$this->request->getParam('prefix')) {
    return true;
}

希望有所帮助