简体   繁体   中英

How to make sure a user can only see and access their own data in Yii

In Yii, is there a best way to make sure a user can only see and access their own data in Yii?

I thought an Admin should be able to see anything, but for now, I'll cross that bridge later.

Thanks

Look into scopes. Default scopes will be your friend: http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes

Because the defaultScopes array is inside of a function, you can also do conditional default scopes:

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

Edit: Note that this can get you in trouble down the road if you aren't careful. See this issue on the Yii site for more info .

There is no way Yii will do this for you, you'll do it on your own, but it's fairly straight forward.

You can consider scopes, or look into Relations and base them all on current user. For example, to get all posts by a user, you can do:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM