Class: Miron::Middleware::BasicAuth

Inherits:
Object
  • Object
show all
Defined in:
lib/miron/middleware/basic_auth.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ BasicAuth

Returns a new instance of BasicAuth


6
7
8
9
# File 'lib/miron/middleware/basic_auth.rb', line 6

def initialize(args)
  @username = args[0]
  @password = args[1]
end

Instance Attribute Details

#requestObject (readonly)

Returns the value of attribute request


4
5
6
# File 'lib/miron/middleware/basic_auth.rb', line 4

def request
  @request
end

#responseObject (readonly)

Returns the value of attribute response


4
5
6
# File 'lib/miron/middleware/basic_auth.rb', line 4

def response
  @response
end

Instance Method Details

#auth_clearedObject


18
19
20
# File 'lib/miron/middleware/basic_auth.rb', line 18

def auth_cleared
  true
end

#authorization_keyObject


22
23
24
25
# File 'lib/miron/middleware/basic_auth.rb', line 22

def authorization_key
  authorization_keys = ['HTTP_AUTHORIZATION', 'HTTP_X-HTTP_AUTHORIZATION', 'HTTP_X_HTTP_AUTHORIZATION']
  @authorization_key ||= authorization_keys.detect { |key| @request.hash.key?(key) } || nil
end

#bad_requestObject


27
28
29
30
31
32
# File 'lib/miron/middleware/basic_auth.rb', line 27

def bad_request
  @response.http_status = 400
  @response.headers = { 'Content-Type' => 'text/plain', 'Content-Length' => '0' }
  @response.body = ''
  @response
end

#call(request, response) ⇒ Object


11
12
13
14
15
16
# File 'lib/miron/middleware/basic_auth.rb', line 11

def call(request, response)
  @request = request
  @response = response
  return unauthorized if authorization_key.nil?
  check_auth
end

#check_authObject


34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/miron/middleware/basic_auth.rb', line 34

def check_auth
  # Get Auth Scheme and encoded username/password
  auth_key = @request.hash[authorization_key].split(' ', 2)
  scheme = auth_key.first && auth_key.first.downcase
  return bad_request if scheme != 'basic'

  # Validate credentials
  decrypted_auth_key = auth_key.last.unpack('m*').first.split(/:/, 2)
  if [@username, @password] == decrypted_auth_key
    return auth_cleared
  else
    return unauthorized
  end
end

#unauthorizedObject


49
50
51
52
53
54
55
56
57
# File 'lib/miron/middleware/basic_auth.rb', line 49

def unauthorized
  @response.http_status = 401
  @response.headers = { 'Content-Type' => 'text/plain',
                        'Content-Length' => '0',
                        'WWW-Authenticate' => 'Basic realm="Login"'
                      }
  @response.body = ''
  @response
end