keeg
keeg

Reputation: 3978

Yii2: Apply different AccessRule filter to specific actions in the same controller

Is it possible to have two different rule sets \yii\filters\AccessRule in behaviors() to control different actions? Something like:

public function behaviors()
{
    return [

        // Standard access
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'actions' => ['create'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ],

        // fancy access
        'accessView' => [
            'class' => AccessControl::className(),
            'ruleConfig' => [
                'class' => MyFancyAccessRule::className(),
            ],
            'rules' => [
                [
                    'actions' => ['view'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ],
    ];
}

In this case I want a different access rule to apply to the view action as it has an extra check...

Upvotes: 1

Views: 292

Answers (1)

rob006
rob006

Reputation: 22174

Yes, you can attach the same behavior multiple times like in your example (AccessControl is a behavior for controlling access to specified action).

But you don't need to. You can use only one AccessControl behavior and configure your rule directly in rules config:

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'actions' => ['create'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
                [
                    'class' => MyFancyAccessRule::className(),
                    'actions' => ['view'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ],
    ];
}

Upvotes: 3

Related Questions