Yii2 rest: checkAccess on restAction

2019-07-29 03:50发布

问题:

After tackling this other question we would now like to check if the authenticated user can view, update or delete an existing record. Since checkAccess() is called by default in all restActions the following seemed the most logic thing to try:

public function checkAccess($action, $model = null, $params = []) {
    if(in_array($action, ['view', 'update', 'delete'])) {
        if(Yii::$app->user->identity->customer->id === null
         || $model->customer_id !== Yii::$app->user->identity->customer->id) {
            throw new \yii\web\ForbiddenHttpException('You can\'t '.$action.' this item.');
        }
    }
}

But the API seems to ignore this function. We added this function in our controller. The actions (view, update and delete) are the default restActions.

Our BaseController sets actions like this:

...
'view' => [
    'class' => 'api\common\components\actions\ViewAction',
    'modelClass' => $this->modelClass,
    'checkAccess' => [$this, 'checkAccess'],
    'scenario' => $this->viewScenario,
],
...

Are we forgetting something?

回答1:

Just add the following inside your custom action before executing any other code as it was done in the default view action (see source code here):

if ($this->checkAccess) {
    call_user_func($this->checkAccess, $this->id, $model);
}

note: $this->checkAccess is defined in parent yii\rest\Action so your custom ActionView class need to either extend yii\rest\Action or redefine the variable public $checkAccess;



回答2:

We obviously should have seen that the viewAction is not the default but an altered api\common\components\actions\ViewAction ... Not sure how we missed that...



标签: rest yii2