2
votes

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?

3
I suppose you mean 2.3? - Jelmer
Have you configured your AuthComponent for Blowfish authentication as well? book.cakephp.org/2.0/en/core-libraries/components/… - thaJeztah
Looks like I missed that. I've changed my $components declaration to what it says in the cookbook however I'm still getting the invalid username/password message. Here's the relevant code: pastebin.com/7EL0p9Bc - James Dawson
@JamesDawson Please update your question with the relevant code , So when Pastebin deletes your code in a year or maybe even in a month, we can still learn from the solution if we have all the relevant stuff on one place :) - Jelmer

3 Answers

5
votes

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;
}
0
votes

Why?

unset($this->data['User']['password']);

This will clear the password before saving..