Class: XRealIp::Middleware
- Inherits:
-
Object
- Object
- XRealIp::Middleware
- Defined in:
- lib/x-real-ip/middleware.rb
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app) ⇒ Middleware
constructor
A new instance of Middleware.
- #is_trusted?(str) ⇒ Boolean
Constructor Details
#initialize(app) ⇒ Middleware
Returns a new instance of Middleware.
3 4 5 |
# File 'lib/x-real-ip/middleware.rb', line 3 def initialize(app) @app = app end |
Instance Method Details
#call(env) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/x-real-ip/middleware.rb', line 18 def call(env) real_ips = env["HTTP_X_REAL_IP"] if real_ips # for Rails logger env["HTTP_X_FORWARDED_FOR"] = real_ips else real_ips = env["HTTP_X_FORWARDED_FOR"] end if real_ips proxies = [] list = real_ips.split(',') return @app.call(env) if list.empty? begin list.push env["REMOTE_ADDR"] while tmp = list.pop addr = tmp if is_trusted?(tmp) proxies.push tmp else break end end if addr env["x.proxies"] = proxies.join(',') env["REMOTE_ADDR"] = addr proto = env["HTTP_X_FORWARDED_PROTO"] || env['HTTP_X_REAL_PROTO'] if (proto && proto == 'https') env["rack.url_scheme"] = 'https' end end rescue => e $stderr.puts "Error in x-real-ip: #{e.}" $stderr.puts "Backtrace:\n\t#{e.backtrace.join("\n\t")}" end end @app.call(env) end |
#is_trusted?(str) ⇒ Boolean
7 8 9 10 11 12 13 14 15 16 |
# File 'lib/x-real-ip/middleware.rb', line 7 def is_trusted?(str) begin ip = IPAddr.new(str.strip) rescue Exception => e $stderr.puts "Error in x-real-ip parsing address '#{str.strip}': #{e.}" $stderr.puts "Backtrace:\n\t#{e.backtrace.join("\n\t")}" raise e end XRealIp.trusted.any? { |proxy| proxy === ip } end |