如何清理与Searchlogic一起使用的表单参数? [路轨] [英] How to sanitize form params for use with Searchlogic? [Rails]

查看:87
本文介绍了如何清理与Searchlogic一起使用的表单参数? [路轨]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<% 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 %>

控制器

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

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

end

在这种情况下,清理参数的最佳方法是什么?用户可以轻松地修改HTML或GET请求字符串,以尝试访问他们不应该访问的其他数据.

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不支持开箱即用的可搜索范围白名单.最简单的方法是编写一种方法来清除未明确授权的所有哈希键:

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...

虽然不算好,但还不错,它一定可以完成工作.在使用meta_search的Rails 3中,您可以在模型级别将搜索范围列入白名单,这是一种更好的方法.您也可以扩展Searchlogic以实现相同的功能.

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.

这篇关于如何清理与Searchlogic一起使用的表单参数? [路轨]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆