Skip to content

Commit

Permalink
Normalize query parameters so we can unmangle facebook's bad encodings
Browse files Browse the repository at this point in the history
  • Loading branch information
cbeer committed Jul 13, 2020
1 parent f70bcbb commit 43a5f23
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
26 changes: 20 additions & 6 deletions lib/blacklight/search_state.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,34 @@ class SearchState
# @param [Blacklight::Config] blacklight_config
# @param [ApplicationController] controller used for the routing helpers
def initialize(params, blacklight_config, controller = nil)
@params = self.class.normalize_params(params)
@blacklight_config = blacklight_config
@controller = controller
end

def self.normalize_params(untrusted_params = {})
params = untrusted_params

if params.respond_to?(:to_unsafe_h)
# This is the typical (not-ActionView::TestCase) code path.
@params = params.to_unsafe_h
params = params.to_unsafe_h
# In Rails 5 to_unsafe_h returns a HashWithIndifferentAccess, in Rails 4 it returns Hash
@params = @params.with_indifferent_access if @params.instance_of? Hash
params = params.with_indifferent_access if params.instance_of? Hash
elsif params.is_a? Hash
# This is an ActionView::TestCase workaround for Rails 4.2.
@params = params.dup.with_indifferent_access
params = params.dup.with_indifferent_access
else
@params = params.dup.to_h.with_indifferent_access
params = params.dup.to_h.with_indifferent_access
end

@blacklight_config = blacklight_config
@controller = controller
# Normalize facet parameters mangled by facebook
if params[:f].is_a?(Hash) && params[:f].values.any? { |x| x.is_a?(Hash) }
params[:f] = params[:f].transform_values do |value|
value.is_a?(Hash) ? value.values : value
end
end

params
end

def to_hash
Expand Down
8 changes: 8 additions & 0 deletions spec/lib/blacklight/search_state_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@
expect(search_state.to_h).to eq data.with_indifferent_access
end
end

context 'with facebooks badly mangled query parameters' do
let(:params) { { f: { field: { '0': 'first', '1': 'second' } } } }

it 'normalizes the facets to the expected format' do
expect(search_state.to_h).to include f: { field: %w[first second] }
end
end
end

describe 'interface compatibility with params' do
Expand Down

0 comments on commit 43a5f23

Please sign in to comment.