基于Controller的认证
看配置代码:
$this->loadComponent('Auth', [
'authorize' => 'Controller',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => $this->referer()
]);
需求,在登录成功后需要修改用户表的某一个字段(最后登录时间)。
基于Controller认证的基础是 Auth是在Controller初始化之前,如果在认证流程走完之前进行数据库操作,是不会成功的。如下面的代码:
// In src/Controller/UsersController.php
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
// update login_logined field
$user = $this->Users->get($this->Auth->user('id'));
$user->last_logined = date("Y-m-d H:i:s");
$this->Users->save($user);
// end
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error('Your username or password is incorrect.');
}
}
上面代码一运行就会在
$user = $this->Users->get($this->Auth->user('id'));
这儿报错,因为Controller未被初始化,里面的任何东西都无法使用。如何才知道认证流程是否走完呢?走了好些弯路,其实在redirect之前就走完了,如果执行$this->redirect($this->Auth->redirectUrl());
不报错,就证明controller是初始化完了的。总结来看,就是$this->Auth->setUser($user);
这句话是关键作用,他通知Auth组件认证已经完成,请接着走。
最终代码修改如下:
// In src/Controller/UsersController.php
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
// update login_logined field
$user = $this->Users->get($this->Auth->user('id'));
$user->last_logined = date("Y-m-d H:i:s");
$this->Users->save($user);
// end
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error('Your username or password is incorrect.');
}
}
总结:Auth是在beforeFilter生命周期之前。