有没有像在Cakephp 3中那样处理角色的简单方法?
应用控制器
public function isAuthorized($user)
{
// Admin can access every action
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
// Default deny
return false;
}帖子控制程序
public function isAuthorized($user) {
// All registered users can add posts
if ($this->action === 'edit') {
return true;
}
return parent::isAuthorized($user);
}我从http://book.cakephp.org/3.0/en/controllers/components/authentication.html#testing-actions-protected-by-authcomponent那里知道
$this->auth->deny('add');正在执行此操作,但我如何添加用户/admin?
发布于 2016-07-18 14:08:20
我已经通过isAuthorised()方法以非常简单的方式使用了ACL身份验证。我希望它能对你有所帮助。
您可以使AppController.php必须定义属性
/**
* ACCESS CONTROL LIST BASED ON METHODS OF CLASS FOR USER ROLES
*/
var $accessControllList = array();定义私有方法
private function _checkAccessControll() {
if ($this->Auth->user('id')) {
if (!isset($this->accessControllList) || empty($this->accessControllList)) {
return true;
}
$action_name = $this->request->params['action'];
$user_role = $this->Auth->user('role');
if (isset($this->accessControllList['allowed']) && !empty($this->accessControllList['allowed']) && in_array($action_name, $this->accessControllList['allowed'])) {
return true;
} else if (isset($this->accessControllList['role_base'][$user_role]) && !empty($this->accessControllList['role_base'][$user_role]) && in_array($action_name, $this->accessControllList['role_base'][$user_role])) {
return true;
}
throw new \Cake\Network\Exception\ForbiddenException(__('You not have access for this page'));
}
return true;
}在isAuthorized()中添加以下行。
$this->_checkAccessControll();在任何控制器中,您都需要将ACL与角色进行映射。对于您的PostsController.php文件,如下所示
/**
* List of all accessible Action from URL
* @var array
*/
var $accessControllList = array(
'allowed' => array('view','index'), // allowed for any role.
'role_base' => array(
'administrator' => array('delete', 'approve'), //specially allowed for administrator only
'publisher' => array('view','create','index','replyComment'), // specially allowed for publisher only
'reader' => array('postComment','replyComment') // specially allowed for reader
)
);https://stackoverflow.com/questions/36933494
复制相似问题