How to change menus on sidebar of Admin LTE as per roles in yii2?

1k views Asked by At

I am using Yii2 basic.

I have Employee table and I have assigned Employee model to user application component as follows in config file:

'user' => [
            'identityClass' => 'app\models\Employee',
            'enableSession' => true,
          ],

I have also created permissions, roles and assigned roles to employees using RBAC.

1. Now when employee whose role is admin logs in, he can see foll menus on sidebar of Admin LTE:

  1. Masters
  2. Employee
  3. Employee Training
  4. SHGProfile
  5. Survey

When employee whose role is fieldofficer logs in, he also sees above menus on sidebar. Fieldofficer should only see foll menus:

  1. My Profile
  2. SHGProfile

How to change the menus on sidebar of Admin LTE as per roles of the employees?

2. Employee should be able to log in to the system only if role is assigned to employee. How to accomplish this?

1

There are 1 answers

0
iamsourabhh On

I am kind of new to Yii 2, did something like this, last week. Hope it helps.

  • You can use Rbac to accomplish the task you want to. To know more about RBAC: https://en.wikipedia.org/wiki/Role-based_access_control

  • There is a Yii 2 plugin to implement RBAC in your system. https://github.com/dektrium/yii2-rbac

  • You can assign roles to users. And give permissions to those roles, basically it is a parent child kin of relationship.

  • Whenever you create a new user assign permission to it as follows:

    $auth = Yii::$app->authManager;
    $admin = $auth->getRole('admin');
    $auth->assign($admin, 1); // the second parameter is user id
    
  • Assign permission to a role:

    $auth = Yii::$app->authManager;
    $admin = $auth->getRole('admin');
    $permCheckAdmin = $auth->createPermission('permCheckAdmin');
    $permCheckAdmin->description = 'Check if admin';
    $auth->add($permCheckAdmin);
    $auth->addChild($admin, $permCheckAdmin);
    
  • Check if a user has permission or not using:

    Yii::$app->user->can('permCheckAdmin');

  • You can assign permissions to admin and employee and use action according to the permission.

Hope it helps