Search code examples
yiirbac

How to pass parameters to the rbac rule when using a permission name in yii\filter\AccesControl?


I want to limit all actions in a controller to the user who has a specific permission, in my case updatePost that is attributed to the author rôle depending on an AuthorRule. The controller aims at assigning translators to posts, not creating or updating the posts themselves.

The rule only verifies that the user is the creator of the post using a param whose name is author_id and value is the value of the author_id attribute of the post. Up to now, all this is common stuff.

I know I could check the

 Yii::$app->user->can('updatePost', ['author_id' => <a value>]) 

function's result in each action. Nevertheless, I read in Yii's guide that the authorisation name (updatePost) could also be given in the behavior like this:

return [
    'access' => [
        'class' => AccessControl::className(),
        'rules' => [
            [
                'allow' => true,
                'actions' => ['index','create', 'view', 'update'],
                'roles' => ['updatePost'],
            ],

and that in this case the AuthorRule's execute method will be called.

My question is: " What is the exact syntax in this case to pass the author_id to the AuthorRule's execute function ?"


Solution

  • You can not pass parameters like that. I guess it's not prepared for parameters because usually you don't know the exact values during this step (these are usually passed as arguments to the action).

    Move this check to the action or if you do know the value use matchCallback like:

    'matchCallback' => function ($rule, $action) {
        return Yii::$app->user->can('updatePost', ['author_id' => <a value>]);
    }