Class: Pushlet::AuthMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/pushlet/auth_middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, username, password) ⇒ AuthMiddleware

Returns a new instance of AuthMiddleware.



3
4
5
6
7
# File 'lib/pushlet/auth_middleware.rb', line 3

def initialize(app, username, password)
  @app = app
  @username = username
  @password = password
end

Instance Method Details

#call(env) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/pushlet/auth_middleware.rb', line 9

def call(env)
  return error_json if env['HTTP_AUTHORIZATION'].nil? || env['HTTP_AUTHORIZATION'] == ''

  begin
      username, password = Base64.strict_decode64(env['HTTP_AUTHORIZATION'].split('Basic ').last).split(':')
  rescue
    return error_json
  end

  return error_json if username != @username || password != @password

  @app.call env
end

#error_json(type = 'access denied', message = 'invalid credentials') ⇒ Object



23
24
25
26
27
# File 'lib/pushlet/auth_middleware.rb', line 23

def error_json(type='access denied', message='invalid credentials')
  payload = {error: {type: type, message: message}}.to_json

  [200, {'Content-Type' => 'application/json', 'Content-Length' => payload.length.to_s}, [payload]]
end