Class: SimpleApiAuth::Middleware

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

Constant Summary collapse

@@api_path_matcher =
/^\/api\//
@@unauthorized_response =
[401, {"Content-Type" => "text/plain"}, ['{ "message": "Unauthenticated." }']]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



12
13
14
# File 'lib/simple_api_auth/simple_api_auth.rb', line 12

def initialize(app)
  @app = app
end

Class Method Details

.api_key=(key) ⇒ Object



8
9
10
# File 'lib/simple_api_auth/simple_api_auth.rb', line 8

def self.api_key=(key)
  @@api_key = key
end

Instance Method Details

#call(env) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/simple_api_auth/simple_api_auth.rb', line 16

def call(env)
  path  = env['PATH_INFO']
  if path =~ @@api_path_matcher
    api_key = env["HTTP_AUTHORIZATION"] || Rack::Request.new(env).params['api_key']
    unless api_key == @@api_key
      env['rack.errors'].write "throw 401 from SimpleApiAuth. got api_key: #{api_key.inspect} \n"
      return @@unauthorized_response
    end
  end

  @app.call(env)
end