防止用户在 Yii 中查看另一个用户个人资料

Preventing user from viewing another user profile in Yii

我对我的应用有一些疑问。如何防止用户查看其他用户个人资料? 我的意思是,用户只能查看自己的个人资料。如果用户 123 已登录,他在 'view&id=123' 中被允许但在 'view&id=234' 等中被拒绝

我知道如何从视图页面执行此操作,但是,我可以从我的控制器中拒绝它吗?我正在考虑使用表达式,但我无法正确使用。这是我的代码

array('deny',
        'actions'=>array('view'),
        'expression'=>'$user->getName()!=??',
),

替换“??”的正确表达方式是什么部分? 我尝试使用 $id(actionView 参数)但它向我显示错误..

我通常在控制器级别执行此操作,我会这样做:

public function actionView($id){
 if($id != Yii::app()->user->id) {
    throw new CHttpException('403','You are not allowed to see this page');
 }

 //Continue with the code
}

假设您已将登录的用户 ID 存储在 Yii:app()->user 变量中。

这也可能有效:

array('deny',
    'actions'=>array('view'),
    'expression'=>'$_GET["id"] != Yii::app()->user->id',
),

使用选项 allow 更容易得到你想要的。

         'actions' => ['view', 'list-post', 'unsubscribe'],
         'allow' => $_GET['id'] == Yii::$app->user->id,

最佳做法是创建自定义过滤器(在 application.components.controller 中,如果您多次使用它):

public function filterCheckOwner($filterChain)
{
    if ($id=Yii::app()->getRequest()->getParam('id'))
    {        
        if($id != Yii::app()->user->id)
            throw new CHttpException('403','You are not allowed to see this page');
        else
            $filterChain->run();
    }
}

然后只需在 filters() 方法中添加必须 运行 的同名操作(不带 'filter'):

public function filters()
{
    return array(
        ...
        'checkOwner + view, update, whatever', 
        ...
    );
}