We seldom need to login into application using Email or Username while using Auth with Cakephp. To achieve this we either need to write customized Auth component or we can achieve the same with the following code :
public function validateUser() {
if (!empty($this->request->data)) {
$username = $this->request->data['User']['username'];
$find_by_email = $this->User->find('first', array(
'conditions' => array('email' => $this->request->data['User']['username']),
'fields' => 'username'
)
);
if (!empty($find_by_email)) {
$this->request->data['User']['username'] = $find_by_email['User']['username'];
}
$this->Auth->authenticate = array('Form' => array('userModel' => 'User',
'fields' => array(
'username' => 'username',
'password' => 'password'
)
));
if ($this->Auth->login()) {
echo "success";
} else {
echo "failure";
}
}
exit;
}
1 Comment(s)