Yii2。按角色访问控制。如何添加' OR'条件?

时间:2017-09-14 14:23:09

标签: yii yii2 yii2-advanced-app yii2-basic-app yii2-validation

我有一个具有以下访问限制的控制器:

'access' => [
                'class' => AccessControl::className(),
                'only' => ['index', 'view', 'create', 'update', 'delete'],
                'rules' => [
                    [
                        'actions' => ['index', 'view'],
                        'allow' => true,
                        'roles' => [RbacComponent::VIEW_EXPENSES_ACCOUNTS_KEY],
                    ],
                    [
                        'actions' => ['create'],
                        'allow' => true,
                        'roles' => [RbacComponent::CREATE_EXPENSES_ACCOUNTS_KEY],
                    ],
                    [
                        'actions' => ['update'],
                        'allow' => true,
                        'roles' => [RbacComponent::EDIT_EXPENSES_ACCOUNTS_KEY],
                    ],
                    [
                        'actions' => ['delete'],
                        'allow' => true,
                        'roles' => [RbacComponent::DELETE_EXPENSES_ACCOUNTS_KEY],
                    ],
                ],
            ],

如何添加' OR ' \ Yii :: $ app-> user-> identity-> isOwner()所有规则?

我尝试使用此变体:

            [
                'actions' => ['index', 'view'],
                'allow' => true,
                'roles' => [RbacComponent::VIEW_EXPENSES_ACCOUNTS_KEY],
                'matchCallback' => function ($rule, $action) {
                    return \Yii::$app->user->identity->isOwner();
                }
            ],

但是,在这种情况下,它将是' AND '并且不会工作。

我认为这种变体可行:

            'rules' => [
                [
                    'actions' => ['index', 'view', 'create', 'update', 'delete'],
                    'allow' => true,
                    'roles' => ['@'],
                    'matchCallback' => function ($rule, $action) {
                        if ($action == 'index') {
                           if (\Yii::$app->user->identity->isOwner() || \Yii::$app->user->can(RbacComponent::VIEW_EXPENSES_ACCOUNTS_KEY)) {
                              return true;
                          }
                        }

                        ... other actions

                    }
                ],

但也许有更好更简单的方法?

2 个答案:

答案 0 :(得分:1)

您只需使用回调添加规则:

$user->newSubscription('main', 'monthly')
        ->trialDays(10)
        ->create($creditCardToken);

答案 1 :(得分:0)

这应该有效

[
    'allow' => true,
    'roles' => ['owner'],
],