after make or edit password User i have login error 'Incorrect username or password' in Yii2
login with user 'admin' is work ( i make admin user with actionCreate1)
auth_key: kYm0pvYAXY4IzuV7eYgGgtjSqoxxMNUL
password: $2y$13$QqsbMW3ErXwWOPad3abDYOPzh5XLwuEvQKBhZGEEDoT0Av5l0bE2S
but i make user or edit password , in login page i have error: 'Incorrect username or password'
i think problem from beforeSave in Model USER
User Table:
id int
auth_key text
username text
password text
actionCreate: it's not work
public function actionCreate()
{
$model = new User();
if ($model->load(Yii::$app->request->post())) {
if($model->save())
{
$model->img = UploadedFile::getInstance($model, 'img');
if($model->img !== null) $model->upload('img',$model->id);
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
actionCreate1: it's GOOD WORK
public function actionCreate()
{
$model = new User();
if ($model->load(Yii::$app->request->post())) {
$model->username = Yii::$app->request->post('User')['username'];
$model->password = Yii::$app->request->post('User')['password'];
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Model User:
public function beforeSave($insert)
{
if($this->password) {
$this->setPassword($this->password);
}
if($insert)
{
$this->generateAuthKey();
}
return parent::beforeSave($insert);
}
public function setPassword($password) {
$this->password = Yii::$app->security->generatePasswordHash($password);
}
public function generateAuthKey() {
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* @param $password
* @return bool
*/
public function validatePassword($password) {
return Yii::$app->security->validatePassword($password, $this->password);
}
/**
* @inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne([
'id' => $id
]);
}
public static function findIdentityByAccessToken($token, $type = null) {}
/**
* @param $username
* @return null|static
*/
public static function findByUsername($username)
{
return static::findOne([
'username' => $username,
]);
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->auth_key === $authKey;
}
You are using the same name for attribute storing password hash and raw password.
Either change password hash attribute to something like
passwod_hash
or raw password attribute to something likeraw_password
and modify the code accordingly to handle it.for fix this problem.
step1: change before save Model USER
step2: small change in update user