【问题标题】:upgrade from rack-attack 6.3.1 to 6.5.0 is giving error on custom methods从 rack-attack 6.3.1 升级到 6.5.0 导致自定义方法出错
【发布时间】:2021-07-21 09:33:01
【问题描述】:

从 rack-attack 6.3.1 升级到 6.5.0 时,请求对象无法获取任何自定义方法

当我运行 request.comment 时,它会抛出以下错误

#Hash:0x00007fd2b4f41530 的未定义方法 `comment'

根据文档,我将方法从 throttled_callback 更新为 throttled_response

Rack::Attack.throttled_response = lambda do |request|
  details = {restriction: {name: 'asdas', comment: request.comment}}

  
  if Feature.enabled?(:some_feature)
    restrict_user(request.token, details) if request.update_password?
  end
end


I have added a lot of method but now after upgradating unable to access any of the method inside the throttled_callback

class Rack::Attack
  class Request < ::Rack::Request
    ##
    ## Helper Functions
    ##
    # Get the real IP Address of the user/client
    attr_accessor :comment

    def remote_ip
      @remote_ip ||= get_header('HTTP_X_FORWARDED_FOR').try(:to_s)
    end

    def body_params
      unless @body_params 
        @body_params = JSON.parse(body.read)
        body.rewind
      end
      @body_params
    end

    def username
      (body_params["username"]).to_s.downcase
    end

    def login?
      self.path == '/user_sign_in'
    end
end

throttle("ip:user-key-min", limit: 10, period: 1.minute) do |req|
  if req.login?
    req.comment = "some comment"
    req.remote_ip
  end
end

当我在节流响应中时。因此,升级到最新版本的 rack-attack 后,请求对象无法访问 Request 类中的评论或任何方法。在 request 对象的 6.3.1 版本中,我能够从class Request 在throttled_callback

中访问该方法
request.methods
[ :comment, :username, , :comment=, :body_params, :remote_ip, :login?]

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-6.1 rackattack


    【解决方案1】:

    throttled_response 的实现与throttled_callback 的实现并不完全相同。在throttled_callback 中,请求对象是可访问的,因此您可以访问所有方法,但在throttled_response 中传递了env 对象。

    参见throttled_response 实现here

    Rack::Attack.throttled_response = lambda do |env|
      # NB: you have access to the name and other data about the matched throttle
      #  env['rack.attack.matched'],
      #  env['rack.attack.match_type'],
      #  env['rack.attack.match_data'],
      #  env['rack.attack.match_discriminator']
    
      # Using 503 because it may make attacker think that they have successfully
      # DOSed the site. Rack::Attack returns 429 for throttling by default
      [ 503, {}, ["Server Error\n"]]
    end
    

    【讨论】:

    • 我理解方法定义不同。我的问题是,如果我必须使用自定义方法,那么我如何将它与 throttled_response 一起使用。另外,你给的链接是错误的。
    • 嘿,我已经更新了上面评论中的链接。要调用自定义方法,您需要在 throttled_response 方法中有一些对象。根据实现,只有 ENV 被传递给它。
    • 某个对象是什么意思?您能否通过显示 request.comment 或 object.comment 可访问来举例说明
    猜你喜欢
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 2017-12-24
    • 1970-01-01
    • 2018-02-25
    • 2019-01-01
    相关资源
    最近更新 更多