Class: PrintosServiceToken

Inherits:
Object
  • Object
show all
Defined in:
lib/printos/printos_service_token.rb

Constant Summary collapse

MUTEX =
Mutex.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#auth_tokenObject (readonly)

Returns the value of attribute auth_token.



5
6
7
# File 'lib/printos/printos_service_token.rb', line 5

def auth_token
  @auth_token
end

Class Method Details

.acquire_service_tokenObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# 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

.get_tokenObject

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



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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

.reset_token(service_token) ⇒ Object

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



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 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