5.2.6.9 autoRedirect
Normally, the AuthComponent will automatically redirect you as soon as it authenticates. Sometimes you want to do some more checking before you redirect users:
<?php
function beforeFilter() {
...
$this->Auth->autoRedirect = false;
}
...
function login() {
//-- code inside this function will execute only when autoRedirect was set to false (i.e. in a beforeFilter).
if ($this->Auth->user()) {
if (!empty($this->data['User']['remember_me'])) {
$cookie = array();
$cookie['username'] = $this->data['User']['username'];
$cookie['password'] = $this->data['User']['password'];
$this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');
unset($this->data['User']['remember_me']);
}
$this->redirect($this->Auth->redirect());
}
if (empty($this->data)) {
$cookie = $this->Cookie->read('Auth.User');
if (!is_null($cookie)) {
if ($this->Auth->login($cookie)) {
// Clear auth message, just in case we use it.
$this->Session->del('Message.auth');
$this->redirect($this->Auth->redirect());
}
}
}
}
?>
<?phpfunction beforeFilter() {...$this->Auth->autoRedirect = false;}...function login() {//-- code inside this function will execute only when autoRedirect was set to false (i.e. in a beforeFilter).if ($this->Auth->user()) {if (!empty($this->data['User']['remember_me'])) {$cookie = array();$cookie['username'] = $this->data['User']['username'];$cookie['password'] = $this->data['User']['password'];$this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');unset($this->data['User']['remember_me']);}$this->redirect($this->Auth->redirect());}if (empty($this->data)) {$cookie = $this->Cookie->read('Auth.User');if (!is_null($cookie)) {if ($this->Auth->login($cookie)) {// Clear auth message, just in case we use it.$this->Session->del('Message.auth');$this->redirect($this->Auth->redirect());}}}}?>
The code in the login function will not execute unless you set $autoRedirect to false in a beforeFilter. The code present in the login function will only execute after authentication was attempted. This is the best place to determine whether or not a successful login occurred by the AuthComponent (should you desire to log the last successful login timestamp, etc.).
With autoRedirect set to false, you can also inject additional code such as keeping track of the last successful login timestamp
<?php
function login() {
if( !(empty($this->data)) && $this->Auth->user() ){
$this->User->id = $this->Auth->user('id');
$this->User->saveField('last_login', date('Y-m-d H:i:s') );
$this->redirect($this->Auth->redirect());
}
}
?>
<?phpfunction login() {if( !(empty($this->data)) && $this->Auth->user() ){$this->User->id = $this->Auth->user('id');$this->User->saveField('last_login', date('Y-m-d H:i:s') );$this->redirect($this->Auth->redirect());}}?>


























