Class: Authlete::AuthenticationServer

Inherits:
Object
  • Object
show all
Defined in:
lib/authlete/authentication-server.rb

Overview

Authlete::AuthenticationServer class

This class is a base class for an authentication server based on Rack. Some method must/should be overridden by subclasses.

  1. authenticate_api_call

  2. authenticate_user

  3. collect_claims

  4. authentication_callback_endpoint_path

Instance Method Summary collapse

Constructor Details

#initialize(app = nil) ⇒ AuthenticationServer

Returns a new instance of AuthenticationServer.



32
33
34
35
36
# File 'lib/authlete/authentication-server.rb', line 32

def initialize(app = nil)
  # Accept 'app' so that this class can work as a Rack middleware
  # as well as a Rack application.
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/authlete/authentication-server.rb', line 38

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

  # If the request is not an authentication callback request.
  if match_authentication_callback_request(request) == false
    # If this class is used as a Rack middleware.
    if @app && @app.respond_to?(:call)
      # Call chain to the next Rack middleware.
      return @app.call(env)
    else
      # 404 Not Found
      return generate_not_found(request)
    end
  end

  # Basic Authentication for the API call.
  authenticated = do_authenticate_api_call(env)
  if authenticated == false
    # 401 Unauthorized
    return generate_api_call_authentication_failure()
  end

  begin
    # Parse the request body as AuthenticationCallbackRequest.
    req = parse_authentication_callback_request(request)
  rescue => e
    # 400 Bad Request
    return generate_authentication_callback_request_format_error(e)
  end

  # Prepare an empty response.
  res = Authlete::Model::Response::AuthenticationCallbackResponse.new

  # Let the subclass authenticate the end-user.
  # When authenticated successfully, a non-nil value is returned.
  subject = authenticate_user(req)
  if subject.nil?
    # End-user authentication failed.
    # Return {"authenticated": false} to Authlete.
    res.authenticated = false
    return res.to_rack_response
  end

  # The end-user has been authenticated successfully.
  res.authenticated = true
  res.subject       = subject

  if req.claims.nil? == false && req.claims.length != 0
    # Make the subclass collect values of the requested claims.
    res.claims = collect_claims(req, subject)
  end

  # Return {"authenticated": true, ...} to Authlete.
  return res.to_rack_response
end