Jonas Kvist Jensen
Jonas Kvist Jensen

Reputation: 139

Change password function not working - hash wrong

Ok, I've been hitting my head against this wall all evening.

Can someone explain to my why this returns false (user model):

public function changePassword($user_id, $currentPassword, $newPassword, $repeatPassword){

    //Check repeat
    /*
    if($newPassword != $repeatPassword)
        return false;
        */

    //Check old password
    $this->id = $user_id;
    $current = $this->field('password');
    $passwordHasher = new BlowfishPasswordHasher();
    $hash = $passwordHasher->hash($currentPassword);
    if($current != $hash)
        return false;       

    //set password to data

    //save
    return true;
}

public function beforeSave($options = array()) {
    if(isset($this->data[$this->alias]['password'])) {
        $passwordHasher = new BlowfishPasswordHasher();
        $this->data[$this->alias]['password'] = $passwordHasher->hash($this->data[$this->alias]['password']);
    }
    return true;
}

I can see from debugging $current and $hash that the generated hash is not the same as the one pulled from the database. Question is why.

Login works fine by the way. CakePHP version is 2.6.5

EDIT: Problem solved. Complete solution here:

public function changePassword($user_id, $currentPassword, $newPassword, $repeatPassword){      
    //Check repeat
    if($newPassword != $repeatPassword)
        return false;           

    //Check old password
    $this->id = $user_id;
    $current = $this->field('password');
    $passwordHasher = new BlowfishPasswordHasher();     
    if(!$passwordHasher->check($currentPassword, $current))
        return false;       

    //set password to data
    $this->data['password'] = $newPassword;

    //save
    if(!$this->save($this->data))
        return false;

    return true;
}

public function beforeSave($options = array()) {
    if(isset($this->data[$this->alias]['password'])) {
        $passwordHasher = new BlowfishPasswordHasher();
        $this->data[$this->alias]['password'] = $passwordHasher->hash($this->data[$this->alias]['password']);
    }
    return true;
}

Upvotes: 0

Views: 161

Answers (1)

ADmad
ADmad

Reputation: 8100

$current and $hash that the generated hash is not the same

That's how blowfish works. It generates a new hash each time.

Instead of hashing the current password and doing string comparison with existing hash from datbase use BlowfishPasswordHasher::check() to check if current password matches hash from database.

Upvotes: 1

Related Questions