module Nordea::Siirto::AccessToken

Responsible for fetching access token from the server, and memoizing it.

Constants

EXPIRATION_BUFFER
KEY

Store current access token into REDIS

MUTEX

Public Instance Methods

access_token() click to toggle source

Fetches access token from server if previous token has expired Memoizes token, and sets expiration time, with some buffer. @return [String] rubocop:disable MethodLength

# File lib/nordea/siirto/access_token.rb, line 17
def access_token
  # Synchronization is needed, otherwise race condition may ensue:
  # Let's assume token has expired, and two threads ask for a new token.
  # Both proceed to fetch the token from remote server, both return,
  # but the first token is no longer valid.
  MUTEX.synchronize do
    token = Nordea::Siirto.redis.get(KEY)
    return token if token

    Nordea::Siirto.log('Requesting new access token...')
    payload = response.body

    token = payload['access_token']
    expires_in = payload['expires_in'] - EXPIRATION_BUFFER
    Nordea::Siirto.redis.set(KEY, token)
    Nordea::Siirto.redis.expire(KEY, expires_in)

    token
  end
end
request() click to toggle source

@return Nordea::Siirto::Request rubocop:disable MethodLength

# File lib/nordea/siirto/access_token.rb, line 46
def request
  request = Nordea::Siirto::Request.new
  request.uri = uri
  request.method = 'POST'
  request.headers = {
    'Accept' => 'application/json',
    'Content-Type' => 'application/x-www-form-urlencoded'
  }
  request.body = {
    grant_type: 'password',
    username:   Nordea::Siirto.username,
    password:   Nordea::Siirto.api_token,
    client_id:  Nordea::Siirto.username
  }.to_query
  request
end
response() click to toggle source

@return [Nordea::Siirto::Response]

# File lib/nordea/siirto/access_token.rb, line 65
def response
  Nordea::Siirto.protocol.send!(request)
end
uri() click to toggle source

@return [URI::HTTPS]

# File lib/nordea/siirto/access_token.rb, line 40
def uri
  @uri ||= URI.parse("#{Nordea::Siirto.endpoint}/auth")
end