V
V
Vladimir Perfiliev2017-05-21 13:35:33
Yii
Vladimir Perfiliev, 2017-05-21 13:35:33

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));
    }
}

But at the same time, nothing prevents the user from making a request like GET /api/posts or even GET /api/posts/1 and viewing someone else's post.
How would you limit it by adding the condition ->where(['createdBy' => \Yii::$app->user->id]) if necessary ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2017-05-22
@Persoff

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;
}

D
Dmitry, 2017-05-21
@slo_nik

Good afternoon.
There is a good video that explains everything.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question