如何在不进行手动验证的情况下验证对象是否属于已登录用户?

时间:2015-07-07 22:08:52

标签: validation yii2

我在Yii2 Active Record中使用parent-> child(master-> detail)关系

当用户想要编辑他的记录时,我必须在所有编辑操作中验证它是否属于用户:

  

关系:客户(1)---> (n)评论

控制器

class ClientController extends \yii\web\Controller
{

    public function actionEditComment($id) {
        // Validate if the edited comment belongs to the user
        if (($comment = Comment::findOne($id)) == null ||
            ($comment->client0->id != Yii::$app->user->id) ) {
                throw new NotFoundHttpException('The requested page does not exist.');
        }
        if ($comment->load(Yii::$app->request->post()) && $comment->save()) {
            return $this->redirect(['view-comment', 'id' => $comment->id]);
        } else {
            return $this->render('edit-comment', ['comment' => $comment]);
        }
    }
}

模型

class Comment extends ActiveRecord {
    public function getClient0() {
        return $this->hasOne(Client::className(), ['client' => 'id']);
    }
}

我必须将此代码放入编辑和删除操作中,以防止用户更改注释ID,从而编辑或删除任何不属于他的记录

我的最后一个选择是始终验证模型中的所有物并在编辑和删除操作中调用它,但我想知道,如果还有其他方法可以使用它吗?

1 个答案:

答案 0 :(得分:2)

您可以在控制器中使用AccessControll filter进行此类检查。并在matchCallback参数中查看它。一个例子:

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['edit-comment', 'delete-comment'],
            'rules' => [
                [
                    'allow' => true,
                    'roles' => ['@'],
                    'matchCallback' => function($rule, $action){
                        $id = Yii::$app->request->get('id');
                        if (($comment = Comment::findOne($id)) == null ||
                            ($comment->client->id != Yii::$app->user->id) ) { 
                                 return false;
                        } else { 
                            return true; 
                        }
                    }
                ],
            ],
        ],
    ];
}

所以现在yii2会在运行之前调用此验证' edit-comment'和'删除 - 评论'动作。