Module: Peat::TokenManager

Defined in:
lib/peat/token_manager.rb

Class Method Summary collapse

Class Method Details

.connectionObject



22
23
24
25
26
27
28
29
30
31
# File 'lib/peat/token_manager.rb', line 22

def connection
  @connection ||= Faraday.new(url: 'https://auth.exacttargetapis.com/v1/') do |conn|
    conn.request :json

    conn.response :logger
    conn.response :json, :content_type => /\bjson$/

    conn.adapter Faraday.default_adapter
  end
end

.fetch_tokenObject



38
39
40
41
42
43
44
45
# File 'lib/peat/token_manager.rb', line 38

def fetch_token
  if @token && !token_expired?
    @token['accessToken']
  else
    @token = yield
    @token['accessToken']
  end
end

.token(fuel_client_id: nil, fuel_secret: nil) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/peat/token_manager.rb', line 5

def token(fuel_client_id: nil, fuel_secret: nil)
  fetch_token do
    client_id = fuel_client_id || ENV['FUEL_CLIENT_ID'] || $fuel_client_id
    secret = fuel_secret || ENV['FUEL_SECRET'] || $fuel_secret
    raise MissingConfiguration, 'You must set values for fuel client id and secret' unless client_id && secret

    connection.post do |req|
      req.url 'requestToken'
      req.headers['Content-Type'] = 'application/json'
      req.body = {
        'clientId' => client_id,
        'clientSecret' => secret,
      }.to_json
    end.body.merge('created_at' => Time.now)
  end
end

.token_expired?Boolean

Returns:

  • (Boolean)


33
34
35
36
# File 'lib/peat/token_manager.rb', line 33

def token_expired?
  # token is good for an hour, but to be safe...
  Time.now > 50.minutes.since(@token['created_at']) 
end