代码之家  ›  专栏  ›  技术社区  ›  Syed Nazmul Hassan

如何在cakephp 3中的用户和角色表连接中创建用户角色智能访问控制?

  •  0
  • Syed Nazmul Hassan  · 技术社区  · 7 年前

    用户表

    enter image description here

    enter image description here

    ctrl_view = 1 表示此角色可以查看任何控制器视图。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Benfarhat    7 年前

    跟随 conventions ,user\u role\u id应命名为“role\u id”,role\u id仅为“id”,user\u name应为“username”或在您的 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;
        }
    

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

    希望有帮助