netguru / cakephp-protected-fields

Protects model fields from mass-assignment such as $model->set(array(...)), still letting you to assign them directly with $model->set($field, $value).

cakephp-protected-fields / README.textile
100644 41 lines (29 sloc) 1.408 kb

AppModel protected fields

This is an AppModel for your CakePHP applications that provides functionality of protected fields.

A protected field can’t be set via multi-assignment (assigning multiple fields at once via $model→set(array(…))), but it still can be set directly with $model→set($field, $value).

You define which fields you want to protect in your model definition:

  class Article extends AppModel {
    var $protectedFields = array(
      'user_id'
    );
  }

Then you don’t need to worry about user_id field being changed by malicious request. For example, you can safely do this in your controller:

  class ArticlesController extends AppController {
    function edit($id) {
      $this->Article->read(null, $id);
      $this->Article->set($this->data);
      $this->Article->save();
    }
  }

When you assign multiple fields (an array of fields) at once via $this→set, protected fields are automatically filtered out. They can only be set directly:

  $this->Article->set('user_id', 1);

Protected fields are also filtered out when you pass multiple records to set() in order to save them all at once with saveAll().

Associated models are also protected. Check included tests for possible scenarios.

Copyright

Copyright © 2008 MichaƂ Szajbe (http://codetunes.com) and netguru (http://netguru.pl), released under the MIT license.