gpt4 book ai didi

yii - Yii2如何将用户密码以Hash格式保存到DB中

转载 作者:行者123 更新时间:2023-12-04 22:46:13 25 4
gpt4 key购买 nike

我需要创建新用户。我想将密码保存为数据库中的哈希格式。但是我失败了好几次。

这是我的代码:

Controller

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']
];
}

我缺少什么?解决办法是什么?

最佳答案

您正在保存未散列的密码 password 而不是 password_hash 。这可以使用 ActiveRecord::beforeSave() 将密码值设置为 password_hash 来完成。您还应该为表单中的密码字段使用不同的名称 say password_field

public function beforeSave($insert) {
if(isset($this->password_field))
$this->password = Security::generatePasswordHash($this->password_field);
return parent::beforeSave($insert);
}

关于yii - Yii2如何将用户密码以Hash格式保存到DB中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24477597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com