Class: EndPointBlank::AccessTokens

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/end_point_blank/access_tokens.rb

Overview

Thread-safe singleton cache for storing access tokens per hostname

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeAccessTokens

Returns a new instance of AccessTokens.



11
12
13
14
# File 'lib/end_point_blank/access_tokens.rb', line 11

def initialize()
  @tokens = {}
  @mutexes = {}
end

Class Method Details

.token(arg) ⇒ Object



16
17
18
# File 'lib/end_point_blank/access_tokens.rb', line 16

def self.token(arg)
  instance.token(arg)
end

Instance Method Details

#clear(arg) ⇒ Hash

Clear all tokens from the cache

Returns:

  • (Hash)

    Empty hash



46
47
48
49
50
51
52
# File 'lib/end_point_blank/access_tokens.rb', line 46

def clear(arg)
  @mutexes.keys.each do |hostname|
    @mutexes[hostname].synchronize do
      @tokens.delete(hostname)
    end
  end
end

#exists?(arg) ⇒ Boolean

Check if a valid token exists for a given hostname

Parameters:

  • hostname (String)

    The hostname to check

Returns:

  • (Boolean)

    True if a valid token exists, false otherwise



67
68
69
70
# File 'lib/end_point_blank/access_tokens.rb', line 67

def exists?(arg)
  hostname = arg.downcase
  @tokens.key?(hostname) && @tokens[hostname][:expired_at] > Time.now + 30
end

#remove(arg) ⇒ Object?

Remove token for a specific hostname

Parameters:

  • hostname (String)

    The hostname for which to remove the token

Returns:

  • (Object, nil)

    The removed token data or nil if not found



57
58
59
60
61
62
# File 'lib/end_point_blank/access_tokens.rb', line 57

def remove(arg)
  hostname = arg.downcase
  @mutexes[hostname].synchronize do
    @tokens.delete(hostname)
  end
end

#token(arg) ⇒ String?

Retrieve or generate an access token for the given hostname

Parameters:

  • hostname (String)

    The hostname for which to retrieve the token

Returns:

  • (String, nil)

    The access token or nil if generation fails



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/end_point_blank/access_tokens.rb', line 23

def token(arg)
  hostname = arg.downcase
  @mutexes[hostname] ||= Mutex.new
  @mutexes[hostname].synchronize do
    # Return cached token if it exists and is not expired
    return @tokens[hostname][:token] if @tokens.key?(hostname) && @tokens[hostname][:expired_at] > Time.now + 120

    # Fetch new token
    payload = Commands::GenerateAccessToken.token(hostname)

    if payload && payload[:token]
      payload[:expired_at] = Time.parse(payload[:expired_at])
      @tokens[hostname] = payload
      payload[:token]
    else
      EndPointBlank.logger.error "Failed to generate access token for #{hostname}: #{payload&.fetch('error')}"
      nil
    end
  end
end