2016-09-22 55 views
3

我想根据几个角色授权用户。所有参观者应该能够达到方法展示。所以我写了AppController:根据CakePHP中的角色授权用户3

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

它的工作原理。

在初始化()的AppController的方法,我有也:

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

我想允许记录的用户角色“用户”,达到所有“指标”和“添加”方法,使我在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; 
} 

管理员可以按预期方式访问所有方法。以角色“用户”登录的用户无法访问“索引”或“添加”方法。我怎样才能解决这个问题?

回答

5

而不是使用您的逻辑添加额外的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', 'logout', 'add']; 
     if(in_array($this->request->action, $allowedActions)) { 
      return true; 
     } 

    } 
    return false; 
} 

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

+1

嘿,我仍然不能投票,但你的回答对我帮助很大。谢谢! – nexequ