I need to create new user. And I want to save password into hash format in DB. But I failed several times.
Here is my code:
public function actionCreate()
{
$model = new User();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
public function validatePassword($password)
{
return Security::validatePassword($password, $this->password_hash);
}
/**
* Generates password hash from password and sets it to the model
*
* @param string $password
*/
public function setPassword($password)
{
$this->password_hash = Security::generatePasswordHash($password);
}
public function rules()
{
return [
[['c_authkey', 'inserttime'], 'required'],
[['c_branch', 'c_roleid', 'c_active', 'c_status'], 'integer'],
[['c_expdate', 'inserttime', 'updatetime'], 'safe'],
[['username', 'c_desig', 'insertuser', 'updateuser'], 'string', 'max' => 50],
[['password'], 'string', 'max' => 32],
[['c_authkey'], 'string', 'max' => 256],
[['c_name'], 'string', 'max' => 100],
[['c_cellno'], 'string', 'max' => 15],
[['username'], 'unique']
];
}
What I am missing? what's the solution?
You are saving the unhashed password password
instead of password_hash
. This can be accomplished using ActiveRecord::beforeSave()
to set the password value to password_hash
. You should also use a different name for the password field in the form say password_field
.
public function beforeSave($insert) {
if(isset($this->password_field))
$this->password = Security::generatePasswordHash($this->password_field);
return parent::beforeSave($insert);
}