Class: Virgil::Jwt::CachingJwtProvider

Inherits:
AccessTokenProvider show all
Defined in:
lib/virgil/jwt/caching_jwt_provider.rb

Overview

Provides an opportunity to get cached access token or renew it using callback mechanism.

Constant Summary collapse

@@mutex =
Mutex.new

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obtain_token_proc) ⇒ CachingJwtProvider

Returns a new instance of CachingJwtProvider.



49
50
51
52
# File 'lib/virgil/jwt/caching_jwt_provider.rb', line 49

def initialize(obtain_token_proc)
  Validation.check_type_argument!(Proc, obtain_token_proc)
  @renew_access_token_proc = obtain_token_proc
end

Instance Attribute Details

#renew_access_token_procProc (readonly)

Callback, that takes an instance of [TokenContext] and returns string representation of generated instance of [AccessToken]

Returns:

  • (Proc)


46
47
48
# File 'lib/virgil/jwt/caching_jwt_provider.rb', line 46

def renew_access_token_proc
  @renew_access_token_proc
end

Instance Method Details

#get_token(token_context) ⇒ Object

Gets cached or renewed access token.

Parameters:

  • token_context

    an instance of [TokenContext]

Returns:

  • The instance of [AccessToken]



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/virgil/jwt/caching_jwt_provider.rb', line 57

def get_token(token_context)
  Validation.check_type_argument!(TokenContext, token_context)

  if !@jwt || (@jwt.body_content.expires_at <= Time.at(Time.now.utc.to_i + 5).utc)
    @@mutex.synchronize {
      jwt_str = @renew_access_token_proc.call(token_context)
      @jwt = Jwt.from(jwt_str)
    }
  end
  @jwt
end