Questions
Questions

Reputation: 69

RBAC tables in yii2

  1. How to create permissions, roles and rules in yii2 using gii?
  2. How to assign roles in yii2?

How to implement all these using below 4 tables?

  1. auth_item
  2. auth_item_child
  3. auth_assignment
  4. auth_rule

Consider the case:

There are two users Admin and FieldOfficer:

I have SHGProfile CRUD application.

FieldOfficer can access only create and view actions in SHGProfile. Whereas Admin can access all create, view, update and delete actions.

Here Roles are Admin and FieldOfficer. Permissions are createGroup, viewGroup, updateGroup, and deleteGroup

Here in which table we need to create Roles and Permissions and how to assign it to user?

Upvotes: 0

Views: 1211

Answers (1)

Lakhan Singh
Lakhan Singh

Reputation: 69

I will explain here which tables contains role and permissions and how to assign permissions to user :

  1. Insert your all roles in auth_item table i.e Admin , FieldOfficer , createGroup , viewGroup , updateGroup , deleteGroup.

  2. Assign createGroup, viewGroup, updateGroup, and deleteGroup to Admin role in auth_item_child table.

  3. Assign createGroup, viewGroup to FieldOfficer role in auth_item_child table.

  4. Assign permission to user in auth_assignment table with role id and user id . Assign only parent role like Admin or FieldOfficer.

  5. Now in your controller use AccessControl for give access to logged in user as per their role

    public function behaviors()
    {
    
       return [
          'access' => [
          'class' => \yii\filters\AccessControl::className(),
          'only' => ['create', 'view' , 'update' , 'delete'],
          'rules' => [
    
              // allow all actions to Admin role users
              [
                  'allow' => true,
                  'actions' => ['create', 'view' , 'update' , 'delete'],
                  'roles' => ['Admin'],
              ],
              // allow create , view actions to FieldOfficer role users
              [
                  'allow' => true,
                  'actions' => ['create', 'view'],
                  'roles' => ['FieldOfficer'],
              ],
              // everything else is denied
           ],
         ],
       ];
       }
    

Upvotes: 0

Related Questions