Reputation: 2632
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 restAction
s 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 restAction
s.
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?
Upvotes: 1
Views: 750
Reputation: 2632
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...
Upvotes: 1
Reputation: 7886
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;
Upvotes: 1