class RestClientWrapper::Authenticator::Oauth

Oauth

Attributes

client_id[R]

Public Class Methods

authenticate(client_id:, access_token: nil) click to toggle source
# File lib/rest_client_wrapper/authenticators/oauth.rb, line 60
def self.authenticate(client_id:, access_token: nil)
  # Ensure that other threads aren't checking and updating the token at the same time
  @@api_client[client_id][:lock].synchronize do
    # Return access_token from @@api_client when the current_token is different to what's in @@api_client as it's already been refreshed
    return @@api_client[client_id][:access_token] if !access_token.nil? && !@@api_client[client_id][:access_token].nil? && @@api_client[client_id][:access_token].casecmp(access_token).nonzero?

    payload = {
      grant_type:    GrantType::CLIENT_CREDENTIALS,
      client_id:     client_id,
      client_secret: @@api_client&.[](client_id)&.[](:settings)&.[](:client_secret)
    }
    url = "#{ @@api_client&.[](client_id)&.[](:settings)&.[](:site) }#{ @@api_client&.[](client_id)&.[](:settings)&.[](:token_url_path) }"

    response = ::RestClient::Request.execute({ method: :post, url: url, payload: payload })

    if Http.ok?(response.code)
      content_type = MIME::Types[response&.headers&.[](:content_type)].first
      raise StandardError "Unable to retreive token, response was in a unexpected format" unless content_type == "application/json"

      token_payload = JSON.parse(response.body)
      @@api_client[client_id][:access_token] = token_payload["access_token"]
      @@api_client[client_id][:refresh_token] = token_payload["refresh_token"]
    end
  end
end
new(client_id:, **config) click to toggle source
# File lib/rest_client_wrapper/authenticators/oauth.rb, line 39
def initialize(client_id:, **config)
  @client_id = client_id
  @@api_client[client_id] = { lock: Mutex.new, settings: config, access_token: nil, refresh_token: nil }
end

Public Instance Methods

access_token() click to toggle source
# File lib/rest_client_wrapper/authenticators/oauth.rb, line 48
def access_token
  return @@api_client&.[](@client_id)&.[](:access_token)
end
generate_auth() click to toggle source
# File lib/rest_client_wrapper/authenticators/oauth.rb, line 52
def generate_auth
  Authenticator::Oauth.authenticate({ client_id: @client_id }) if @@api_client&.[](@client_id)&.[](:access_token).nil?
  access_token = @@api_client&.[](@client_id)&.[](:access_token)
  raise StandardError "Unable to authenticate #{ @client_id }" if @@api_client&.[](@client_id)&.[](:access_token).nil?

  return { Authorization: "Bearer #{ access_token }" }
end
tokens() click to toggle source
# File lib/rest_client_wrapper/authenticators/oauth.rb, line 44
def tokens
  return @@api_client
end