Jonnny
Jonnny

Reputation: 5039

Yii2 passwordHash returns different values

I've made a few apps with Yii2, but having some trouble with the login functionality here. The passwords don't seem to match.

_form.php

<?= $form->field($model, 'first_name')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'last_name')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'pass')->passwordInput(['maxlength' => true]) ?>

User.php

public function beforeSave($insert) 
{

    if($this->isNewRecord)
    {
        $this->pass = Yii::$app->getSecurity()->generatePasswordHash($this->pass);

    }
    return parent::beforeSave($insert);
}

LoginForm.php

    public function validatePassword($attribute, $params)
{
    if (!$this->hasErrors()) {
        $user = $this->getUser(); 
        echo 'current: ' . $user->pass; 
        echo '<br />';
        echo 'plain: ' . Yii::$app->getSecurity()->generatePasswordHash('Password');
        echo '<br />';
        echo 'function: ' . $user->validatePassword($this->pass);

        if (!$user || !$user->validatePassword($this->pass)) {
            $this->addError($attribute, 'Incorrect user or password.');
        }
    }
}

My email and password fail here. I echoed out some things to check. The user value from the DB is always the same, the plain version where I pass "Password" always returns a different hash and the third print_r() returns nothing. I'm not sure what I'm doing wrong here?

Upvotes: 2

Views: 525

Answers (2)

Arie Satriananta
Arie Satriananta

Reputation: 51

  • the generatePasswordHash function will always create different value if you do print_r().
  • but the validatePassword function always return true if your password string is correct
  • so never mind about it.
  • maybe your column length in database is to short to save the hash

Upvotes: -1

Onedev_Link
Onedev_Link

Reputation: 2012

Check this code:

$password = 'Password';
$passwordHash = Yii::$app->getSecurity()->generatePasswordHash($password);
Yii::$app->getSecurity()->validatePassword($password, $passwordHash);

You should:

  • Correct write result of generatePasswordHash to database
  • use that hash on validatePassword method

Write correct user->validatePassword method like this:

public function validatePassword($password)
{
    return Yii::$app->security->validatePassword($password, $this->password_hash);
}

Upvotes: 2

Related Questions