Class: StandardId::JwtService

Inherits:
Object
  • Object
show all
Defined in:
lib/standard_id/jwt_service.rb

Constant Summary collapse

ALGORITHM =
"HS256"
RESERVED_JWT_KEYS =
%i[sub client_id scope grant_type exp iat aud iss nbf jti]
BASE_SESSION_FIELDS =
%i[account_id client_id scopes grant_type]

Class Method Summary collapse

Class Method Details

.decode(token) ⇒ Object



24
25
26
27
28
29
# File 'lib/standard_id/jwt_service.rb', line 24

def self.decode(token)
  decoded = JWT.decode(token, secret_key, true, { algorithm: ALGORITHM })
  decoded.first.with_indifferent_access
rescue JWT::DecodeError, JWT::ExpiredSignature, JWT::InvalidIatError
  nil
end

.decode_session(token) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/standard_id/jwt_service.rb', line 31

def self.decode_session(token)
  payload = decode(token)
  return unless payload

  scopes = if payload[:scope].is_a?(String)
    payload[:scope].split(" ")
  else
    Array(payload[:scope]).compact
  end

  session_class.new(
    **payload.slice(*claim_resolver_keys),
    account_id: payload[:sub],
    client_id: payload[:client_id],
    scopes: scopes,
    grant_type: payload[:grant_type],
  )
end

.encode(payload, expires_in: 1.hour) ⇒ Object



17
18
19
20
21
22
# File 'lib/standard_id/jwt_service.rb', line 17

def self.encode(payload, expires_in: 1.hour)
  payload[:exp] = expires_in.from_now.to_i
  payload[:iat] = Time.current.to_i

  JWT.encode(payload, secret_key, ALGORITHM)
end

.session_classObject



9
10
11
12
13
14
15
# File 'lib/standard_id/jwt_service.rb', line 9

def self.session_class
  Struct.new(*(BASE_SESSION_FIELDS + claim_resolver_keys), keyword_init: true) do
    def active?
      true
    end
  end
end