jbq
jbq

Reputation: 191

CakePHP Security - Prevent Form Injection

I currently have 1 table, Users which looks like this

|**id**|**username**|**password**|**role**|**email**|

I'm using CakePHP's form helper to automatically fill in editable form fields. I'm creating an edit page in which users can change there username/password/email, but should NOT be able to change their role. I'm currently checking to make sure the user hasn't injected a role POST field into the request and was wondering if there is any better way to do this? It's trivial in this scenario with such a small table, but I can see this becoming tiresome on fields/tables with a large amount of columns. My current edit action looks like this.

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

Upvotes: 0

Views: 429

Answers (1)

Serge Rodovnichenko
Serge Rodovnichenko

Reputation: 558

The third parameter of save() method lets you to define the list of fields to save. Model::save() docs

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

Upvotes: 1

Related Questions