Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 816
Turgs Avatar asked Jan 25 '26 20:01

Turgs


2 Answers

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.

like image 106
acorncom Avatar answered Jan 28 '26 14:01

acorncom


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)
like image 28
mjalajel Avatar answered Jan 28 '26 14:01

mjalajel