strong_parameters.rb 32.5 KB
Newer Older
1
require 'active_support/core_ext/hash/indifferent_access'
2
require 'active_support/core_ext/hash/transform_values'
R
Rafael Mendonça França 已提交
3
require 'active_support/core_ext/array/wrap'
X
Xavier Noria 已提交
4
require 'active_support/core_ext/string/filters'
5
require 'active_support/rescuable'
6
require 'action_dispatch/http/upload'
7
require 'rack/test'
8
require 'stringio'
9
require 'set'
10 11 12 13 14
require 'yaml'

# Wire up YAML format compatibility with Rails 4.2. Makes the YAML parser call
# `init_with` when it encounters `!ruby/hash-with-ivars:ActionController::Parameters`,
# instead of trying to parse it as a regular hash subclass.
15 16
# Second `load_tags` is for compatibility with Psych prior to 2.0.9 where hashes
# were dumped without instance variables.
17
YAML.load_tags['!ruby/hash-with-ivars:ActionController::Parameters'] = 'ActionController::Parameters'
18
YAML.load_tags['!ruby/hash:ActionController::Parameters'] = 'ActionController::Parameters'
19 20

module ActionController
21 22 23 24
  # Raised when a required parameter is missing.
  #
  #   params = ActionController::Parameters.new(a: {})
  #   params.fetch(:b)
25
  #   # => ActionController::ParameterMissing: param is missing or the value is empty: b
26
  #   params.require(:a)
27
  #   # => ActionController::ParameterMissing: param is missing or the value is empty: a
28
  class ParameterMissing < KeyError
29
    attr_reader :param # :nodoc:
30

31
    def initialize(param) # :nodoc:
32
      @param = param
33
      super("param is missing or the value is empty: #{param}")
34 35 36
    end
  end

37 38
  # Raised when a supplied parameter is not expected and
  # ActionController::Parameters.action_on_unpermitted_parameters
39
  # is set to <tt>:raise</tt>.
40 41 42
  #
  #   params = ActionController::Parameters.new(a: "123", b: "456")
  #   params.permit(:c)
43
  #   # => ActionController::UnpermittedParameters: found unpermitted parameters: a, b
44 45
  class UnpermittedParameters < IndexError
    attr_reader :params # :nodoc:
46

47
    def initialize(params) # :nodoc:
48
      @params = params
49
      super("found unpermitted parameter#{'s' if params.size > 1 }: #{params.join(", ")}")
50 51 52
    end
  end

53
  # == Action Controller \Parameters
54
  #
T
Tom Kadwill 已提交
55
  # Allows you to choose which attributes should be whitelisted for mass updating
56
  # and thus prevent accidentally exposing that which shouldn't be exposed.
57 58
  # Provides two methods for this purpose: #require and #permit. The former is
  # used to mark parameters as required. The latter is used to set the parameter
59
  # as permitted and limit which attributes should be allowed for mass updating.
60 61 62 63 64 65 66 67 68 69
  #
  #   params = ActionController::Parameters.new({
  #     person: {
  #       name: 'Francesco',
  #       age:  22,
  #       role: 'admin'
  #     }
  #   })
  #
  #   permitted = params.require(:person).permit(:name, :age)
70
  #   permitted            # => <ActionController::Parameters {"name"=>"Francesco", "age"=>22} permitted: true>
71 72
  #   permitted.permitted? # => true
  #
73
  #   Person.first.update!(permitted)
74
  #   # => #<Person id: 1, name: "Francesco", age: 22, role: "user">
75
  #
76 77 78 79 80 81 82 83 84
  # It provides two options that controls the top-level behavior of new instances:
  #
  # * +permit_all_parameters+ - If it's +true+, all the parameters will be
  #   permitted by default. The default is +false+.
  # * +action_on_unpermitted_parameters+ - Allow to control the behavior when parameters
  #   that are not explicitly permitted are found. The values can be <tt>:log</tt> to
  #   write a message on the logger or <tt>:raise</tt> to raise
  #   ActionController::UnpermittedParameters exception. The default value is <tt>:log</tt>
  #   in test and development environments, +false+ otherwise.
85
  #
86 87
  # Examples:
  #
88
  #   params = ActionController::Parameters.new
89
  #   params.permitted? # => false
90 91 92 93 94 95
  #
  #   ActionController::Parameters.permit_all_parameters = true
  #
  #   params = ActionController::Parameters.new
  #   params.permitted? # => true
  #
96 97
  #   params = ActionController::Parameters.new(a: "123", b: "456")
  #   params.permit(:c)
98
  #   # => <ActionController::Parameters {} permitted: true>
99 100 101 102 103 104 105
  #
  #   ActionController::Parameters.action_on_unpermitted_parameters = :raise
  #
  #   params = ActionController::Parameters.new(a: "123", b: "456")
  #   params.permit(:c)
  #   # => ActionController::UnpermittedParameters: found unpermitted keys: a, b
  #
106 107 108 109
  # Please note that these options *are not thread-safe*. In a multi-threaded
  # environment they should only be set once at boot-time and never mutated at
  # runtime.
  #
110 111
  # You can fetch values of <tt>ActionController::Parameters</tt> using either
  # <tt>:key</tt> or <tt>"key"</tt>.
112 113 114 115
  #
  #   params = ActionController::Parameters.new(key: 'value')
  #   params[:key]  # => "value"
  #   params["key"] # => "value"
116
  class Parameters
117
    cattr_accessor :permit_all_parameters, instance_accessor: false
118 119
    self.permit_all_parameters = false

120 121
    cattr_accessor :action_on_unpermitted_parameters, instance_accessor: false

122
    delegate :keys, :key?, :has_key?, :values, :has_value?, :value?, :empty?, :include?,
123
      :as_json, to: :@parameters
124

125 126 127 128
    # By default, never raise an UnpermittedParameters exception if these
    # params are present. The default includes both 'controller' and 'action'
    # because they are added by Rails and should be of no concern. One way
    # to change these is to specify `always_permitted_parameters` in your
R
Rafael Chacón 已提交
129 130 131
    # config. For instance:
    #
    #    config.always_permitted_parameters = %w( controller action format )
132 133 134
    cattr_accessor :always_permitted_parameters
    self.always_permitted_parameters = %w( controller action )

135 136 137 138
    # Returns a new instance of <tt>ActionController::Parameters</tt>.
    # Also, sets the +permitted+ attribute to the default value of
    # <tt>ActionController::Parameters.permit_all_parameters</tt>.
    #
U
Uģis Ozols 已提交
139
    #   class Person < ActiveRecord::Base
140 141 142 143
    #   end
    #
    #   params = ActionController::Parameters.new(name: 'Francesco')
    #   params.permitted?  # => false
144
    #   Person.new(params) # => ActiveModel::ForbiddenAttributesError
145 146 147 148
    #
    #   ActionController::Parameters.permit_all_parameters = true
    #
    #   params = ActionController::Parameters.new(name: 'Francesco')
149
    #   params.permitted?  # => true
150
    #   Person.new(params) # => #<Person id: nil, name: "Francesco">
151 152
    def initialize(parameters = {})
      @parameters = parameters.with_indifferent_access
153
      @permitted = self.class.permit_all_parameters
154 155
    end

156
    # Returns true if another +Parameters+ object contains the same content and
157 158 159 160 161 162 163 164 165 166 167 168 169
    # permitted flag.
    def ==(other)
      if other.respond_to?(:permitted?)
        self.permitted? == other.permitted? && self.parameters == other.parameters
      elsif other.is_a?(Hash)
        ActiveSupport::Deprecation.warn <<-WARNING.squish
          Comparing equality between `ActionController::Parameters` and a
          `Hash` is deprecated and will be removed in Rails 5.1. Please only do
          comparisons between instances of `ActionController::Parameters`. If
          you need to compare to a hash, first convert it using
          `ActionController::Parameters#new`.
        WARNING
        @parameters == other.with_indifferent_access
170
      else
171
        @parameters == other
172 173 174
      end
    end

175 176
    # Returns a safe <tt>ActiveSupport::HashWithIndifferentAccess</tt>
    # representation of this parameter with all unpermitted keys removed.
177 178 179 180 181 182 183 184 185 186 187
    #
    #   params = ActionController::Parameters.new({
    #     name: 'Senjougahara Hitagi',
    #     oddity: 'Heavy stone crab'
    #   })
    #   params.to_h # => {}
    #
    #   safe_params = params.permit(:name)
    #   safe_params.to_h # => {"name"=>"Senjougahara Hitagi"}
    def to_h
      if permitted?
188
        convert_parameters_to_hashes(@parameters, :to_h)
189 190 191 192 193
      else
        slice(*self.class.always_permitted_parameters).permit!.to_h
      end
    end

194 195 196
    # Returns an unsafe, unfiltered
    # <tt>ActiveSupport::HashWithIndifferentAccess</tt> representation of this
    # parameter.
197 198 199 200 201 202
    #
    #   params = ActionController::Parameters.new({
    #     name: 'Senjougahara Hitagi',
    #     oddity: 'Heavy stone crab'
    #   })
    #   params.to_unsafe_h
203
    #   # => {"name"=>"Senjougahara Hitagi", "oddity" => "Heavy stone crab"}
P
Prem Sichanugrist 已提交
204
    def to_unsafe_h
205
      convert_parameters_to_hashes(@parameters, :to_unsafe_h)
P
Prem Sichanugrist 已提交
206 207 208
    end
    alias_method :to_unsafe_hash, :to_unsafe_h

T
Tom Kadwill 已提交
209
    # Convert all hashes in values into parameters, then yield each pair in
210 211
    # the same way as <tt>Hash#each_pair</tt>
    def each_pair(&block)
212 213
      @parameters.each_pair do |key, value|
        yield key, convert_hashes_to_parameters(key, value)
214 215 216 217
      end
    end
    alias_method :each, :each_pair

218 219 220
    # Attribute that keeps track of converted arrays, if any, to avoid double
    # looping in the common use case permit + mass-assignment. Defined in a
    # method to instantiate it only if needed.
221 222 223 224
    #
    # Testing membership still loops, but it's going to be faster than our own
    # loop that converts values. Also, we are not going to build a new array
    # object per fetch.
225
    def converted_arrays
226
      @converted_arrays ||= Set.new
227 228
    end

229 230 231 232 233 234 235 236 237 238
    # Returns +true+ if the parameter is permitted, +false+ otherwise.
    #
    #   params = ActionController::Parameters.new
    #   params.permitted? # => false
    #   params.permit!
    #   params.permitted? # => true
    def permitted?
      @permitted
    end

239 240 241 242 243 244 245
    # Sets the +permitted+ attribute to +true+. This can be used to pass
    # mass assignment. Returns +self+.
    #
    #   class Person < ActiveRecord::Base
    #   end
    #
    #   params = ActionController::Parameters.new(name: 'Francesco')
246
    #   params.permitted?  # => false
247 248 249 250
    #   Person.new(params) # => ActiveModel::ForbiddenAttributesError
    #   params.permit!
    #   params.permitted?  # => true
    #   Person.new(params) # => #<Person id: nil, name: "Francesco">
251
    def permit!
252
      each_pair do |key, value|
C
Corey Ward 已提交
253 254
        Array.wrap(value).each do |v|
          v.permit! if v.respond_to? :permit!
255
        end
256 257
      end

258 259 260 261
      @permitted = true
      self
    end

262 263 264 265
    # This method accepts both a single key and an array of keys.
    #
    # When passed a single key, if it exists and its associated value is
    # either present or the singleton +false+, returns said value:
266
    #
267
    #   ActionController::Parameters.new(person: { name: 'Francesco' }).require(:person)
268
    #   # => <ActionController::Parameters {"name"=>"Francesco"} permitted: false>
269
    #
270 271 272 273 274
    # Otherwise raises <tt>ActionController::ParameterMissing</tt>:
    #
    #   ActionController::Parameters.new.require(:person)
    #   # ActionController::ParameterMissing: param is missing or the value is empty: person
    #
275
    #   ActionController::Parameters.new(person: nil).require(:person)
276 277 278 279
    #   # ActionController::ParameterMissing: param is missing or the value is empty: person
    #
    #   ActionController::Parameters.new(person: "\t").require(:person)
    #   # ActionController::ParameterMissing: param is missing or the value is empty: person
280
    #
281
    #   ActionController::Parameters.new(person: {}).require(:person)
282 283 284
    #   # ActionController::ParameterMissing: param is missing or the value is empty: person
    #
    # When given an array of keys, the method tries to require each one of them
X
Xavier Noria 已提交
285
    # in order. If it succeeds, an array with the respective return values is
286 287 288
    # returned:
    #
    #   params = ActionController::Parameters.new(user: { ... }, profile: { ... })
289
    #   user_params, profile_params = params.require([:user, :profile])
290
    #
T
Tom Kadwill 已提交
291
    # Otherwise, the method re-raises the first exception found:
292
    #
293
    #   params = ActionController::Parameters.new(user: {}, profile: {})
294
    #   user_params, profile_params = params.require([:user, :profile])
295 296 297 298 299 300 301 302 303 304
    #   # ActionController::ParameterMissing: param is missing or the value is empty: user
    #
    # Technically this method can be used to fetch terminal values:
    #
    #   # CAREFUL
    #   params = ActionController::Parameters.new(person: { name: 'Finn' })
    #   name = params.require(:person).require(:name) # CAREFUL
    #
    # but take into account that at some point those ones have to be permitted:
    #
305 306 307
    #   def person_params
    #     params.require(:person).permit(:name).tap do |person_params|
    #       person_params.require(:name) # SAFER
308 309
    #     end
    #   end
310
    #
311
    # for example.
312
    def require(key)
X
Xavier Noria 已提交
313
      return key.map { |k| require(k) } if key.is_a?(Array)
314 315 316 317 318 319
      value = self[key]
      if value.present? || value == false
        value
      else
        raise ParameterMissing.new(key)
      end
320 321
    end

322
    # Alias of #require.
323 324
    alias :required :require

325
    # Returns a new <tt>ActionController::Parameters</tt> instance that
326 327
    # includes only the given +filters+ and sets the +permitted+ attribute
    # for the object to +true+. This is useful for limiting which attributes
328 329 330 331
    # should be allowed for mass updating.
    #
    #   params = ActionController::Parameters.new(user: { name: 'Francesco', age: 22, role: 'admin' })
    #   permitted = params.require(:user).permit(:name, :age)
332
    #   permitted.permitted?      # => true
333 334 335 336
    #   permitted.has_key?(:name) # => true
    #   permitted.has_key?(:age)  # => true
    #   permitted.has_key?(:role) # => false
    #
337 338 339 340
    # Only permitted scalars pass the filter. For example, given
    #
    #   params.permit(:name)
    #
341
    # +:name+ passes if it is a key of +params+ whose associated value is of type
342
    # +String+, +Symbol+, +NilClass+, +Numeric+, +TrueClass+, +FalseClass+,
343 344 345
    # +Date+, +Time+, +DateTime+, +StringIO+, +IO+,
    # +ActionDispatch::Http::UploadedFile+ or +Rack::Test::UploadedFile+.
    # Otherwise, the key +:name+ is filtered out.
346 347 348 349
    #
    # You may declare that the parameter should be an array of permitted scalars
    # by mapping it to an empty array:
    #
350
    #   params = ActionController::Parameters.new(tags: ['rails', 'parameters'])
351
    #   params.permit(tags: [])
352
    #
353 354 355
    # You can also use +permit+ on nested parameters, like:
    #
    #   params = ActionController::Parameters.new({
356
    #     person: {
357 358 359 360 361 362 363 364 365
    #       name: 'Francesco',
    #       age:  22,
    #       pets: [{
    #         name: 'Purplish',
    #         category: 'dogs'
    #       }]
    #     }
    #   })
    #
366
    #   permitted = params.permit(person: [ :name, { pets: :name } ])
367 368
    #   permitted.permitted?                    # => true
    #   permitted[:person][:name]               # => "Francesco"
369
    #   permitted[:person][:age]                # => nil
370 371
    #   permitted[:person][:pets][0][:name]     # => "Purplish"
    #   permitted[:person][:pets][0][:category] # => nil
372 373 374 375 376 377 378 379
    #
    # Note that if you use +permit+ in a key that points to a hash,
    # it won't allow all the hash. You also need to specify which
    # attributes inside the hash should be whitelisted.
    #
    #   params = ActionController::Parameters.new({
    #     person: {
    #       contact: {
I
Ilya Vorontsov 已提交
380
    #         email: 'none@test.com',
381 382 383 384 385 386
    #         phone: '555-1234'
    #       }
    #     }
    #   })
    #
    #   params.require(:person).permit(:contact)
387
    #   # => <ActionController::Parameters {} permitted: true>
388 389
    #
    #   params.require(:person).permit(contact: :phone)
390
    #   # => <ActionController::Parameters {"contact"=><ActionController::Parameters {"phone"=>"555-1234"} permitted: true>} permitted: true>
391 392
    #
    #   params.require(:person).permit(contact: [ :email, :phone ])
393
    #   # => <ActionController::Parameters {"contact"=><ActionController::Parameters {"email"=>"none@test.com", "phone"=>"555-1234"} permitted: true>} permitted: true>
394 395 396
    def permit(*filters)
      params = self.class.new

397
      filters.flatten.each do |filter|
398
        case filter
399 400
        when Symbol, String
          permitted_scalar_filter(params, filter)
401
        when Hash then
402
          hash_filter(params, filter)
403 404 405
        end
      end

406
      unpermitted_parameters!(params) if self.class.action_on_unpermitted_parameters
407

408 409 410
      params.permit!
    end

411 412 413
    # Returns a parameter for the given +key+. If not found,
    # returns +nil+.
    #
414
    #   params = ActionController::Parameters.new(person: { name: 'Francesco' })
415
    #   params[:person] # => <ActionController::Parameters {"name"=>"Francesco"} permitted: false>
416
    #   params[:none]   # => nil
417
    def [](key)
418 419 420
      convert_hashes_to_parameters(key, @parameters[key])
    end

421 422
    # Assigns a value to a given +key+. The given key may still get filtered out
    # when +permit+ is called.
423 424
    def []=(key, value)
      @parameters[key] = value
425 426
    end

427 428 429 430 431 432 433
    # Returns a parameter for the given +key+. If the +key+
    # can't be found, there are several options: With no other arguments,
    # it will raise an <tt>ActionController::ParameterMissing</tt> error;
    # if more arguments are given, then that will be returned; if a block
    # is given, then that will be run and its result returned.
    #
    #   params = ActionController::Parameters.new(person: { name: 'Francesco' })
434
    #   params.fetch(:person)               # => <ActionController::Parameters {"name"=>"Francesco"} permitted: false>
435
    #   params.fetch(:none)                 # => ActionController::ParameterMissing: param is missing or the value is empty: none
436
    #   params.fetch(:none, 'Francesco')    # => "Francesco"
437
    #   params.fetch(:none) { 'Francesco' } # => "Francesco"
A
Akira Matsuda 已提交
438
    def fetch(key, *args)
439
      convert_value_to_parameters(
440 441 442 443 444 445
        @parameters.fetch(key) {
          if block_given?
            yield
          else
            args.fetch(0) { raise ActionController::ParameterMissing.new(key) }
          end
446
        }
447
      )
448 449
    end

450 451 452 453
    if Hash.method_defined?(:dig)
      # Extracts the nested parameter from the given +keys+ by calling +dig+
      # at each step. Returns +nil+ if any intermediate step is +nil+.
      #
454 455 456
      #   params = ActionController::Parameters.new(foo: { bar: { baz: 1 } })
      #   params.dig(:foo, :bar, :baz) # => 1
      #   params.dig(:foo, :zot, :xyz) # => nil
457
      #
458 459
      #   params2 = ActionController::Parameters.new(foo: [10, 11, 12])
      #   params2.dig(:foo, 1) # => 11
460 461 462 463 464
      def dig(*keys)
        convert_value_to_parameters(@parameters.dig(*keys))
      end
    end

465 466 467 468 469
    # Returns a new <tt>ActionController::Parameters</tt> instance that
    # includes only the given +keys+. If the given +keys+
    # don't exist, returns an empty hash.
    #
    #   params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
470 471
    #   params.slice(:a, :b) # => <ActionController::Parameters {"a"=>1, "b"=>2} permitted: false>
    #   params.slice(:d)     # => <ActionController::Parameters {} permitted: false>
472
    def slice(*keys)
473 474 475
      new_instance_with_inherited_permitted_status(@parameters.slice(*keys))
    end

476 477
    # Returns current <tt>ActionController::Parameters</tt> instance which
    # contains only the given +keys+.
478 479 480 481 482
    def slice!(*keys)
      @parameters.slice!(*keys)
      self
    end

483 484 485 486
    # Returns a new <tt>ActionController::Parameters</tt> instance that
    # filters out the given +keys+.
    #
    #   params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
487 488
    #   params.except(:a, :b) # => <ActionController::Parameters {"c"=>3} permitted: false>
    #   params.except(:d)     # => <ActionController::Parameters {"a"=>1, "b"=>2, "c"=>3} permitted: false>
489 490
    def except(*keys)
      new_instance_with_inherited_permitted_status(@parameters.except(*keys))
491 492
    end

493 494 495
    # Removes and returns the key/value pairs matching the given keys.
    #
    #   params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
496 497
    #   params.extract!(:a, :b) # => <ActionController::Parameters {"a"=>1, "b"=>2} permitted: false>
    #   params                  # => <ActionController::Parameters {"c"=>3} permitted: false>
498
    def extract!(*keys)
499
      new_instance_with_inherited_permitted_status(@parameters.extract!(*keys))
500 501 502 503 504 505 506
    end

    # Returns a new <tt>ActionController::Parameters</tt> with the results of
    # running +block+ once for every value. The keys are unchanged.
    #
    #   params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
    #   params.transform_values { |x| x * 2 }
507
    #   # => <ActionController::Parameters {"a"=>2, "b"=>4, "c"=>6} permitted: false>
508 509 510 511 512
    def transform_values(&block)
      if block
        new_instance_with_inherited_permitted_status(
          @parameters.transform_values(&block)
        )
513
      else
514
        @parameters.transform_values
515 516 517
      end
    end

518 519
    # Performs values transformation and returns the altered
    # <tt>ActionController::Parameters</tt> instance.
520 521 522 523 524
    def transform_values!(&block)
      @parameters.transform_values!(&block)
      self
    end

525 526 527
    # Returns a new <tt>ActionController::Parameters</tt> instance with the
    # results of running +block+ once for every key. The values are unchanged.
    def transform_keys(&block)
528 529 530 531
      if block
        new_instance_with_inherited_permitted_status(
          @parameters.transform_keys(&block)
        )
532
      else
533
        @parameters.transform_keys
534 535 536
      end
    end

J
Jon Atack 已提交
537
    # Performs keys transformation and returns the altered
538
    # <tt>ActionController::Parameters</tt> instance.
539 540 541 542 543
    def transform_keys!(&block)
      @parameters.transform_keys!(&block)
      self
    end

544 545 546 547
    # Deletes and returns a key-value pair from +Parameters+ whose key is equal
    # to key. If the key is not found, returns the default value. If the
    # optional code block is given and the key is not found, pass in the key
    # and return the result of block.
A
Akira Matsuda 已提交
548
    def delete(key)
549
      convert_value_to_parameters(@parameters.delete(key))
550 551
    end

552 553
    # Returns a new instance of <tt>ActionController::Parameters</tt> with only
    # items that the block evaluates to true.
554 555
    def select(&block)
      new_instance_with_inherited_permitted_status(@parameters.select(&block))
556 557 558 559
    end

    # Equivalent to Hash#keep_if, but returns nil if no changes were made.
    def select!(&block)
560 561 562 563 564
      @parameters.select!(&block)
      self
    end
    alias_method :keep_if, :select!

565 566
    # Returns a new instance of <tt>ActionController::Parameters</tt> with items
    # that the block evaluates to true removed.
567 568 569 570
    def reject(&block)
      new_instance_with_inherited_permitted_status(@parameters.reject(&block))
    end

571
    # Removes items that the block evaluates to true and returns self.
572 573 574 575 576 577
    def reject!(&block)
      @parameters.reject!(&block)
      self
    end
    alias_method :delete_if, :reject!

578
    # Returns values that were assigned to the given +keys+. Note that all the
579
    # +Hash+ objects will be converted to <tt>ActionController::Parameters</tt>.
580 581
    def values_at(*keys)
      convert_value_to_parameters(@parameters.values_at(*keys))
582 583
    end

584 585
    # Returns a new <tt>ActionController::Parameters</tt> with all keys from
    # +other_hash+ merges into current hash.
586 587 588 589 590 591 592
    def merge(other_hash)
      new_instance_with_inherited_permitted_status(
        @parameters.merge(other_hash)
      )
    end

    # This is required by ActiveModel attribute assignment, so that user can
593 594 595
    # pass +Parameters+ to a mass assignment methods in a model. It should not
    # matter as we are using +HashWithIndifferentAccess+ internally.
    def stringify_keys # :nodoc:
596 597 598
      dup
    end

599
    def inspect
600
      "<#{self.class} #{@parameters} permitted: #{@permitted}>"
601 602
    end

603
    def init_with(coder) # :nodoc:
604 605 606 607 608 609 610
      case coder.tag
      when '!ruby/hash:ActionController::Parameters'
        # YAML 2.0.8's format where hash instance variables weren't stored.
        @parameters = coder.map.with_indifferent_access
        @permitted  = false
      when '!ruby/hash-with-ivars:ActionController::Parameters'
        # YAML 2.0.9's Hash subclass format where keys and values
611 612 613
        # were stored under an elements hash and `permitted` within an ivars hash.
        @parameters = coder.map['elements'].with_indifferent_access
        @permitted  = coder.map['ivars'][:@permitted]
614
      when '!ruby/object:ActionController::Parameters'
615 616 617 618 619 620
        # YAML's Object format. Only needed because of the format
        # backwardscompability above, otherwise equivalent to YAML's initialization.
        @parameters, @permitted = coder.map['parameters'], coder.map['permitted']
      end
    end

621 622 623
    def method_missing(method_sym, *args, &block)
      if @parameters.respond_to?(method_sym)
        message = <<-DEPRECATE.squish
624
          Method #{method_sym} is deprecated and will be removed in Rails 5.1,
625 626 627
          as `ActionController::Parameters` no longer inherits from
          hash. Using this deprecated behavior exposes potential security
          problems. If you continue to use this method you may be creating
628
          a security vulnerability in your app that can be exploited. Instead,
629 630
          consider using one of these documented methods which are not
          deprecated: http://api.rubyonrails.org/v#{ActionPack.version}/classes/ActionController/Parameters.html
631 632 633 634 635 636 637 638
        DEPRECATE
        ActiveSupport::Deprecation.warn(message)
        @parameters.public_send(method_sym, *args, &block)
      else
        super
      end
    end

639
    protected
640 641
      attr_reader :parameters

642 643 644 645
      def permitted=(new_permitted)
        @permitted = new_permitted
      end

646
      def fields_for_style?
647
        @parameters.all? { |k, v| k =~ /\A-?\d+\z/ && (v.is_a?(Hash) || v.is_a?(Parameters)) }
648 649
      end

650
    private
651 652 653 654 655 656
      def new_instance_with_inherited_permitted_status(hash)
        self.class.new(hash).tap do |new_instance|
          new_instance.permitted = @permitted
        end
      end

657
      def convert_parameters_to_hashes(value, using)
658 659
        case value
        when Array
660
          value.map { |v| convert_parameters_to_hashes(v, using) }
661 662
        when Hash
          value.transform_values do |v|
663
            convert_parameters_to_hashes(v, using)
664 665
          end.with_indifferent_access
        when Parameters
666
          value.send(using)
667 668 669 670 671
        else
          value
        end
      end

672
      def convert_hashes_to_parameters(key, value)
673
        converted = convert_value_to_parameters(value)
674
        @parameters[key] = converted unless converted.equal?(value)
675 676 677
        converted
      end

678
      def convert_value_to_parameters(value)
679 680 681
        case value
        when Array
          return value if converted_arrays.member?(value)
682 683
          converted = value.map { |_| convert_value_to_parameters(_) }
          converted_arrays << converted
684
          converted
685
        when Hash
686
          self.class.new(value)
687 688
        else
          value
689 690 691 692
        end
      end

      def each_element(object)
A
Aaron Patterson 已提交
693 694 695 696
        case object
        when Array
          object.grep(Parameters).map { |el| yield el }.compact
        when Parameters
697
          if object.fields_for_style?
A
Aaron Patterson 已提交
698 699 700 701 702 703
            hash = object.class.new
            object.each { |k,v| hash[k] = yield v }
            hash
          else
            yield object
          end
704 705
        end
      end
706 707 708 709 710 711

      def unpermitted_parameters!(params)
        unpermitted_keys = unpermitted_keys(params)
        if unpermitted_keys.any?
          case self.class.action_on_unpermitted_parameters
          when :log
712 713
            name = "unpermitted_parameters.action_controller"
            ActiveSupport::Notifications.instrument(name, keys: unpermitted_keys)
714 715 716 717 718 719 720
          when :raise
            raise ActionController::UnpermittedParameters.new(unpermitted_keys)
          end
        end
      end

      def unpermitted_keys(params)
721
        self.keys - params.keys - self.always_permitted_parameters
722
      end
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746

      #
      # --- Filtering ----------------------------------------------------------
      #

      # This is a white list of permitted scalar types that includes the ones
      # supported in XML and JSON requests.
      #
      # This list is in particular used to filter ordinary requests, String goes
      # as first element to quickly short-circuit the common case.
      #
      # If you modify this collection please update the API of +permit+ above.
      PERMITTED_SCALAR_TYPES = [
        String,
        Symbol,
        NilClass,
        Numeric,
        TrueClass,
        FalseClass,
        Date,
        Time,
        # DateTimes are Dates, we document the type but avoid the redundant check.
        StringIO,
        IO,
747
        ActionDispatch::Http::UploadedFile,
748
        Rack::Test::UploadedFile,
749 750 751 752 753 754 755 756 757 758 759
      ]

      def permitted_scalar?(value)
        PERMITTED_SCALAR_TYPES.any? {|type| value.is_a?(type)}
      end

      def permitted_scalar_filter(params, key)
        if has_key?(key) && permitted_scalar?(self[key])
          params[key] = self[key]
        end

760
        keys.grep(/\A#{Regexp.escape(key)}\(\d+[if]?\)\z/) do |k|
761 762
          if permitted_scalar?(self[k])
            params[k] = self[k]
763 764 765 766 767
          end
        end
      end

      def array_of_permitted_scalars?(value)
A
Aaron Patterson 已提交
768
        if value.is_a?(Array) && value.all? {|element| permitted_scalar?(element)}
769
          yield value
770 771 772
        end
      end

773 774 775 776
      def non_scalar?(value)
        value.is_a?(Array) || value.is_a?(Parameters)
      end

777
      EMPTY_ARRAY = []
778 779 780 781 782
      def hash_filter(params, filter)
        filter = filter.with_indifferent_access

        # Slicing filters out non-declared keys.
        slice(*filter.keys).each do |key, value|
783
          next unless value
A
Aaron Patterson 已提交
784
          next unless has_key? key
785

786
          if filter[key] == EMPTY_ARRAY
787
            # Declaration { comment_ids: [] }.
A
Aaron Patterson 已提交
788
            array_of_permitted_scalars?(self[key]) do |val|
789 790
              params[key] = val
            end
791
          elsif non_scalar?(value)
V
Vipul A M 已提交
792
            # Declaration { user: :name } or { user: [:name, :age, { address: ... }] }.
793
            params[key] = each_element(value) do |element|
A
Aaron Patterson 已提交
794
              element.permit(*Array.wrap(filter[key]))
795 796 797 798
            end
          end
        end
      end
799 800 801

      def initialize_copy(source)
        super
802
        @parameters = @parameters.dup
803
      end
804 805
  end

806
  # == Strong \Parameters
807
  #
808
  # It provides an interface for protecting attributes from end-user
809
  # assignment. This makes Action Controller parameters forbidden
810
  # to be used in Active Model mass assignment until they have been
811 812 813 814 815 816 817
  # whitelisted.
  #
  # In addition, parameters can be marked as required and flow through a
  # predefined raise/rescue flow to end up as a 400 Bad Request with no
  # effort.
  #
  #   class PeopleController < ActionController::Base
818
  #     # Using "Person.create(params[:person])" would raise an
819
  #     # ActiveModel::ForbiddenAttributesError exception because it'd
820 821
  #     # be using mass assignment without an explicit permit step.
  #     # This is the recommended form:
822
  #     def create
823
  #       Person.create(person_params)
824 825 826
  #     end
  #
  #     # This will pass with flying colors as long as there's a person key in the
827
  #     # parameters, otherwise it'll raise an ActionController::MissingParameter
828
  #     # exception, which will get caught by ActionController::Base and turned
829
  #     # into a 400 Bad Request reply.
830 831
  #     def update
  #       redirect_to current_account.people.find(params[:id]).tap { |person|
832
  #         person.update!(person_params)
833 834 835 836 837
  #       }
  #     end
  #
  #     private
  #       # Using a private method to encapsulate the permissible parameters is
838
  #       # just a good pattern since you'll be able to reuse the same permit
839 840 841 842 843 844 845
  #       # list between create and update. Also, you can specialize this method
  #       # with per-user checking of permissible attributes.
  #       def person_params
  #         params.require(:person).permit(:name, :age)
  #       end
  #   end
  #
846
  # In order to use <tt>accepts_nested_attributes_for</tt> with Strong \Parameters, you
847 848
  # will need to specify which nested attributes should be whitelisted. You might want
  # to allow +:id+ and +:_destroy+, see ActiveRecord::NestedAttributes for more information.
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
  #
  #   class Person
  #     has_many :pets
  #     accepts_nested_attributes_for :pets
  #   end
  #
  #   class PeopleController < ActionController::Base
  #     def create
  #       Person.create(person_params)
  #     end
  #
  #     ...
  #
  #     private
  #
  #       def person_params
  #         # It's mandatory to specify the nested attributes that should be whitelisted.
  #         # If you use `permit` with just the key that points to the nested attributes hash,
  #         # it will return an empty hash.
868
  #         params.require(:person).permit(:name, :age, pets_attributes: [ :id, :name, :category ])
869 870 871
  #       end
  #   end
  #
872 873
  # See ActionController::Parameters.require and ActionController::Parameters.permit
  # for more information.
874 875 876 877
  module StrongParameters
    extend ActiveSupport::Concern
    include ActiveSupport::Rescuable

878 879
    # Returns a new ActionController::Parameters object that
    # has been instantiated with the <tt>request.parameters</tt>.
880 881 882 883
    def params
      @_params ||= Parameters.new(request.parameters)
    end

884 885 886 887 888
    # Assigns the given +value+ to the +params+ hash. If +value+
    # is a Hash, this will create an ActionController::Parameters
    # object that has been instantiated with the given +value+ hash.
    def params=(value)
      @_params = value.is_a?(Hash) ? Parameters.new(value) : value
889 890 891
    end
  end
end