Turgs
Turgs

Reputation: 1799

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

Upvotes: 3

Views: 2133

Answers (3)

acorncom
acorncom

Reputation: 5955

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.

Upvotes: 9

mjalajel
mjalajel

Reputation: 2201

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)

Upvotes: 2

Related Questions