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?
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):
note:
$this->checkAccess
is defined in parentyii\rest\Action
so your custom ActionView class need to either extendyii\rest\Action
or redefine the variablepublic $checkAccess;
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...