Module: Workarea::Listrak::Oauth

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

Class Method Summary collapse

Class Method Details

.httpObject



36
37
38
39
40
# File 'app/services/workarea/listrak/oauth.rb', line 36

def self.http
  @http ||= Net::HTTP.new('auth.listrak.com', 443).tap do |client|
    client.use_ssl = true
  end
end

.token(client_id:, client_secret:) ⇒ String

Generates an oauth token for a client_id and client_secret.

Parameters:

  • client_id (String)

    client id

  • client_secret (String)

    client secret

Returns:

  • (String)

    Oauth token

Raises:

  • (OauthError)

    raised if generating an Oauth token is unsucessful



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/services/workarea/listrak/oauth.rb', line 10

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

  return token if token.present?

  payload = {
    grant_type: 'client_credentials',
    client_id: client_id,
    client_secret: client_secret
  }
  response = http.post('/OAuth2/Token', payload.to_json)

  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