我目前有 1 个表,用户看起来像这样
|**id**|**username**|**password**|**role**|**email**|
我正在使用 CakePHP 的表单助手来自动填写可编辑的表单字段。我正在创建一个编辑页面,用户可以在其中更改用户名/密码/电子邮件,但不能更改他们的角色。我目前正在检查以确保用户没有在请求中注入角色 POST 字段,并且想知道是否有更好的方法来做到这一点?在这种情况下,使用这么小的表是微不足道的,但我可以看到这在具有大量列的字段/表上变得令人厌烦。我当前的编辑操作如下所示。
public function edit($id = null)
{
$this->User->id = $id;
if(!$this->User->exists())
{
throw new NotFoundException('Invalid user');
}
$userToEdit = $this->User->findById($id);
if(!$userToEdit)
{
throw new NotFoundException('Invalid user');
}
if($this->getUserRole() != 'admin' && $userToEdit['User']['owner'] != $this->Auth->user('id'))
{
throw new ForbiddenException("You do not have permission to edit this user");
}
if($this->request->is('post') || $this->request->is('put'))
{
//Do not reset password if empty
if(empty($this->request->data['User']['password']))
unset($this->request->data['User']['password']);
if(isset($this->request->data['User']['role']))
unset($this->request->data['User']['role']);
if($this->User->save($this->request->data))
{
$this->set('success', true);
}
else
$this->set('success', false);
}
else
{
$this->request->data = $this->User->read();
//Prevent formhelper from displaying hashed password.
unset($this->request->data['User']['password']);
}
}