Some Difficulties With Password In User-Model

Hello,

my User-Model defines three differenct scenarios: login, create and update. First of all the relevant code:




class User extends ActiveRecord implements IdentityInterface

{

    public function rules()

    {

        return [

            // in every scenario

            ['username', 'required'],

            [['username', 'password', 'email'], 'filter', 'filter' => 'trim'],

            

            // in login scenario

            ['password', 'validatePassword', 'on' => ['login']],

            

            // login and create

            ['password', 'required', 'on' => ['login', 'create']],

            

            // in update or create scenario

            ['username', 'string', 'length' => [4, 50], 'on' => ['create', 'update']],

            ['username', 'unique', 'on' => ['create', 'update']],

            ['email', 'email', 'on' => ['create', 'update']],

            ['email', 'required', 'on' => ['create', 'update']],

        ];

    }

    

    public function scenarios()

    {

        return [

            'login' => ['username', 'password'],

            'create' => ['username', 'email', 'password'],

            'update' => ['username', 'email', 'password'],

        ];

    }

    

    public function hashPassword()

    {

        $this->password = Security::generatePasswordHash($this->password);

    }    


    // ...  

}

The login scenario works fine, but I have difficulties to implement the other two scenarios.

First of all what is the right place to hash passwords? At the moment I use the function User::hashPassword() in the controller after the input data got validated:




    public function actionCreate()

    {

        $model = new \app\models\User(['scenario' => 'create']);

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {

            $model->hashPassword();

            $model->save();

            return $this->redirect(['users/index']);

        } else {

            return $this->render('create', [

                'model' => $model,

            ]);

        }

    }



I was thinking of replacing User::hashPassword() by User::beforeSave() so the password is getting hashed automatically but I’m not sure if that’s the proper way.

Best regards,

okinez

Yes, beforeSave() is a good place to put it.