gugoan
gugoan

Reputation: 780

Set user permissions on each module in Yii2

I would like to set user permissions on each module. Each module would have its table with the permissions. What is the most recommended way to do this?

Reason: My application has some optional modules for only a few clients.

UPDATE Something like:

Table: mod_inventory_permission

id int
User_id int
Read_permission boolean
Write_permission boolean
Admin_permission boolean

Upvotes: 0

Views: 1187

Answers (2)

Dani
Dani

Reputation: 925

Yes you can do it by using Rbac which facilitate you to restrict user in same application to limited modules,controllers, or actions You have to follow the following step i hope it will help you.
I suggest you to use the auth_ tables provided by yii2 for rbac
step 1: import all auth tables
step 2: Create different roles in auth_item tables with type = 1 and all permission with type = 2 Note Please make sure you enter your permission in some specific pattern,i am using module/controller/action, its up to you how you are going to implement it.
step 3: Create generic controller and extend all of your controller from this generic controller, In your generic controller you have to check whether the user is allow to access the module,controller or action he/she want to access of not.

public function beforeAction($action) {
        $module = Yii::$app->controller->module->id;
        $controller = ucfirst(Yii::$app->controller->id);
        $action = Yii::$app->controller->action->id;
        if (Yii::$app->user->can($module)) {

            if (Yii::$app->user->can($module . '/' . $controller)) {
                return true;
            } 
            if (Yii::$app->user->can($module . '/' . $controller . '/' . $action)) {
                return true;
            } 
else {
                throw new \yii\web\HttpException(403, 'You are not allowed to view this page');
            }
        } else {
            throw new \yii\web\HttpException(403, 'You are not allowed to view this page');
        }
    }

The beforeAction function implement 3 layer authentication you can change it according to your requirements.... i hope it will help you

Upvotes: 0

Wajid
Wajid

Reputation: 2341

You can use RBAC for it! you can set different modules in it and different permission for each module.

Upvotes: 1

Related Questions