I noticed in the 3.2 release of CakePHP they added support for hashing using bcrypt. I'd like to take advantage of this however I can't seem to find how to use it properly.
On my User
models beforeSave()
method I'm doing this:
if(isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = Security::hash($this->data[$this->alias]['password'], 'blowfish');
unset($this->data['User']['passwd']);
}
which successfully saves a bcrypt hash in the database for the user account. However, I'm not sure how I'm meant to then log in the user. My users controller has the following login action:
public function login() {
if($this->request->is('post')) {
if($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Invalid username or password, try again.');
}
}
}
but it's saying "Invalid username or password" every time, and I'm certain it's the correct email/password. I think it's because the AuthComponent doesn't know it should use bcrypt but I'm not sure.
Any suggestions?
Alright I managed to work it out. Here's the relevant code:
In AppController.php
:
public $components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'Blowfish' => array(
'fields' => array('username' => 'email')
)
),
'loginRedirect' => array('controller' => 'pages', 'action' => 'home'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'home')
)
);
In User.php
:
public function beforeSave($options = array()) {
if(isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = Security::hash($this->data[$this->alias]['password'], 'blowfish');
unset($this->data['User']['passwd']);
}
return true;
}
Why?
unset($this->data['User']['password']);
This will clear the password before saving..
Relevant subject: CakePHP - How do I implement blowfish hashing for passwords?
plus+ varchar(60) for password db field