A
A
Albert Tobacco2015-01-30 11:45:14
Yii
Albert Tobacco, 2015-01-30 11:45:14

How to properly store password in Yii2?

Problem:
My User table has a password_hash field.
I am creating a form in which the user can change his email name and password.
By displaying this form, I do not want to show the user the current password (especially its hash).
Therefore, I created two properties in the model

public $password;
    public $password_repeat;
function rules(){
return [ ['password_repeat', 'compare', 'compareAttribute' => 'password']];
}

Here is my form
<?php $form = ActiveForm::begin(); ?>


        <?= $form->field($user, 'username') ?>
        <?= $form->field($user, 'email') ?>
        <?= $form->field($user, 'password')->passwordInput() ?>
        <?= $form->field($user, 'password_repeat')->passwordInput() ?>

        <div class="form-group">
            <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
        </div>
    <?php ActiveForm::end(); ?>

In order for all this to work well, I had to do this in the controller:
$user_id = Yii::$app->getUser()->id;
        $user = User::findOne($user_id);
        $post = Yii::$app->request->post();
        if(isset($post['User']['password'])){
            $user->setPassword(Yii::$app->request->post('password'));
            unset($post['User']['password']);
            unset($post['User']['password_repeat']);
        }
        if ($user->load($post) && $user->validate()) { .....

I have to use anset otherwise I get the error "Password must be repeated exactly." (although I enter two lonely passwords).
All this painfully looks like a bicycle.
Question:
How to do this operation correctly?
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
LIAL, 2015-01-30
@LIAL

And why do you need all this:

if(isset($post['User']['password'])){
            $user->setPassword(Yii::$app->request->post('password'));
            unset($post['User']['password']);
            unset($post['User']['password_repeat']);
        }

In theory, it is redundant, you have a validation rule, and it will work in if. If everything is fine, you get inside if
And try to replace the validation rule with this:
['password', 'compare']
judging by the description https://github.com/yiisoft/yii2/blob/master/docs/g...
// validates if the value of "password" attribute equals to that of "password_repeat"
['password', 'compare'],
this should be enough

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question