简体   繁体   English

访问rails中间件中的路由

[英]Access routes in rails middleware

How do I access Rails.application.routes in a Rails middleware? 如何在Rails中间件中访问Rails.application.routes? I think that usually the routes.rb is being processed higher in the stack, that's why I don't have a real access to it. 我认为通常routes.rb在堆栈中处理得更高,这就是为什么我没有真正的访问权限。 How can I access my routes anyhow? 我怎么能访问我的路线?

Well, here is my solution, how to annotate the routes file, so I can access it in my middleware (in this example the Rack Attack) 好吧,这是我的解决方案,如何注释路由文件,所以我可以在我的中间件中访问它(在本例中为Rack Attack)

  file = File.read(File.expand_path('../../routes.rb', __FILE__))
  file = file.split("\n")[1..-2].join("\n") # remove first line and last line

  myroutes = Rails.application.routes
  myroutes.prepend do
    eval(file)
  end
  myroutes.clear!
  counter = 0
  myroutes.named_routes.routes.each do |route| # For each route
    extractedroute = route[1]
    if extractedroute.defaults[:attackip] != nil
      attack = extractedroute.defaults[:attackip]
      path   = extractedroute.path.spec.left.to_s  
      attack.each do |method| # For each Attack method
        counter = counter + 1
        if method[:t] != nil # If we have a throttle
          throttlename = 'throttle-'+counter.to_s+'-'+path
          Rails.logger.error 'Creating throttle: '+throttlename
          throttle(throttlename, :limit => method[:t][0], :period => method[:t][1]) do |req|
            if req.path.start_with?(path)
                req.ip
            end
          end    
        elsif method[:a] != nil
          allow2banname = 'allow2banname-'+counter.to_s+'-'+path
          Rails.logger.error 'Creating allow2ban: '+allow2banname
          Rack::Attack.blacklist(allow2banname) do |req|

            Rack::Attack::Allow2Ban.filter(allow2banname+req.ip, :maxretry => method[:a][0], :findtime => method[:a][1], :bantime => method[:a][2]) do    
              if req.path.start_with?(path) 
                true   
              end  
            end
          end
         end

      end # For all attack mechanisms
    end # If we have an attack directive
  end # EOF for all routes
  myroutes.prepend.clear

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM