V
V
Villarou2015-10-13 11:46:14
Yii
Villarou, 2015-10-13 11:46:14

User role at registration (RBAC). How to do it right?

There is a Yii2 Advanced Template. For the convenience of working with RBAC, the yii2-admin module was taken . authManager is defined as:

'authManager' => [
            'class' => 'yii\rbac\DbManager',
]

For simplicity, set in common\config\params.php:
'defaultRole' => 'User'.
Actually according to The registration dock shows the code that needs to be placed in the signup method of the SignupForm modules. With my slight modification, it looks like this:
...
if ($user->save()) {
    $auth = Yii::$app->authManager;
    $defaultRole = $auth->getRole(Yii::$app->params['defaultRole']);
    $auth->assign($defaultRole, $user->getId());

    return $user;
}

Actually questions.
1) Is it correct to set the default role like this? Is there a "right way"?
2) Do I understand correctly that adding a role to a user is better through afterSave in the user model?
3) Is it possible to call afterSave only on the signup method in SignupForm?
PS Yii see in the eye 4 days. Please do not kick hard if something is wrong.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Donkovtsev, 2015-10-14
@VirmarY

1) I won't say for that.
2) Yes, but for reinsurance, you can make it still a transaction, in case the user was added, but the rights were not added for some reason. after successfully adding a user, we add rights and, if an error occurs, then rollback the transaction.
3)

public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);

        if($insert) {
            $auth = Yii::$app->authManager;
            $role = $auth->getRole(self::ROLE_USER);
            $auth->assign($role, $this->id);
        }

        Yii::$app->authManager->invalidateCache();
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question