首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在用户和角色表中创建用户角色智能访问控制,加入cakephp 3?

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

Stack Overflow用户
提问于 2017-08-06 12:58:22
回答 1查看 395关注 0票数 0

用户表

角色表

我只想允许对角色表集的访问控制,比如:ctrl_view = 1意味着这个角色可以查看任何控制器视图。

我如何在不同的角色中设定不同的动作?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-22 22:41:34

遵循公约,user_role_id应该命名为" role_id ",role_id只应该是"id“,而user_name应该是”用户名“,或者在Auth组态中更改连接表单的默认字段名称。

代码语言:javascript
复制
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'
                ],
            ]);
// ...
}

在你的应用控制器里面,让你像这样

代码语言:javascript
复制
 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可以简化您的授权过程(我将不允许前缀,使用前缀我检查角色表),为此,您只需在isAuthorized函数的开头添加以下行:

代码语言:javascript
复制
if (!$this->request->getParam('prefix')) {
    return true;
}

希望它能帮上忙

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45532281

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档