答案 0 :(得分:0)
关注conventions,user_role_id应命名为“role_id”,role_id只能命名为“id”,user_name应为“username”,或者在Auth configuration内更改默认字段名称用于连接表单。< / p>
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内部进行像这样的somtehing
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可以简化您的授权过程(我将不允许前缀,前缀i检查我的角色表),为此你必须简单地添加这些行在你的isAuthorized函数的开头:
if (!$this->request->getParam('prefix')) {
return true;
}
希望有所帮助