Skip to content

Commit

Permalink
filter collections and arrays properly
Browse files Browse the repository at this point in the history
  • Loading branch information
ujifgc committed May 8, 2014
1 parent 58b3213 commit cc61350
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
11 changes: 9 additions & 2 deletions padrino-core/lib/padrino-core/application/params_protection.rb
Expand Up @@ -50,7 +50,7 @@ def prepare_allowed_params(allowed_params)
when value.kind_of?(Hash) || value.kind_of?(Array)
param_filter[key.to_s] = prepare_allowed_params(value)
else
param_filter[key.to_s] = value || true
param_filter[key.to_s] = value == false ? false : (value || true)
end
end
param_filter.freeze
Expand Down Expand Up @@ -80,9 +80,16 @@ module InstanceMethods
def filter_params!(params, allowed_params)
params.each do |key,value|
type = allowed_params[key]
next if value.kind_of?(Array) && type
case
when type.kind_of?(Hash)
params[key] = filter_params!(value, type)
if key == key.pluralize
value.each do |array_index,array_value|
value[array_index] = filter_params!(array_value, type)
end
else
params[key] = filter_params!(value, type)
end
when type == Integer
params[key] = value.empty? ? nil : value.to_i
when type.kind_of?(Proc)
Expand Down
25 changes: 25 additions & 0 deletions padrino-core/test/test_params_protection.rb
Expand Up @@ -5,6 +5,7 @@
@teri = { 'name' => 'Teri Bauer', 'position' => 'baby' }
@kim = { 'name' => 'Kim Bauer', 'position' => 'daughter', 'child' => @teri }
@jack = { 'name' => 'Jack Bauer', 'position' => 'terrorist', 'child' => @kim }
@family = { 'name' => 'Bauer', 'persons' => { 1 => @teri, 2 => @kim, 3 => @jack } }
end

it 'should drop all parameters except allowed ones' do
Expand Down Expand Up @@ -122,4 +123,28 @@
post '/persons/destroy/1?' + @jack.to_query
assert_equal({"id"=>"1"}, result)
end

it 'should successfully filter hashes' do
result = nil
mock_app do
post :family, :params => [ :persons => [ :name ] ] do
result = params
''
end
end
post '/family?' + @family.to_query
assert_equal({"persons" => {"3" => {"name" => @jack["name"]}, "2" => {"name" => @kim["name"]}, "1" => {"name" => @teri["name"]}}}, result)
end

it 'should pass arrays' do
result = nil
mock_app do
post :family, :params => [ :names => [] ] do
result = params
''
end
end
post '/family?names[]=Jack&names[]=Kim&names[]=Teri'
assert_equal({"names" => %w[Jack Kim Teri]}, result)
end
end

0 comments on commit cc61350

Please sign in to comment.