I’m implementing a logic where you can use either your username or email address to log in in CakePHP. I’m following an example in a book called CakePHP 1.3: Application Development Cookbook (Chapter 1: Allowing logins with username or email). The book explains that when the Auth component cannot log the user in with the provided info, it goes back to the login() action and can look for additional info that might log the user in with the logic within the login() action.
The code/logic is working. However, when I login with my email address, it still displays the loginError message, which says “Invalid account specified.” Below that it says “Welcome,” which is a message I display when a login is successfull.
These are what I’d like to know:
-
The book doesn’t indicate whether or not this is normal, but I’d like to learn how to omit this error message, since it doesn’t make sense. Where is THIS LINE (in comment) taking the user? The error message displays after that line.
-
.. and possibly display with “you logged logged in with email.” This is of secondary importance.
Below are what I think relevant code. Please let me know if you need more.
class AppController extends Controller {
public $components = array(
'Auth' => array(
'authorize' => 'controller',
'loginRedirect' => array(
'admin' => false,
'controller' => 'users',
'action' => 'dashboard'
),
'loginError' => 'Invalid account specified',
'authError' => 'You don\'t have the right permission'
),
'Session'
);
}
class UsersController extends AppController {
public function login() {
if (
!empty($this->data) &&
!empty($this->Auth->data['User']['username']) &&
!empty($this->Auth->data['User']['password'])
) {
$user = $this->User->find('first', array(
'conditions' => array(
'User.email' => $this->Auth->data['User']['username'],
'User.password' => $this->Auth->data['User']['password']
),
'recursive' => -1
));
if (!empty($user) && $this->Auth->login($user)) { // $this->Auth->login() true if logs in
if ($this->Auth->autoRedirect) { // I think autoRedirect is TRUE by default
$this->redirect($this->Auth->redirect()); // <<THIS LINE>>
}
} else {
$this->Session->setFlash($this->Auth->loginError, $this->Auth->flashElement, array(), 'auth');
}
}
}
You don’t need to setFlash for authError if you flash(‘auth’) in login view (as in the cookbook) and you don’t need to call redirect.