【问题标题】:Access routes in rails middlewareRails 中间件中的访问路由
【发布时间】:2016-02-22 15:49:24
【问题描述】:

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

【问题讨论】:

  • 您想在需要 Rails 路由知识的中间件中做什么?
  • 我想通过在 routes.rb 中添加路由指令来增强 Rack Attack (github.com/kickstarter/rack-attack),用于描述如何保护每条路径。这个想法是在 routes.rb 文件中添加元数据,并且 Rack Attack gem 将根据路由文件中存在的信息自动生成正确的限制。这样一来,它将更加高效和一致。因此,当您向路由文件添加新路径时,它将自动受到保护。我需要能够以编程方式解析/处理路由文件。
  • 是的,这似乎是一个合法的理由。虽然我个人不知道如何实现这一点,但也许有人知道。
  • 好的,我已经创建了一个解决方案。像魅力一样工作,但我不能发布它,因为出于某种原因,stackoverflow 决定不接受我的帐户中的解决方案......耻辱。
  • @NadavB 我们正在寻找同样的东西。您可以在 github 或 gist 上的某个地方发布您的解决方案吗?谢谢!

标签: ruby-on-rails routes middleware


【解决方案1】:

好吧,这是我的解决方案,如何注释路由文件,以便我可以在我的中间件中访问它(在本例中为机架攻击)

  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

【讨论】:

    猜你喜欢
    • 2011-03-16
    • 1970-01-01
    • 2017-06-12
    • 2016-02-14
    • 2022-06-29
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多