使用config.filter_parameters自定义过滤rails 3中的参数

kei*_*ley 5 ruby ruby-on-rails ruby-on-rails-3 rails-3-upgrade

我正在升级从Rails的2.3.11到3.0.10,和我有麻烦将是什么在ApplicationControllerfilter_parameter_logging.我想过滤某些参数,如果它们出现在像:referrer标签这样的值中,也会对它们进行过滤.

我可以在我的网站中过滤掉常规参数 application.rb

config.filter_parameters += [:password, :oauth, ...]
Run Code Online (Sandbox Code Playgroud)

但我遇到的问题是我们也在filter_parameter_logging中传递的块.它还会过滤掉任何看起来像网址的值中的参数,因此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
Run Code Online (Sandbox Code Playgroud)

有没有一种方法,使导轨过滤器使用这种方式config.filter_parametersapplication.rb?我似乎无法找到有关如何在rails 3中自定义过滤的任何好文档.

kei*_*ley 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
Run Code Online (Sandbox Code Playgroud)