在我们的 CakePHP 应用程序中,我们尝试使用 Auth 组件进行登录。
这是应用控制器:
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'homes', 'action' => 'dashboard'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'home')
)
);
public function beforeFilter() {
$this->Auth->allow('index','logout','display','home');
}
这是用户控制器:
class UsersController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add');
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Checkin now'));
$this->redirect(array('action' => 'login'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
}
然后按照以下步骤操作:
- 在浏览器中输入的 URL 为
http://localhost/cakephp/
- 从 Homepage
home.ctp
,导航到http://localhost/cakephp/users/login
登录,使用Login
按钮 - 输入用户名和密码,然后点击登录按钮
- 然后它重定向到上一个访问
home.ctp
的页面,而不是AppController
.
第二次尝试:
- 参观过
http://localhost/cakephp/users/login/
直接从 URL 字段 - 然后输入登录凭据,然后它重定向到正确的页面,如
AppController
.
为什么 Auth 组件的行为是这样的.....