【问题标题】:CakePHP Security - Prevent Form InjectionCakePHP 安全性 - 防止表单注入
【发布时间】:2013-07-29 23:06:36
【问题描述】:

我目前有 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']);
        }
    } 

【问题讨论】:

标签: php security cakephp


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-01-16
    • 2021-04-08
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    相关资源
    最近更新 更多