Cakephp 3.6.14:拒绝操作后重定向

时间:2019-01-30 08:42:32

标签: php cakephp authorization cakephp-3.x

我正在尝试对控制器中的非管理员用户进行一些操作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'));
}

因此,现在无论何时不是管理员或项目经理的用户尝试执行indexdelete的操作,都将被重定向到“不允许使用方法”错误页面。但我想返回上一条消息:“您无权执行此操作”。

我试图在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']);
    }

但是在我想拒绝某些动作的所有控制器中,似乎并不是执行此操作的正确方法。还有另一种方法吗?

1 个答案:

答案 0 :(得分:0)

Cakephp为此提供了isAuthorized功能。您可以利用它。 只需在您的App控制器或单独的控制器中定义isAuthorized(如果要为每个控制器分别设置条件)即可。

 public function isAuthorized($user)
    {
        $roleArray = [1, 2]; // your role ids array
        if ( !in_array($user['role_id'], $roleArray) && in_array($this->request->getParam('action'), ['index', 'delete'])) {  // put your conditions here
           return false;
        }
      return true;
    }

Cakephp -> Authentication and Authorization -> Authorization (who’s allowed to access what)