Class: MAuth::Rack::RequestAuthenticator

Inherits:
Middleware
  • Object
show all
Defined in:
lib/mauth/rack.rb

Overview

middleware which will check that a request is authentically signed.

if the request is checked and is not authentic, 401 Unauthorized is returned and the app is not called.

options accepted (key may be string or symbol)

  • should_authenticate_check: a proc which should accept a rack env as an argument, and return true if the request should be authenticated; false if not. if the result from this is false, the request is passed to the app with no authentication performed.

Instance Method Summary collapse

Methods inherited from Middleware

#initialize, #mauth_client

Constructor Details

This class inherits a constructor from MAuth::Middleware

Instance Method Details

#call(env) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/mauth/rack.rb', line 17

def call(env)
  if should_authenticate?(env)
    mauth_request = MAuth::Rack::Request.new(env)
    begin
      if mauth_client.authentic?(mauth_request)
        @app.call(env.merge('mauth.app_uuid' => mauth_request.signature_app_uuid, 'mauth.authentic' => true))
      else
        response_for_inauthentic_request(env)
      end
    rescue MAuth::UnableToAuthenticateError
      response_for_unable_to_authenticate(env)
    end
  else
    @app.call(env)
  end
end

#handle_head(env) ⇒ Object

discards the body if REQUEST_METHOD is HEAD. sets the Content-Length.



35
36
37
38
39
# File 'lib/mauth/rack.rb', line 35

def handle_head(env)
  status, headers, body = *yield
  headers["Content-Length"] = body.map(&:bytesize).inject(0, &:+).to_s
  [status, headers, env['REQUEST_METHOD'].casecmp('head').zero? ? [] : body]
end

#response_for_inauthentic_request(env) ⇒ Object

response when the request is inauthentic. responds with status 401 Unauthorized and a message.



48
49
50
51
52
53
# File 'lib/mauth/rack.rb', line 48

def response_for_inauthentic_request(env)
  handle_head(env) do
    body = { 'errors' => { 'mauth' => ['Unauthorized'] } }
    [401, { 'Content-Type' => 'application/json' }, [JSON.pretty_generate(body)]]
  end
end

#response_for_unable_to_authenticate(env) ⇒ Object

response when the authenticity of the request cannot be determined, due to a problem communicating with the MAuth service. responds with a status of 500 and a message.



58
59
60
61
62
63
# File 'lib/mauth/rack.rb', line 58

def response_for_unable_to_authenticate(env)
  handle_head(env) do
    body = { 'errors' => { 'mauth' => ['Could not determine request authenticity'] } }
    [500, { 'Content-Type' => 'application/json' }, [JSON.pretty_generate(body)]]
  end
end

#should_authenticate?(env) ⇒ Boolean

whether the request needs to be authenticated

Returns:

  • (Boolean)


42
43
44
# File 'lib/mauth/rack.rb', line 42

def should_authenticate?(env)
  @config['should_authenticate_check'] ? @config['should_authenticate_check'].call(env) : true
end