Class: Seekmodo::Sdk::BrowserToken
- Inherits:
-
Object
- Object
- Seekmodo::Sdk::BrowserToken
- Defined in:
- lib/seekmodo/sdk/browser_token.rb
Constant Summary collapse
- CACHE_KEY =
"numinix.seekmodo.browser_token"- SAFETY_MARGIN_SECONDS =
60
Instance Method Summary collapse
- #forget(audience = nil) ⇒ Object
-
#initialize(client, cache, clock: nil) ⇒ BrowserToken
constructor
A new instance of BrowserToken.
- #token(audience = nil, force: false) ⇒ Object
Constructor Details
#initialize(client, cache, clock: nil) ⇒ BrowserToken
Returns a new instance of BrowserToken.
13 14 15 16 17 |
# File 'lib/seekmodo/sdk/browser_token.rb', line 13 def initialize(client, cache, clock: nil) @client = client @cache = cache @clock = clock || -> { Time.now.to_i } end |
Instance Method Details
#forget(audience = nil) ⇒ Object
57 58 59 |
# File 'lib/seekmodo/sdk/browser_token.rb', line 57 def forget(audience = nil) @cache.delete("#{CACHE_KEY}:#{audience || 'default'}") end |
#token(audience = nil, force: false) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/seekmodo/sdk/browser_token.rb', line 19 def token(audience = nil, force: false) cache_key = "#{CACHE_KEY}:#{audience || 'default'}" unless force cached = @cache.get(cache_key) if cached.is_a?(Hash) expires_at = cached.fetch("expires_at", 0).to_i if expires_at > @clock.call + SAFETY_MARGIN_SECONDS return { "token" => cached["token"].to_s, "expires_at" => expires_at, "issued_at" => cached.fetch("issued_at", @clock.call).to_i } end end end response = @client.browser_token(audience) token = response["token"].to_s expires_at = response.fetch("expires_at", 0).to_i issued_at = response.fetch("issued_at", @clock.call).to_i if token.empty? || expires_at.zero? raise ClientError.new( "Gateway tenants.token response missing token/expires_at fields.", ClientError::KIND_BAD_RESPONSE ) end value = { "token" => token, "expires_at" => expires_at, "issued_at" => issued_at } ttl = [expires_at - @clock.call - SAFETY_MARGIN_SECONDS, 1].max @cache.set(cache_key, value, ttl) value end |