1

I am using RBAC in my yii2 basic application to assign module to users based on their roles.

I store role id and user_id in auth_assignment table.

Now if i change role of user during update. I have to change it also in auth_assignment table. Now I want to delete all entries of that user from auth assignment and add new entries in table.

The problem is that i cannot find any RBAC function to update auth_assignment table data or to delete auth assignment table data.

There is a function in Yii2 Documentation removeAllAssignments() but it truncates the whole table i only want to delete entries for perticular user.

Is there any function available for that?

Ninja Turtle
  • 1,293
  • 2
  • 24
  • 50

2 Answers2

1

Yes, there is.

assign() assigns role to a user.
revoke() revokes role from a user.
revokeAll() revokes all roles from a user.

To get the list of all roles assigned to a user you can use getRolesByUser().

Bizley
  • 17,392
  • 5
  • 49
  • 59
0

Assume the role name is being sent from the form and you are storing the value in the 'role' field, then add this to your model.

This will remove the existing assigments, and assign the new ones.

public function afterSave($isInsert, $changedOldAttributes)
{

    // Update the user role in the RBAC layer
    // Purge the user tokens when the password is changed
    if (array_key_exists('role', $changedOldAttributes)) {

        $auth = Yii::$app->authManager;

        $auth->revokeAll($this->id );

        $role = $auth->getRole($this->role);

        $auth->assign($role, $this->id);
    }
        return parent::afterSave($isInsert, $changedOldAttributes);
    }
crafter
  • 6,246
  • 1
  • 34
  • 46