Class: Napa::Middleware::Authentication

Inherits:
Object
  • Object
show all
Defined in:
lib/napa/middleware/authentication.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Authentication

Returns a new instance of Authentication.



4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/napa/middleware/authentication.rb', line 4

def initialize(app)
  @app = app
  @old_allowed_passwords = []
  @allowed_header_passwords = []

  if ENV['HEADER_PASSWORDS']
    @old_allowed_passwords += ENV['HEADER_PASSWORDS'].split(',').map(&:strip).freeze
  end

  if ENV['ALLOWED_HEADER_PASSWORDS']
    @allowed_header_passwords += ENV['ALLOWED_HEADER_PASSWORDS'].split(',').map(&:strip).freeze
  end
end

Instance Method Details

#authenticated_request?(env) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
35
36
37
38
39
40
41
# File 'lib/napa/middleware/authentication.rb', line 32

def authenticated_request?(env)
  return if @old_allowed_passwords.blank? && @allowed_header_passwords.blank?

  if env['HTTP_PASSWORDS'].present?
    possible_passwords = env['HTTP_PASSWORDS'].to_s.split(',')
    (@allowed_header_passwords & possible_passwords).any?
  else
    @old_allowed_passwords.include? env['HTTP_PASSWORD']
  end
end

#call(env) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/napa/middleware/authentication.rb', line 18

def call(env)
  if authenticated_request?(env)
    @app.call(env)
  else
    unless @old_allowed_passwords.blank? && @allowed_header_passwords.blank?
      error_response = Napa::JsonError.new('bad_password', 'bad password').to_json
    else
      error_response = Napa::JsonError.new('not_configured', 'password not configured').to_json
    end

    [401, { 'Content-type' => 'application/json' }, Array.wrap(error_response)]
  end
end