I create a controller which extends yii/rest/ActiveController
. In this scenario I will use index and view endpoint, rest of action will be unset. The code of my controller like below
<?php
public function actions()
{
$actions = parent::actions();
unset($actions['view'], $actions['create'], $actions['update'], $actions['delete']);
$actions['index'] = [
'class' => 'yii\rest\IndexAction',
'modelClass' => $this->modelClass,
'checkAccess' => $this->checkAccess('index', $this->modelClass),
'prepareDataProvider' => function () {
return new ActiveDataProvider([
'query' => $this->modelClass::find(),
'pagination' => false,
]);
},
];
return $actions;
}
/**
* Checks the privilege of the current user.
*
* This method should be overridden to check whether the current user has the privilege
* to run the specified action against the specified data model.
* If the user does not have access, a [[ForbiddenHttpException]] should be thrown.
*
* @param string $action the ID of the action to be executed
* @param \yii\base\Model $model the model to be accessed. If `null`, it means no specific model is being accessed.
* @param array $params additional parameters
* @throws ForbiddenHttpException if the user does not have access
*/
public function checkAccess($action, $model = null, $params = [])
{
// check if the user can access $action and $model
// throw ForbiddenHttpException if access should be denied
// if ($action === 'view') {
// throw new ForbiddenHttpException(sprintf("You didn't have access to this endpoint."));
// }
if ($action === 'index') {
throw new ForbiddenHttpException(sprintf("You didn't have access to this endpoint. $action"));
}
}
/**
* View curent selected record.
* Override actionView from [[ActiveController]]
*
* @method GET | HEAD
*
*
* @return RefUnit
*
* @author @hoaaah
*/
public function actionView()
{
$this->checkAccess($this->action->id, $this->modelClass);
$model = $this->findModel();
// if ($this->checkAccess) {
// call_user_func($this->checkAccess, $this->id, $model);
// }
return $this->action->id;
}
Expected behavior of code above is when I access index it will throw ForbiddenException, when I access view it will give the right authorization. But when I access view, it throw ForbiddenException too.
What is the right way to override checkAccess in ActiveController?