【发布时间】:2019-01-30 08:42:31
【问题描述】:
我正在尝试deny 为我的控制器中的非管理员用户执行一些操作。所以在控制器中我使用了这段代码:
public $components = array('Auth');
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
if($this->Auth->user('role_id')==1 or $this->Auth->user('role_id')==2){ //role: 1 admin, 2 project manager
$this->set('is_admin', true);
}
else
{
$this->Auth->deny(['index','delete']);
$this->set('is_admin', false);
}
$this->set('my_id', $this->Auth->user('id'));
}
因此,现在只要不是管理员或项目经理的用户尝试执行index 或delete 操作,就会被重定向到“方法不允许”错误页面。但是我想返回上一页并显示一条消息:“您无权执行此操作”。
我尝试在 AppController 中设置'unauthorizedRedirect' => $this->referer():
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => $this->referer()
]);
但是没有用。我设法实现这一点的唯一方法是在控制器的beforeFilter 函数中使用此代码:
if(!($this->Auth->user('role_id')==1 && !$this->Auth->user('role_id')==2 && ($this->request->action === 'index' || $this->request->action === 'delete')){
$this->Flash->error(__('You are not authorized to perform this action'));
return $this->redirect(['controller' => 'Users', 'action' => 'index']);
}
但在我想拒绝某些操作的所有控制器中,这似乎不是正确的方法。还有其他方法吗?
【问题讨论】:
-
你可能想研究一个更干净的解决方案,比如tinyauth,代码更少,可能更安全。
标签: php cakephp authorization cakephp-3.x