Basically, I’m trying to restrict a user to update posts that only he has made. I’ve gone through the forums to find the simplest way to achieve that, and for the most part I’ve succeeded.
So far, whenever I go to index.php/r=story/update&id=7, if the users ID matches the ID on record it allows them to update the post; otherwise they’re hit with a 403.
However, the problem arises when I go to view all the stories (index.php/r=story/index). It hits me with an Undefined Index: id. I assume it’s because on the index page, there is no ID to get from. Does anyone have a better solution to solve this? I’ve looked at RBAC but I felt that it was too much for what I was trying to achieve; Unless, I’m mistaken.
Here’s the code I’m working with:
public function accessRules()
{
$userid = $this->loadModel($_GET['id'])->user_id;
return array(
...
array('allow',
'actions'=>array('update'),
'expression' => '(Yii::app()->user->id) =='.$userid,
),
...
);
}
yes, you’re right about the index not containing the GET id. For this reason, I would do the validation in the actionUpdate method. I.e. not in the access rules. You could also write a filter.
public function actionUpdate($id)
{
$model = $this->loadModel($id);
$userId = Yii::app()->user->id;
if ($model->user_id != $userId)
{
// throw exception here.
}
if (isset($_POST['ModelName']))
{
...
Doing the validation in a controller/filter allows for a more flexible option to redirect, log, scorn the user. If you just need to block and show a 403, use the previous solutions.