防止显示来自其他用户的数据

Prevent show data from another user

如何防止其他用户的所有 detailView 显示数据??

例如,当您在 URL 中键入另一个用户的产品 ID 时,就会发生这种情况。 detailView正常显示商品的详细信息,但是属于另一个用户,甚至可以更改和删除它。

几个选项:
1) 最简单的一个,在显示视图之前在控制器中检查当前用户是否可以看到产品。如果他无法将他重定向(通过抛出错误)到 404 页面(或您想要显示的任何错误)。
2) 使用RBAC 设置角色以及这些角色可以做什么。这是最专业的选择
3) 您也可以修改 accessfilter 来执行此操作

如果您需要询问如何执行此操作,请选择选项 1。

如果您想要选项 2 或 3,请先阅读本文 http://www.yiiframework.com/doc-2.0/guide-security-authorization.html

Mihai 建议的示例。

    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' => ['*'],
                    ],
                ],
            ]
        ];
    }

如果你不想使用 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.');
    }
}

非作者用户无法查看、更新或删除该产品。 http://www.yiiframework.com/forum/index.php/topic/61915-prevent-show-data-from-another-user/page__view__findpost__p__274644