How to save user password in Hash format in DB in Yii2

I need to create a new user. And I want to save the password in a hash format in the database. But I failed several times.

Here is my code:

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,
        ]);
    }
}

User 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);
}

User Table Rules

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 am I missing? what's the solution?

+4
source share
2 answers

You keep your password uncovered passwordinstead password_hash. This can be done using ActiveRecord::beforeSave()to set the password value password_hash. You should also use a different name for the password field in the say form password_field.

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

, , , .

setPassword , , VARCHAR(32) . VARCHAR(64). , , $2a$12$FbbEBjZVTLPZg4D/143KWu0ptEXL7iEcXpxJ.MNMl8/6L0SV5FR6u. , .

.

Yii2/Advanced. . $model->signup() ( Frontend Sitecontroller)

public function actionSignup()
{
    $model = new SignupForm();
    if ($model->load(Yii::$app->request->post())) {
        if ($user = $model->signup()) {
            if (Yii::$app->getUser()->login($user)) {
                return $this->goHome();
            }
        }
    }

    return $this->render('signup', [
        'model' => $model,
    ]);
}

, "" ( ). . .

public function signup()
{
    if ($this->validate()) {
        $user = new User();
        $user->username = $this->username;
        $user->email = $this->email;
        $user->setPassword($this->password);
        $user->generateAuthKey();
        $user->save();
        return $user;
    }

    return null;
}

print_r($model->getErrors()); $model->save();

, , .

+5

Source: https://habr.com/ru/post/1546481/


All Articles