Reputation: 5039
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
Reputation: 51
Upvotes: -1
Reputation: 2012
Check this code:
$password = 'Password';
$passwordHash = Yii::$app->getSecurity()->generatePasswordHash($password);
Yii::$app->getSecurity()->validatePassword($password, $passwordHash);
You should:
generatePasswordHash
to databasevalidatePassword
methodWrite correct user->validatePassword
method like this:
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
Upvotes: 2