【问题标题】:How to make sure a user can only see and access their own data in Yii如何确保用户在 Yii 中只能查看和访问自己的数据
【发布时间】:2012-06-17 00:32:40
【问题描述】:

在 Yii 中,有没有最好的方法来确保用户只能在 Yii 中查看和访问他们自己的数据?

我认为管理员应该可以看到任何东西,但现在,我稍后会越过那座桥。

谢谢

【问题讨论】:

  • 给出一些你尝试过的代码或者db table sample。

标签: security yii authorization


【解决方案1】:

查看范围。默认范围将是您的朋友: http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes

因为 defaultScopes 数组在函数内部,你也可以做有条件的默认作用域:

public function defaultScope()
{
    $t=$this->getTableAlias(false,false);

    if(Yii::app()->user->notAdmin()) {
        return array(
            'condition'=>"$t.<column_name> = :<columnName>",
            'params'=>array(':<columnName>'=>Yii::app()->user->notAdmin),
        );
    }
    else return array();
}

编辑:请注意,如果您不小心,这可能会给您带来麻烦。见this issue on the Yii site for more info

【讨论】:

  • 是的,但是这并不能完全解决问题。它让我更接近,这就是我当时投票支持的原因。
【解决方案2】:

Yii 不可能为你做这件事,你会自己做,但它相当简单。

您可以考虑范围,或查看关系并将它们全部基于当前用户。例如,要获取用户的所有帖子,您可以:

$posts = Post::model()->findAll();    //WRONG

$posts = Yii::app()->user->posts();   //RIGHT (Should define the relation in the User model)

【讨论】:

    【解决方案3】:
    猜你喜欢
    • 2016-06-19
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多