Class: StandardId::JwtService

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

Defined Under Namespace

Classes: Session

Constant Summary collapse

ALGORITHM =
"HS256"

Class Method Summary collapse

Class Method Details

.decode(token) ⇒ Object



19
20
21
22
23
24
# File 'lib/standard_id/jwt_service.rb', line 19

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



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/standard_id/jwt_service.rb', line 26

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.new(
    account_id: payload[:sub],
    client_id: payload[:client_id],
    scopes: scopes,
    grant_type: payload[:grant_type]
  )
end

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



12
13
14
15
16
17
# File 'lib/standard_id/jwt_service.rb', line 12

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