Yii2 rest: checkAccess on restAction

2019-07-29 03:51发布

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?

标签: rest yii2
2条回答
闹够了就滚
2楼-- · 2019-07-29 04:19

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;

查看更多
ら.Afraid
3楼-- · 2019-07-29 04:20

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...

查看更多
登录 后发表回答