Module: Workarea::Listrak::Oauth

Defined in:
app/services/workarea/listrak/oauth.rb

Class Method Summary collapse

Class Method Details

.token(client_id:, client_secret:, **options) ⇒ String

Generates an oauth token for a client_id and client_secret.

Parameters:

  • client_id (String)

    client id

  • client_secret (String)

    client secret

  • options (Hash)

    extra options when getting the OAuth token

Options Hash (**options):

  • timeout (Integer)

    value for open and read timeouts

  • open_timeout (Integer)

    value for open timeout

  • read_timeout (Integer)

    value for read timeout

Returns:

  • (String)

    Oauth token

Raises:

  • (OauthError)

    raised if generating an Oauth token is unsucessful



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'app/services/workarea/listrak/oauth.rb', line 16

def self.token(client_id:, client_secret:, **options)
  cache_key = "listrak/api/#{client_id}"
  token = Rails.cache.read(cache_key)

  return token if token.present?

  uri = URI('https://auth.listrak.com/OAuth2/Token')
  params = {
    grant_type: 'client_credentials',
    client_id: client_id,
    client_secret: client_secret
  }

  response = Net::HTTP.post_form uri, params

  case response
  when ::Net::HTTPSuccess
    body = JSON.parse response.body
    token = body["access_token"]
    expiry = body["expires_in"] - 60

    Rails.cache.write(cache_key, token, expires_in: expiry)
    token
  else
    raise OauthError.new response
  end
end