访问rails中间件中的路由
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了访问rails中间件中的路由相关的知识,希望对你有一定的参考价值。
如何在Rails中间件中访问Rails.application.routes?我认为通常routes.rb在堆栈中处理得更高,这就是为什么我没有真正的访问权限。我怎么能访问我的路线?
答案
好吧,这是我的解决方案,如何注释路由文件,所以我可以在我的中间件中访问它(在本例中为Rack Attack)
file = File.read(File.expand_path('../../routes.rb', __FILE__))
file = file.split("
")[1..-2].join("
") # 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
以上是关于访问rails中间件中的路由的主要内容,如果未能解决你的问题,请参考以下文章
以下代码片段是不是容易受到 Rails 5 中 SQL 注入的影响?