在rails应用程序中限制POST请求

时间:2012-03-12 06:48:16

标签: ruby-on-rails ruby rack throttling rate-limiting

我在我的rails 3应用程序中使用rack-throttle作为速率限制引擎。我已经基于Rack::Throttle::Interval创建了自己的类来定义自定义速率限制逻辑。我正在检查请求是否是针对确切的控制器和确切的操作。如果我发出GET请求,这样可以正常工作。但是,如果我发送POST请求,我会遇到一些问题。

class CustomLimiter < Rack::Throttle::Interval
  def allowed?(request)
    path_info = Rails.application.routes.recognize_path request.url rescue path_info = {} 
    if path_info[:controller] == "some_controller" and path_info[:action] == "some_action"
      super
    else
      true
    end
  end
end

以下是我的控制器操作

def question
  #user is redirected here
end

def check_answer
  #some logic to check answer
  redirect_to question_path
end

我的路线

get "questions" => "application#question", :as => "question"
post "check_answer" => "application#check_answer", :as => "check_answer"

编辑:

问题是POST请求即将到来,以便调用方法allowed?。但是,当我致电Rails.application.routes.recognize_path时,我得到Route set not finalized例外。如何在rack-throttle

的帮助下阻止用户针对确切控制器的确切操作发送大量帖子请求

中间件已添加到application.rb

class Application < Rails::Application
  #Set up rate limiting
  config.require "ip_limiter"
  config.require "ip_user_agent_limiter"
  config.middleware.use IpLimiter, :min => 0.2
  config.middleware.use IpUserAgentLimiter, :min => 2
end

IpLimiterIpUserAgentLimiter都来自自定义限制器

2 个答案:

答案 0 :(得分:2)

在阅读了Rails.application.routes.recognize_path(http://apidock.com/rails/ActionDispatch/Routing/RouteSet/recognize_path)的代码之后,这个方法获得了第二个args,您可以在其中传递METHOD。

尝试:

path_info = Rails.application.routes.recognize_path(request.url, {:method => request.request_method}) rescue path_info = {} 

我认为所有方法都可行。

答案 1 :(得分:0)

这个对我有用,可以捕获所有POST请求,并忽略所有GET请求:

class CustomLimiter < Rack::Throttle::Interval

  def allowed?(request)
    return true unless request.request_method == "POST"
    super request
  end

end