Class: BasicAuthMark::Middleware

Inherits:
Object
  • Object
show all
Includes:
Rack::Utils
Defined in:
lib/basic_auth_mark/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



5
6
7
# File 'lib/basic_auth_mark/middleware.rb', line 5

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/basic_auth_mark/middleware.rb', line 9

def call(env)
  status, headers, response = @app.call(env)

  return [status, headers, response] unless headers['Content-Type'].to_s =~ %r{\btext/html\b}i
  return [status, headers, response] if status >= 300 && status < 400

  markable_ip_addresses = BasicAuthMark.markable_ip_addresses

  request = Rack::Request.new(env)

  if markable_ip_addresses.empty? || markable_ip_addresses.include?(request.ip)
    basic_request = Rack::Auth::Basic::Request.new(env)

    if basic_request.provided? && basic_request.basic?
      new_body = ''
      response.each do |b|
        begin
          new_body << insert_basic_auth_marks(b)
        rescue => exception
          $stderr.write %Q|Failed to insert basic auth marks: #{exception.message}\n  #{exception.backtrace.join("  \n")}|
        end
      end
      response.close if response.respond_to?(:close)
      headers['Content-Length'] &&= new_body.bytesize.to_s
      response = [new_body]
    end
  end

  [status, headers, response]
end