Restrict users to their own records

Maybe I just haven’t been looking in the right places, but I’m surprised I haven’t seen much documentation on this subject.

I am working on an application where users can enter and save a list of books (and information on the book) that they own. In the database, I save the ID of the user that has provided the record.

What I am looking to do from there, which is typical of such an application, is to restrict users from only seeing their records (i.e, their books).

What is the best way to go about doing this? Is it possible to do it within accessRules() in the controller?

You could define access rules via RBAC (http://www.yiiframework.com/doc/guide/1.1/en/topics.auth#role-based-access-control) where you can check if a user is the owner of the book and should therefore be allowed to see it. If your application has more than one restriction this is a good start. If it is only about the books and their owners than RBAC could be overkill. A possible solution could be to define a defaultScope on your Book-ActiveRecord class where you only receive books with the user_id of the currently logged in user.

Default scopes: http://www.yiiframework.com/doc/guide/1.1/en/database.ar#default-scope

Named scopes: http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes

simple example:


public function defaultScope()

{         

    return array(

        'condition'=>'user_id='.Yii::app()->user->id,         

    );     

}



Now every time a function is returning book models it is using the default scope. This could lead to errors when you want to display the index page with all books and nobody is currently logged in but I think you got the point (simply check that they have to be logged in via simple access rules as you already stated). In this case you could also use named scopes and only use them in the actions that need that.

Example index action with named scope ‘usersBooks()’:


public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider(Book::model()->usersBooks());

		$this->render('index',array(

			'dataProvider'=>$dataProvider,

		));

	}

greetings,

Haensel

Thanks for pointing me in the right direction!