访问rails中间件中的路由

问题描述 投票:3回答:1

如何在Rails中间件中访问Rails.application.routes?我认为通常routes.rb在堆栈中处理得更高,这就是为什么我没有真正的访问权限。我怎么能访问我的路线?

ruby-on-rails routes middleware
1个回答
1
投票

好吧,这是我的解决方案,如何注释路由文件,所以我可以在我的中间件中访问它(在本例中为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
© www.soinside.com 2019 - 2024. All rights reserved.