CakePHP3 BeforeFilter&验证重定向

时间:2016-10-15 20:00:29

标签: authentication cakephp-3.x before-filter

任何人都可以帮助我理解与Cakephp 3.3的交易以及我遇到的BeforeFilter / Auth Redirect问题。

我使用默认的Auth组件。我创建了一个自定义组件,它还检查会话变量(注册),如果未设置该变量,则重定向到设计用于设置所需注册的页面。

这是我的自定义组件:

<?php

namespace App\Controller\Component;

use Cake\Controller\Component;
use Cake\Network\Request;


class RegistrationCheckComponent extends Component
{

private $_allowedActions = [];
private $_superUserBypass = false;

public $components = ['Auth'];

public function superUserBypass($val = false) {
    $this->_superUserBypass = $val;
}

public function allow(Array $allowedActions = []) {
    $this->_allowedActions = $allowedActions;
}

public function verify() {

    if($this->_superUserBypass) {
        return true;
    }

    $session = $this->request->session();
    //if Auth Registration is not set
    if(!$session->read('Auth.Registration')) {
        //if requested action is not in the array of allowed actions, redirect to select registration
        if(!in_array($this->request->param('action'), $this->_allowedActions)) {
            return $this->redirect();
        };
        return true;
    }
    return true;

}

public function redirect() {
    $controller = $this->_registry->getController();
    return $controller->redirect($this->config('redirect'));
}

}

并非所有控制器都需要设置注册变量,这就是我决定采用组件方法的原因。然而,该组件通过以下行加载到AppController中:

$this->loadComponent('RegistrationCheck', ['redirect' => ['controller' => 'Users', 'action' => 'registrations']]);

在需要设置Registration变量的控制器中,我包括以下beforeFilter函数:

public function beforeFilter(Event $event) {
    parent::beforeFilter($event);
    return $this->RegistrationCheck->verify();
}

现在,我已经定义了一些集成测试,其中一个是:

public function testUnauthenticatedEdit()
{
    $this->get('/teams/edit');
    $this->assertRedirect(['controller' => 'Users', 'action' => 'login']);
}

因此,在我实现了RegistrationCheck组件之后,我运行了集成测试。我期待测试通过,但事实并非如此。有趣的是,它实际上返回了一个重定向到用户 - &gt;注册,而不是像我预期的那样返回用户 - >登录。

在我看来,在Auth组件重定向之前发生了RegistrationCheck重定向。我不确定这是一笔巨大的交易,因为重定向到没有Auth设置的注册将最终重定向回登录,但忽略它似乎是不正确的......我也是只是想了解更多实际情况。

有人可以建议更改我的代码,以确保在RegistrationCheck组件之前处理Auth组件吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

嗯,经过一番研究后,我找到了我在这里寻找的答案:http://book.cakephp.org/3.0/en/controllers/components/authentication.html#deciding-when-to-run-authentication

非常简单,只是想在这里为可能遇到同一问题的人提供一个答案。

相关问题