rbac- check user permission

I’ve setup rbac and wonder if there are better ways to do the check in each controller actions.

For each action in the controller, I have the code





   public function behaviors()

    {

        return [

            'access' => [

                'class' => AccessControl::className(),

                // We will override the default rule config with the new AccessRule class

                'only' => ['index', 'view', 'create', 'update', 'delete'],

                'rules' => [

                    [

                        'allow' => true,

                        'roles' => ['@']

                    ],

                ],

            ],   

            'verbs' => [

                'class' => VerbFilter::className(),

                'actions' => [

                    'delete' => ['post'],

                ],

            ],

        ];

    }


   public function actionIndex()

    {

        if (!Yii::$app->user->can('read')) {

            throw new ForbiddenHttpException();

        }

        

        // do some useful things

    }


    public function actionCreate()

    {

       if (!Yii::$app->user->can('create')) {

            throw new ForbiddenHttpException();

        }

    }


    public function actionDelete()

    {

       if (!Yii::$app->user->can('delete')) {

            throw new ForbiddenHttpException();

        }

    }



Can I put the rbac permission check in behaviors (not sure if possible) ? My goal is reducing if check in each actions if possible.

I think you could consider using this extension:

mdmsoft/yii2-admin

It allows you to replace the default Access Control Filter with its own which enables the access control filtering using the special "permissions" called "routes".

For instance, you can define 2 routes whose names are "some-controller/index" and "some-controller/view", and then add them as the children of the "read" permission. And now you can restrict the access to the index and view actions to the user with "read" permission.

thanks, i will check it out

Yes you can. I do the following:


            'access' => [

                'class' => AccessControl::className(),

                'rules' => [

                    [

                        'allow' => true,

                        'roles' => ['@'],

                        'matchCallback' => function ($rule, $action) {

                            // find if the user has acces to the controller action

                            return Yii::$app->user->can(Yii::$app->controller->id.'-'.$action->id);

                        },

                    ],

                ],

            ],

The code above gets the controller and action id and uses it to check if the user has specific rights. Perhaps it could be done better, but this works fine for me.

cool, i try it out. thanks for the tip