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

how to create user role wise access control in user and role table joining in cakephp 3?

用户table

角色table

我只想允许对角色 table 的访问控制设置如下:ctrl_view = 1 表示此角色可以查看任何控制器视图。

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

按照 conventions, user_role_id should be named "role_id", role_id only "id" and user_name should be "username" or inside your Auth configuration 更改用于连接表单的默认字段名称。

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 中做一些这样的事情

 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;
    }

最后,我认为最好使用 "prefix",带有前缀 u 可以简化您的授权过程(没有前缀 i 允许,带有前缀 i 检查我的角色 table),因为您只需在 isAuthorized 函数的开头添加这些行:

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

希望对您有所帮助