CakePHP安全 - 防止表单注入

时间:2013-07-30 00:02:07

标签: php security cakephp

我目前有一个表,用户看起来像这样

|**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']);
        }
    } 

1 个答案:

答案 0 :(得分:1)

save()方法的第三个参数允许您定义要保存的字段列表。 Model::save() docs

$this->User->id = $this->Auth->user('id'); $this->User->save($this->request->data, true, array('username', 'email'))