Правила доступа Yii2 с использованием разных моделей

У меня проблемы с управлением доступом на основе ролей Yii2. В обычной настройке правило аутентификации имеет место, когда личность текущего пользователя. Вроде в документах написано. Авторизация

Как в моем случае настроить авторизацию (помимо базовой функции) с использованием другого набора моделей? Вот моя установка.

Таблица auth_assignment [item_name, user_id] из миграции rbac, user [id] из миграции yii2. Я создал новую таблицу assignment [user_id, связанную с user, rec_id, связанную с recognition из organization].

Это сценарий. У меня роли admin, organization-head, member. Как я могу проверить, принадлежит ли organization-head или member их собственному модулю распознавания; а не другие модули от других организаций-руководителей?

Я также использовал фильтр управления контекстным доступом по peixoto.

Вот мой код для проверки. RecognitionRule проверяет, существует ли пользователь, user_id совпадающий с идентификатором пользователя; и account_id равно rec_id. Второе условие говорит, принадлежит ли он к организации

/**
 * Checks if ID matches user passed via params
 */
class RecognitionRule extends Rule
{
    public $name = 'isRecognition';

    /**
     * @param string|integer $user the user ID.
     * @param Item $item the role or permission that this rule is associated with
     * @param array $params parameters passed to ManagerInterface::checkAccess().
     * @return boolean a value indicating whether the rule permits the role or permission it is associated with.
     */
    public function execute($user, $item, $params)
    {
        if(isset($params['recognition'])){ //Directly specify the model you plan to use via param
            $model = $params['recognition']; 
        }else{ //Use the controller findModel method to get the model - this is what executes via the behaviour/rules
            $id = Yii::$app->request->get('id'); //Note, this is an assumption on your url structure. 
            $model = Yii::$app->controller->findModel($id); //Note, this only works if you change findModel to be a public function within the controller.
        }
        return \common\models\Assignment::find()->where(['rec_id' => $model->id, 'user_id' => $user])->exists();
    }
}

Тем не менее, мне не разрешено выполнять действие. Любые подсказки?


person Community    schedule 23.07.2015    source источник


Ответы (1)


Я получил ответы. Я основывал свой ответ на поведении AccessRule и rbac\Rule $params

фрагмент правила распознавания

/**
 * @param string|integer $user the user ID.
 * @param Item $item the role or permission that this rule is associated with
 * @param array $params parameters passed to ManagerInterface::checkAccess().
 * @return boolean a value indicating whether the rule permits the role or permission it is associated with.
 */
public function execute($user, $item, $params)
{
    if(isset($params['recognition'])){ //Directly specify the model you plan to use via param
        $model = $params['recognition']; 
    } else{ //Use the controller findModel method to get the model - this is what executes via the behaviour/rules
        $id = Yii::$app->request->get('id'); //Note, this is an assumption on your url structure.
    }

    return \common\models\Assignment::find()->where(['rec_id' => $id, 'user_id' => $user])->exists();
}
}
?>

Контроллер распознавания

                [
                    'class' => 'common\rbac\ContextAccessRule',
                    'modelClass' => 'frontend\models\recognition',
                    'allow' => true,
                    'actions' => ['view','update'],
                    'roles' => ['viewOwnRecognition', 'updateOwnRecognition'],
                ],
            ],
        ],
    ];
person Community    schedule 23.07.2015