【问题标题】:Sanitize SQL in custom conditions在自定义条件下清理 SQL
【发布时间】:2010-12-14 04:33:37
【问题描述】:

我需要创建一个简单的搜索,但我负担不起使用 Sphinx。

这是我写的:


keywords = input.split(/\s+/)
queries = []

keywords.each do |keyword|
  queries << sanitize_sql_for_conditions(
              "(classifications.species LIKE '%#{keyword}%' OR 
               classifications.family LIKE '%#{keyword}%' OR 
               classifications.trivial_names LIKE '%#{keyword}%' OR
               place LIKE '%#{keyword}%')")
end

options[:conditions] = queries.join(' AND ')

现在,sanitize_sql_for_conditions 不起作用!它返回只是返回原始字符串。

如何重写此代码以逃避恶意代码?

【问题讨论】:

  • 你是什么意思你不能使用 Sphinx?它是免费的!

标签: sql ruby-on-rails sanitize


【解决方案1】:

如果您将“#{keyword}”替换为“?”,您可以执行以下操作。使用问号会自动清理 SQL。

keywords = input.split(/\s+/)
queries = []
vars = []

keywords.each do |keyword|
  queries << "(classifications.species LIKE '%?%' OR 
               classifications.family LIKE '%?%' OR 
               classifications.trivial_names LIKE '%?%' OR
               place LIKE '%?%')"
  vars = vars << keyword << keyword << keyword << keyword
end

options[:conditions] = [queries.join(' AND '), vars].flatten

【讨论】:

    【解决方案2】:

    我在 ActiveRecord 中使用了很多自定义条件,但我喜欢将它们打包到条件数组的数组中,然后使用 ? value 让 AR 自动清理它们:

    conditions = Array.new
    conditions << ["name = ?", "bob"]
    conditions << ["(created_at > ? and created_at < ?)", 1.year.ago, 1.year.from_now]  
    
    User.find(:first, :conditions => combine_conditions(conditions))
    
     def combine_conditions(somearray) # takes an array of condition set arrays and reform them into a AR-compatible condition array
       conditions = Array.new
       values = Array.new
       somearray.each do |conditions_array|
         conditions << conditions_array[0] # place the condition in an array
         # extract values
         for i in (1..conditions_array.size - 1)
           values << conditions_array[i]
         end 
       end
       [conditions.join(" AND "), values].flatten
     end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-12
      • 2017-11-28
      • 2011-04-24
      • 1970-01-01
      • 2019-07-01
      • 2020-01-19
      • 1970-01-01
      • 2015-03-16
      相关资源
      最近更新 更多