Module: CTAAggregatorClient::API::Authenticator

Extended by:
Utilities
Defined in:
lib/cta_aggregator_client/api/authenticator.rb

Defined Under Namespace

Classes: Auth

Constant Summary collapse

THREE_HOURS =
10800

Class Method Summary collapse

Methods included from Utilities

api_key, api_secret, api_version, auth_url, base_url, default_headers, headers_with_auth_creds

Class Method Details

.authObject



17
18
19
# File 'lib/cta_aggregator_client/api/authenticator.rb', line 17

def auth
  @auth ||= generate_auth
end

.default_token_expirationObject



31
32
33
34
35
# File 'lib/cta_aggregator_client/api/authenticator.rb', line 31

def default_token_expiration
  # API is more lenient on token expriation (way over 3 hours).
  # We're keeping low expiration here to avoid dealing with expired tokens.
  Time.now + THREE_HOURS
end

.generate_authObject



21
22
23
24
25
26
27
28
29
# File 'lib/cta_aggregator_client/api/authenticator.rb', line 21

def generate_auth
  raw_response = RestClient.post(auth_url, nil, headers_with_auth_creds)
  token = raw_response.code == 201 ? JSON.parse(raw_response.body)["jwt"] : nil

  Auth.new(
    token,
    default_token_expiration
  )
end

.headers_with_authenticationObject



12
13
14
15
# File 'lib/cta_aggregator_client/api/authenticator.rb', line 12

def headers_with_authentication 
  reset_auth unless Time.now < auth.expiration
  default_headers.merge(authorization: "Bearer: #{auth.token}")
end

.reset_authObject



37
38
39
# File 'lib/cta_aggregator_client/api/authenticator.rb', line 37

def reset_auth
  @auth = nil
end