5

我正在从 Rails 2.3.11 升级到 3.0.10,并且在转换ApplicationController. filter_parameter_logging我想过滤某些参数,如果它们出现在:referrer标签之类的值中,也要过滤它们。

我可以在我的application.rb

config.filter_parameters += [:password, :oauth, ...]

但我遇到的问题是我们也在 filter_parameter_logging 中传递的块。它还过滤掉任何看起来像 url 的值中的参数,所以类似的东西http://example.com?password=foobar&oauth=123foo&page=2会被记录为http://example.com?password=[FILTERED]&oauth=[FILTERED]&page=2. 我需要一种方法让 rails 既可以过滤指定的参数,又可以仅从其他值中过滤掉那些参数,例如上面的 url。

这是它在 filter_parameter_logging 中的样子:

FILTER_WORDS = %{password oauth email ...} 
FILTER_WORDS_REGEX = /#{FILTER_WORDS.join("|")}/i

#Captures param in $1 (would also match things like old_password, new_password), and value in $2
FILTER_WORDS_GSUB_REGEX = /((?:#{FILTER_WORDS.join("|")})[^\/?]*?)(?:=|%3D).*?(&|%26|$)/i

filter_parameter_logging(*FILTER_WORDS) do |k,v|
  begin
    # Bail immediately if we can
    next unless v =~ FILTER_WORDS_REGEX && (v.index("=") || v.index("%3D"))

    #Filters out values for params that match
    v.gsub!(FILTER_WORDS_GSUB_REGEX) do
      "#{$1}=[FILTERED]#{$2}"
    end
  rescue Exception => e
    logger.error e
  end
end

config.filter_parameters有没有办法使用in以这种方式制作 rails 过滤器application.rb?我似乎找不到任何关于如何在 rails 3 中自定义过滤的好文档。

4

1 回答 1

6

弄清楚了。您可以将 lambda 语句传递给config.filter_parameters,所以在我将参数添加到过滤器之后,我现在有了这个:

config.filter_parameters << lambda do |k,v|
  begin
    # Bail immediately if we can
    next unless v =~ FILTER_WORDS_REGEX && (v.index("=") || v.index("%3D"))

    #Filters out values for params that match
    v.gsub!(FILTER_WORDS_GSUB_REGEX) do
      "#{$1}=[FILTERED]#{$2}"
    end
  rescue Exception => e
    logger.error e
  end
end
于 2011-10-03T15:38:53.467 回答