gugoan
gugoan

Reputation: 780

Prevent show data from another user

How to prevent all detailView show data from another user ??

For example, this happens when you type an product ID of another user in the URL. The detailView shows the details of the product normally, however belongs to another User, and may even change it and delete it.

Upvotes: 1

Views: 415

Answers (3)

You can do something like this in the controller if you don't want to use RBAC :

protected function findModel($id)
{
    //Check if the author is the current user
    if (($model = Product::findOne($id)) !== null && $model->author_id==Yii::$app->user->id) { 
        return $model;
    } else {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

Like this users which are not the author can't view, update or delete the product. http://www.yiiframework.com/forum/index.php/topic/61915-prevent-show-data-from-another-user/page__view__findpost__p__274644

Upvotes: 1

jovani
jovani

Reputation: 849

An example to what Mihai have suggested.

    public function behaviors()
    {
        return [
            'accessControl' => [
                'class' => \yii\filters\AccessControl::className(),
                'rules' => [
                    [
                        'actions'       => ['view'],
                        'allow'         => true,
                        'matchCallback' => function () {
                            $request = \Yii::$app->request;
                            $user = \Yii::$app->user->identity;
                            $product = Product::findOne($request->get('id'));

                            if ($user && $product->owner_id == $user->id) {
                                return true;
                            }

                            return false;
                        }
                    ],
                    [
                        'allow' => false,
                        'roles' => ['*'],
                    ],
                ],
            ]
        ];
    }

Upvotes: 1

Mihai P.
Mihai P.

Reputation: 9367

Several options:
1) simplest one, in the controller before showing the view check that the current user can see the product. If he cannot redirect him (by throwing an error) to a 404 page (or whatever error you want to show).
2) use RBAC to set up roles and what those roles can do. This is the most professional option
3) you may be able to modify the accessfilter to do this too too

If you need to ask how to do this go with option 1.

If you want option 2 or 3 start by reading this http://www.yiiframework.com/doc-2.0/guide-security-authorization.html

Upvotes: 1

Related Questions