How to ensure users can only access their own records?

For example in my database I have a field called "assigned_to", this contains the integer value of the user ID that the record is assigned to.

I want to configure accessRules() so that the users can only access their own records (when they are logged in) and not anybody elses.

Not sure if this is the best way to tackle the problem, but I would do something similar to the following in your view controller




public function accessRules()

{

	return array(

		array('allow',

			'actions'=>array('show'),

			'expression'=>$databaseModel->assigned_to==Yii::app()->user->id ? true : false,

		),

		array('deny',  // deny all users

			'users'=>array('*'),

		),

	);

}

OK I did that but it breaks the ‘authenticated’ users functionality. Here is my code:


public function accessRules()

{

	$model=Application::model()->findByPk($id);

	

	return array(

		array('allow',

			'actions'=>array('list', 'view'),

			'expression'=>$model->assigned_to==Yii::app()->user->id ? true : false,

		),

		array('allow',

			'actions'=>array('admin'),

			'users'=>array('@'), 

		),

		array('deny',

			'users'=>array('*'),

		),

	);

}

Where I try to access index.php?r=admin, the error message I get says: The requested page does not exist.

Anyone able to advise?

I think what’s happening is that $model is null on the ‘admin’ view. But it should ignore that really.

Reorder your access rules and put the one you want to give priority to at the top