比方说,我有User
模型和Post
模型。 Post
模型包含字段user_id
。 User
有$hasMany
on Post
and Post
has $belongsTo
on User
。如何防止用户编辑其他人的帖子
我有一些文章编辑动作:
PostsController::edit($id) {
if($this->request->isPost())
{
$this->Post->id = $id;
$this->Post->save();
}
$post = $this->Post->read($id);
$this->set(compact('post'));
}
我用AuthComponent
登录的用户。
我该如何防止用户编辑别人的帖子?功能/选项中是否有任何蛋糕构建?因为some1可以使用任何ID登录并发布编辑操作。它甚至没有保存发布数据的情况 - 假设发布是私人的(只有所有者应该看到它) - 当有人打电话发布/编辑/ some_id时,它会看到这篇文章的编辑窗体...
更容易的方法是只在编辑行动开始补充一点:
$this->Post->id = $id;
if($this->Post->readField('user_id') != $this->Auth->user('id'))
{ //trigger error or redirect }
但我将不得不在这个更新/读取属于某个用户的任何数据的每个动作的开头添加这一点。所以我正在寻找更优雅的方式来做到这一点。
其实,有避免添加一行的一种方式,这或许可以通过编辑操作在一个地方比较用户ID来解决,比如'的AppController :: isAuthorized()'或'beforeFilter()'。 –