【发布时间】:2014-08-20 02:02:33
【问题描述】:
我需要创建新用户。我想将密码保存为数据库中的哈希格式。但是我失败了好几次。
这是我的代码:
控制器
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']
];
}
我错过了什么?有什么解决办法?
【问题讨论】:
-
您有两个返回语句(这是复制+粘贴错误还是您的问题的一部分?)。删除第一个,因为它是演示中不使用安全组件的那个。
-
这是我的问题的一部分。我删除了第一个。但它只保存静态密码,如:123 ..如何将它们转换为哈希并保存到数据库 .. 谢谢
-
那么请编辑问题以包含实际导致您的问题的代码
-
谢谢。我已经编辑了我的问题行。它仅保存静态密码,例如:123 ..如何将它们转换为哈希并保存到数据库。请
-
您在数据库中的密码字段名称是什么?
标签: yii yii-components yii2