class PrintosServiceToken

Constants

MUTEX

Attributes

auth_token[R]

Public Class Methods

get_token() click to toggle source

Get an authentication token which can be used to login to PrintOS as a Sulu service account.

# File lib/printos/printos_service_token.rb, line 9
def self.get_token

  # Quick check for existing cached token
  result = @token
  return result if result.present?

  # Synchronized check for cached token
  MUTEX.synchronize do
    return @token if @token.present?

    # Acquire new token
    @token = acquire_service_token
  end
end
new(token) click to toggle source
# File lib/printos/printos_service_token.rb, line 72
def initialize(token)
  # For now just keep track of the printos auth_token. In future we can expand
  # to capture the token expiration time and optimize to fetch a new token
  # before token expires.
  @auth_token = token
end
reset_token(service_token) click to toggle source

Reset the specified service token. Call this method if a previously acquired token is bad (e.g., expired, etc.)

# File lib/printos/printos_service_token.rb, line 26
def self.reset_token(service_token)
  raise 'Invalid token' unless service_token.instance_of? PrintosServiceToken

  MUTEX.synchronize do
    #Only reset if the tokens match. It is possible that another thread
    #has already reset the token and do not want to reset when unnecessary.
    if @token != nil && @token.equal?(service_token)
      Printos.config.logger.debug 'Resetting printos service authentication token.'

      # Set token to nil so that other threads stop using the old token while we
      # acquire a new one
      @token = nil
    else
      Printos.config.logger.debug 'Not going to reset printos service token, looks like it has already been reset.'
    end
  end
end

Private Class Methods

acquire_service_token() click to toggle source
# File lib/printos/printos_service_token.rb, line 46
def self.acquire_service_token
  body = {
    login: Printos.config.service_user,
    password: Printos.config.service_password
  }

  url = "#{Printos.config.api_host}/#{PrintosClient::API_BASE}/services/login"
  response = RestClient.post(url, body.to_json, :content_type => 'application/json')

  if response.code == 401
    Printos.config.logger.error 'Printos service login failed with 401.'
    raise "Unauthorized: #{response.body}"
  end

  result = {}
  result = JSON.parse(response.body, symbolize_names: :true) if response.body.present?
  auth_token = result[:authToken]

  unless auth_token.present?
    Printos.config.logger.error 'Printos service login failed. Authentication token not found in response.'
    raise "Unauthorized: #{response.body}"
  end

  PrintosServiceToken.new(auth_token)
end