Module: ApiGuard::JwtAuth::RefreshJwtToken

Included in:
Test::ControllerHelper
Defined in:
lib/api_guard/jwt_auth/refresh_jwt_token.rb

Overview

Common module for refresh token functionality

Instance Method Summary collapse

Instance Method Details

#destroy_all_refresh_tokens(resource) ⇒ Object



45
46
47
48
49
# File 'lib/api_guard/jwt_auth/refresh_jwt_token.rb', line 45

def destroy_all_refresh_tokens(resource)
  return unless refresh_token_enabled?(resource)

  refresh_tokens_for(resource).destroy_all
end

#find_refresh_token_of(resource, refresh_token) ⇒ Object



25
26
27
# File 'lib/api_guard/jwt_auth/refresh_jwt_token.rb', line 25

def find_refresh_token_of(resource, refresh_token)
  refresh_tokens_for(resource).where(token: refresh_token).where('expire_at IS NULL OR expire_at > ?', Time.now.utc).first
end

#new_refresh_token(resource, expired_refresh_token = false) ⇒ Object

Create a new refresh_token for the current resource This creates expired refresh_token if the argument 'expired_refresh_token' is true which can be used for testing.



39
40
41
42
43
# File 'lib/api_guard/jwt_auth/refresh_jwt_token.rb', line 39

def new_refresh_token(resource, expired_refresh_token = false)
  return unless refresh_token_enabled?(resource)

  refresh_tokens_for(resource).create(token: uniq_refresh_token(resource), expire_at: expired_refresh_token ? Time.now.utc : refresh_token_expire_at).token
end

#refresh_token_association(resource) ⇒ Object



12
13
14
# File 'lib/api_guard/jwt_auth/refresh_jwt_token.rb', line 12

def refresh_token_association(resource)
  resource.class.refresh_token_association
end

#refresh_token_enabled?(resource) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/api_guard/jwt_auth/refresh_jwt_token.rb', line 16

def refresh_token_enabled?(resource)
  refresh_token_association(resource).present?
end

#refresh_token_expire_atObject



8
9
10
# File 'lib/api_guard/jwt_auth/refresh_jwt_token.rb', line 8

def refresh_token_expire_at
  @refresh_token_expire_at ||= (Time.now.utc + ApiGuard.refresh_token_validity)
end

#refresh_tokens_for(resource) ⇒ Object



20
21
22
23
# File 'lib/api_guard/jwt_auth/refresh_jwt_token.rb', line 20

def refresh_tokens_for(resource)
  refresh_token_association = refresh_token_association(resource)
  resource.send(refresh_token_association)
end

#uniq_refresh_token(resource) ⇒ Object

Generate and return unique refresh token for the resource



30
31
32
33
34
35
# File 'lib/api_guard/jwt_auth/refresh_jwt_token.rb', line 30

def uniq_refresh_token(resource)
  loop do
    random_token = SecureRandom.urlsafe_base64
    return random_token unless refresh_tokens_for(resource).exists?(token: random_token)
  end
end