Answer the question
In order to leave comments, you need to log in
How to restrict access to other people's records in the RESTful API in Yii2?
Good day everyone!
I read the documentation for site Yii2 on RESTful API, Google searched, but did not find a solution.
You can restrict access to editing and deleting other people's records by overriding checkAccess, for example:
public function checkAccess($action, $model = null, $params = [])
{
if ($action === 'update' || $action === 'delete') {
if ($model->createdBy !== \Yii::$app->user->id)
throw new \yii\web\ForbiddenHttpException(sprintf('You can only %s lease that you\'ve created.', $action));
}
}
Answer the question
In order to leave comments, you need to log in
To determine the access rights to view the post (/api/posts/1), use checkAccess as well.
To select records of available users (/api/posts), override the prepareDataProvider property of actionIndex in the controller, like this:
public function actions()
{
$actions = parent::actions();
$actions['index'] = [
'class' => 'yii\rest\IndexAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'prepareDataProvider' => function ($action) {
return new ActiveDataProvider([
'query' => MyModel::findByAuthor(Yii::$app->user->id);
]);
}
]
return $actions;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question