开发者

How to sanitize form params for use with Searchlogic? [Rails]

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 /开发者_JAVA技巧>
      <%= 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.


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.


Take a look at meta_search -- specifically the attr_searchable and assoc_searchable methods. This is (almost) a direct replacement for Searchlogic, and it also works with Rails 3.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜