How to filter parameters in rails?

前端 未结 5 692
南笙
南笙 2020-12-13 12:03

Rails has built in log filtering so you don\'t log passwords and credit cards. Works great for that but when you want to trigger a custom log (like to email) and send your

相关标签:
5条回答
  • 2020-12-13 12:56

    tadman answered correctly but here is some additional info:

    In application.rb

    config.filter_parameters += [:password, :password_confirmation, :credit_card]
    

    Wherever you are doing custom logging:

    f = ActionDispatch::Http::ParameterFilter.new(Rails.application.config.filter_parameters)
    f.filter :order => {:credit_card => "4111111111111111"}
    
     => {:order=>{:credit_card=>"[FILTERED]"}} 
    
    0 讨论(0)
  • 2020-12-13 12:57

    You can always use the except method:

    params.except(:password, :password_confirmation, :credit_card)
    

    That will exclude them from the listing. To "filter" them you could try this approach.

    0 讨论(0)
  • 2020-12-13 12:59

    Just to add on @tadman answer:

    When using except, beware that it will remove only top-level keys of your parameters, eg:

    params = {
      search_query: 'foobar', 
      secret_key1: 'SENSITIVE_KEY_1', 
      auth_info: {secret_key_2: 'SENSITIVE_KEY2'}
    }
    params.except(:secret_key1, :secret_key2)
    
    => {:search_query=>"foobar", :auth_info=>{:secret_key_2=>"SENSITIVE_KEY2"}}
    

    Using request.filtered_parameters will filter both of those keys if they are in config/application.rb

    config.filter_parameters += [:password]
    
    0 讨论(0)
  • 2020-12-13 13:02

    If you are inside a rails controller method, why not just call request.filtered_parameters?

    It is always a good choice to use what is already provided. Cheers!

    0 讨论(0)
  • 2020-12-13 13:03

    Rails 4+

    Sidenote for filtering the log in Rails 4+: The config.filter_parameters has been moved from application.rb to it's own initializer.

    config/initializers/filter_parameter_logging.rb

    Rails.application.config.filter_parameters += [:password]
    
    0 讨论(0)
提交回复
热议问题