Class: Auth::ClientCredentials::Service

Inherits:
Common::Client::Base show all
Defined in:
lib/lighthouse/auth/client_credentials/service.rb

Instance Method Summary collapse

Methods inherited from Common::Client::Base

configuration, #raise_backend_exception

Methods included from SentryLogging

#log_exception_to_sentry, #log_message_to_sentry, #non_nil_hash?, #normalize_level, #rails_logger

Constructor Details

#initialize(token_url, api_scopes, client_id, aud_claim_url, rsa_key, service_name = nil) ⇒ Service

rubocop:disable Metrics/ParameterLists

Parameters:

  • token_url (String)
    • URL of the token endpoint

  • api_scopes (Array)
    • List of requested API scopes

  • client_id (String)
    • ID used to identify the application

  • aud_claim_url (String)
    • The claim URL used as the ‘aud’ portion of the JWT

  • rsa_key (String)
    • RSA key used to encode the authentication JWT

  • service_name (String) (defaults to: nil)
    • name to use when caching access token in Redis (Optional)



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/lighthouse/auth/client_credentials/service.rb', line 22

def initialize(token_url, api_scopes, client_id, aud_claim_url, rsa_key, service_name = nil)
  @url = token_url
  @scopes = api_scopes
  @client_id = client_id
  @aud = aud_claim_url
  @rsa_key = rsa_key
  @service_name = service_name

  @tracker = AccessTokenTracker
  super()
end

Instance Method Details

#get_token(auth_params = {}) ⇒ String

Request an access token

Returns:

  • (String)

    the access token needed to make requests



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/lighthouse/auth/client_credentials/service.rb', line 40

def get_token(auth_params = {})
  if @service_name.nil?
    res = get_new_token(auth_params)
    return res.body['access_token']
  end

  access_token = @tracker.get_access_token(@service_name)

  if access_token.nil?
    uuid = SecureRandom.uuid
    log_info(message: 'Access token expired. Fetching new token', service_name: @service_name, uuid:)

    res = get_new_token(auth_params)
    access_token = res.body['access_token']
    ttl = res.body['expires_in']
    @tracker.set_access_token(@service_name, access_token, ttl)

    log_info(message: "New access token deposited in Redis store with TTL: #{ttl}",
             service_name: @service_name, uuid:)
  end

  access_token
end