Class: OAuthenticator::RackAuthenticator

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

Overview

Rack middleware to determine if the incoming request is signed authentically with OAuth 1.0.

If the request is not authentically signed, then the middleware responds with 401 Unauthorized, with the body a JSON object indicating errors encountered authenticating the request. The error object is structured like rails / ActiveResource:

{'errors' => {'attribute1' => ['messageA', 'messageB'], 'attribute2' => ['messageC']}}

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ RackAuthenticator

options:

  • :bypass - a proc which will be called with a Rack::Request, which must have a boolean result. if the result is true, authentication checking is bypassed. if false, the request is authenticated and responds 401 if not authenticated.

  • :config_methods - a Module which defines necessary methods for an SignedRequest to determine if it is validly signed. See documentation for ConfigMethods for details of what this module must implement.

  • :logger - a Logger instance to which OAuthenticator::RackAuthenticator will log informative messages

  • :realm - 401 responses include a WWW-Authenticate with the realm set to the given value. default is an empty string.



28
29
30
31
32
33
34
# File 'lib/oauthenticator/rack_authenticator.rb', line 28

def initialize(app, options = {})
  @app = app
  @options = options
  unless @options[:config_methods].is_a?(Module)
    raise ArgumentError, "options[:config_methods] must be a Module"
  end
end

Instance Method Details

#call(env) ⇒ Object

call the middleware!



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/oauthenticator/rack_authenticator.rb', line 37

def call(env)
  request = Rack::Request.new(env)

  if @options[:bypass] && @options[:bypass].call(request)
    env["oauth.authenticated"] = false
    @app.call(env)
  else
    oauth_signed_request_class = OAuthenticator::SignedRequest.including_config(@options[:config_methods])
    oauth_request = oauth_signed_request_class.from_rack_request(request)
    if oauth_request.errors
      log_unauthenticated(env, oauth_request)
      unauthenticated_response(oauth_request.errors)
    else
      log_success(env, oauth_request)
      env["oauth.signed_request"] = oauth_request
      env["oauth.consumer_key"] = oauth_request.consumer_key
      env["oauth.token"] = oauth_request.token
      env["oauth.authenticated"] = true
      @app.call(env)
    end
  end
end