2012-03-12 60 views
5

我在我的rails 3应用程序中使用rack-throttle作为限速引擎。我已经根据Rack::Throttle::Interval创建了自己的类来定义自定义速率限制逻辑。我正在检查请求是否是针对确切的控制器和确切的操作。如果我请GET请求,这工作正常。但是,如果我发送POST请求我得到一些问题。在rails应用程序中限制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增加都源于确切控制器的动作准确发送大量POST请求自定义限制器

+0

你如何插入机架::油门::区间在您的应用程序? – shingara 2012-03-12 08:55:21

+0

@shingara 它包含在'application.rb'中 – RomanKapitonov 2012-03-12 10:40:17

+0

允许?方法是否在POST方法中调用?你可以在你的应用程序中添加这个中间件吗? – shingara 2012-03-12 10:48:44

回答

2

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

尝试用:

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

毕竟方法可以工作,我想。

+1

我仍然收到以下'RuntimeError:路由集未完成 from /home/rkapitonov/.rvm/gems/ruby-1.9.2-p290/gems/rack-mount-0.8.3/lib/rack/mount/route_set .rb:81:在搭建时执行以下'Rails.application.routes.recognize_path(request.url,{:method => request.request_method})' – RomanKapitonov 2012-03-12 11:22:22

0

这一个工作对我来说,捕获所有的POST请求,并忽略GET请求:

class CustomLimiter < Rack::Throttle::Interval 

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

end 
相关问题