Class: ZaiPayment::Auth::TokenProvider

Inherits:
Object
  • Object
show all
Defined in:
lib/zai_payment/auth/token_provider.rb

Instance Method Summary collapse

Constructor Details

#initialize(config:, store: nil) ⇒ TokenProvider

Returns a new instance of TokenProvider.



8
9
10
11
12
# File 'lib/zai_payment/auth/token_provider.rb', line 8

def initialize(config:, store: nil)
  @config = config
  @store  = store || TokenStores::MemoryStore.new
  @mutex  = Mutex.new
end

Instance Method Details

#bearer_tokenObject

Returns "Bearer "



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/zai_payment/auth/token_provider.rb', line 15

def bearer_token
  token = @store.fetch
  return "Bearer #{token.value}" if token && Time.now < token.expires_at

  @mutex.synchronize do
    token = @store.fetch
    return "Bearer #{token.value}" if token && Time.now < token.expires_at

    new_token = request_token!
    @store.write(new_token)
    "Bearer #{new_token.value}"
  end
end

#clear_tokenObject

Clear cached token (next call will re-auth)



36
37
38
# File 'lib/zai_payment/auth/token_provider.rb', line 36

def clear_token
  @store.clear
end

#refresh_tokenObject

Force refresh: clears current token then fetches a new one



30
31
32
33
# File 'lib/zai_payment/auth/token_provider.rb', line 30

def refresh_token
  clear_token
  bearer_token
end

#token_expiryObject

Returns a Time (or nil if no token cached)



41
42
43
44
# File 'lib/zai_payment/auth/token_provider.rb', line 41

def token_expiry
  token = @store.fetch
  token&.expires_at
end

#token_typeObject

Returns the token type string (e.g., "Bearer") or nil if none cached



47
48
49
50
# File 'lib/zai_payment/auth/token_provider.rb', line 47

def token_type
  token = @store.fetch
  token&.type
end