How to use CakePHP Auth component login with username or e-mail


CakePHP proved to be a nice flexible and lightweight framework. When I try to bend it a little to perform something unusual it almost always turns out ok. Below an example of a custom login action that will allow users to login with their username OR e-mail. The action goes into the Users controller.
/**
 * Log in with username OR e-mail
 *
 *  @param void
 */
function login() {
 
  // login with username or e-mail
  if (!empty($this->Auth->data)) {
 
    // save username entered in the login form
    $username = $this->Auth->data['User']['username'];
 
    // find a user by e-mail
    $this->User->contain();
    $find_by_email = $this->User->find('first', array(
        'conditions' => array('email' => $this->Auth->data['User']['username']),
        'fields' => 'username'
      )
    );
 
    // found
    if (!empty($find_by_email)) {
 
      // retry login with e-mail instead of username
      $this->Auth->data['User']['username'] = $find_by_email['User']['username'];
      if (!$this->Auth->login($this->Auth->data['User'])) {
 
        // login failed
        // bring back the username entered in the login form
        $this->Auth->data['User']['username'] = $username;
      } else {
        // login successful
        // clear flash message
        $this->Session->delete('Message.auth');
 
        // redirect
        if ($this->Auth->autoRedirect) {
          $this->redirect($this->Auth->redirect(), null, true);
        }
      }
    }
  }
}
The view:
<?php echo $form->create('User', array('action' => 'login')); ?>
<fieldset>
  <legend>Login</legend>
  <?php echo $form->input('username', array('label' => 'Username or e-mail:')); ?>
  <?php echo $form->input('password', array('label' => 'Password:')); ?>
</fieldset>
<?php echo $form->end('Login'); ?>

This entry was posted in . Bookmark the permalink.

Leave a Reply