任何人都可以幫助我理解Cakephp 3.3的處理和我遇到的BeforeFilter/Auth重定向問題。我使用默認的Auth組件。我創建了一個額外檢查會話變量(註冊)的自定義組件,如果該變量未設置,則重定向到設計用於設置所需註冊的選擇頁面。CakePHP3 BeforeFilter&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'));
}
}
並非所有控制器的要求要設置的註冊變量,這就是爲什麼我決定去與該組件的方法。
$this->loadComponent('RegistrationCheck', ['redirect' => ['controller' => 'Users', 'action' => 'registrations']]);
在需要註冊變量設置,我包括以下beforeFilter功能的控制器::
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
return $this->RegistrationCheck->verify();
}
現在,我已經組件通過該線路但是裝載在AppController的有一些集成測試定義,這裏是其中的一個:
public function testUnauthenticatedEdit()
{
$this->get('/teams/edit');
$this->assertRedirect(['controller' => 'Users', 'action' => 'login']);
}
所以,我實現了我的RegistrationCheck組件後,我跑了集成測試。我期待測試通過,但沒有。有趣的是,它實際上返回了一個重定向到用戶 - >註冊,而不是用戶 - >登錄,如我所料。
在我看來RegistrationCheck重定向發生在Auth組件重定向之前。我不確定這是一筆鉅額交易,因爲重定向到沒有Auth設置的註冊將最終重定向回登錄,但忽略它似乎是不正確的......另外,我只想了解更多一點實際發生的事情。
任何人都可以建議更改我的代碼,以確保在RegistrationCheck組件之前處理Auth組件嗎?
在此先感謝。