加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

根据CakePHP 3中的角色授权用户

发布时间:2020-12-13 21:58:53 所属栏目:PHP教程 来源:网络整理
导读:我想基于几个角色授权用户.所有访客都应该能够到达方法节目.所以我在AppController中写道: public function beforeFilter(Event $event) { $this-Auth-allow(['show']);} 有用. 在AppController的initialize()方法中,我还得到了: $this-loadComponent('Aut
我想基于几个角色授权用户.所有访客都应该能够到达方法节目.所以我在AppController中写道:

public function beforeFilter(Event $event) {
    $this->Auth->allow(['show']);
}

有用.

在AppController的initialize()方法中,我还得到了:

$this->loadComponent('Auth',[
    'authorize' => 'Controller'
]);

我想允许具有角色“user”的登录用户访问所有“索引”和“添加”方法,所以我在AppController中写道:

public function isAuthorized($user) {
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
if (isset($user['role']) && $user['role'] === 'user') {
$this->Auth->allow(['index','logout','add']);
}

return false;
}

管理员可以按预期访问所有方法.用角色“user”登录的用户无法达到“index”或“add”方法.我怎样才能解决这个问题?

解决方法

而不是使用您的逻辑添加额外的Auth允许,只需使用逻辑来确定它们是否在允许的操作中,通过检查操作,如果它们被授权则返回true.

public function isAuthorized($user) {

    // Admin allowed anywhere
    if (isset($user['role']) && $user['role'] === 'admin') {
        return true;
    }

    // 'user' allowed in specific actions
    if (isset($user['role']) && $user['role'] === 'user') {

        $allowedActions = ['index','add'];
        if(in_array($this->request->action,$allowedActions)) {
            return true;
        }

    }
    return false;
}

(显然这段代码可以根据自己的喜好缩短,但它显示了这个概念)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读