views:

39

answers:

1

Example form

<% form_for @search do |f| %>
  <ul>
    <li>
      <%= f.label :item_number_equals, "Item number" %><br />
      <%= f.text_field :item_number_equals %>
    </li>
    <li>
      <%= f.label :description_keywords, "Description" %><br />
      <%= f.text_field :description_keywords %>
    </li>
    <li>
      <%= f.check_box :in_stock %>
      <%= f.label :in_stock, "In Stock?" %>
    </li>
    <li>
      <%= f.label :price_gte, "Price Min" %>
      <%= f.text_field :price_gte, :size => 3 %> 
      <%= f.label :price_lte, "Max" %>
      <%= f.text_field :price_lte, :size => 3 %>
    </li>
    <li>
      <%= f.submit "Search" %>
    </li>
  </ul>
<% end %>

Controller

# app/controllers/products_controller.rb
class ProductsController < ApplicationController

  def index
    @search = Product.search(params[:search])
    @products = @search.all
  end

end

What's the best way to sanitize the params in this case? The user could easily modify the HTML or GET request string in attempt to access other data they shouldn't have access to.

+1  A: 

AFAIK, Searchlogic doesn't support any sort of whitelisting of searchable scopes out of the box. The easiest approach is to write a method to obliterate any hash keys that aren't explicitly authorized:

class Hash
  def sanitize_keys!(*allowed)
    self.each do |key, value|
      self.delete(key) unless allowed.include? key
    end
  end
end

# in your controller...
params[:search].andand.sanitize_keys!(:in_stock, :price_gte) # etc...

Not great, but not bad, and it would certainly get the job done. In Rails 3 using meta_search, you can whitelist your scopes for searching at the model level, which is a superior approach. You could probably extend Searchlogic to achieve this same functionality, too.

Dave Pirotte