Yii2 rest: checkAccess on restAction

萝らか妹 提交于 2019-12-11 04:47:40

问题


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



来源:https://stackoverflow.com/questions/48666986/yii2-rest-checkaccess-on-restaction

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!