Skip to content
Browse files

Integrate ActiveModel::ForbiddenAttributesProtection from StrongParam…

…eters gem
  • Loading branch information...
1 parent 8850054 commit a8f6d5c6450a7fe058348a7f10a908352bb6c7fc @guilleiguaran guilleiguaran committed Jul 13, 2012
View
1 activemodel/lib/active_model.rb
@@ -34,6 +34,7 @@ module ActiveModel
autoload :Conversion
autoload :Dirty
autoload :EachValidator, 'active_model/validator'
+ autoload :ForbiddenAttributesProtection
autoload :Lint
autoload :MassAssignmentSecurity
autoload :Model
View
14 activemodel/lib/active_model/forbidden_attributes_protection.rb
@@ -0,0 +1,14 @@
+module ActiveModel
+ class ForbiddenAttributes < StandardError
+ end
+
+ module ForbiddenAttributesProtection
+ def sanitize_for_mass_assignment(new_attributes, options = {})
@tenderlove
Ruby on Rails member
tenderlove added a note Nov 9, 2012

why do we have an unused options hash? I hate options hashes, especially unused ones. :-P

@carlosantoniodasilva
Ruby on Rails member

I think that was supposed to be the role argument that exists in protected_attributes (which is also why the method got protected I think, since it's protected there?).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ if !new_attributes.respond_to?(:permitted?) || (new_attributes.respond_to?(:permitted?) && new_attributes.permitted?)
+ super
+ else
+ raise ActiveModel::ForbiddenAttributes
+ end
+ end
+ end
+end
View
32 activemodel/test/cases/forbidden_attributes_protection_test.rb
@@ -0,0 +1,32 @@
+require 'cases/helper'
+require 'models/mass_assignment_specific'
+
+class ActiveModelMassUpdateProtectionTest < ActiveSupport::TestCase
+ test "forbidden attributes cannot be used for mass updating" do
+ params = { "a" => "b" }
+ class << params
+ define_method(:permitted?) { false }
+ end
+ assert_raises(ActiveModel::ForbiddenAttributes) do
+ SpecialPerson.new.sanitize_for_mass_assignment(params)
+ end
+ end
+
+ test "permitted attributes can be used for mass updating" do
+ params = { "a" => "b" }
+ class << params
+ define_method(:permitted?) { true }
+ end
+ assert_nothing_raised do
+ assert_equal({ "a" => "b" },
+ SpecialPerson.new.sanitize_for_mass_assignment(params))
+ end
+ end
+
+ test "regular attributes should still be allowed" do
+ assert_nothing_raised do
+ assert_equal({ a: "b" },
+ SpecialPerson.new.sanitize_for_mass_assignment(a: "b"))
+ end
+ end
+end
View
7 activemodel/test/models/mass_assignment_specific.rb
@@ -20,6 +20,13 @@ class Person
public :sanitize_for_mass_assignment
end
+class SpecialPerson
+ include ActiveModel::MassAssignmentSecurity
+ include ActiveModel::ForbiddenAttributesProtection
+
+ public :sanitize_for_mass_assignment
+end
+
class Account
include ActiveModel::MassAssignmentSecurity
attr_accessible :name, :email, :as => [:default, :admin]

0 comments on commit a8f6d5c

Please sign in to comment.
Something went wrong with that request. Please try again.