Class: Dscf::Core::TokenService

Inherits:
Object
  • Object
show all
Defined in:
app/services/dscf/core/token_service.rb

Class Method Summary collapse

Class Method Details

.access_token_payload(user) ⇒ Object



35
36
37
38
39
40
41
# File 'app/services/dscf/core/token_service.rb', line 35

def access_token_payload(user)
  {
    user_id: user.id,
    identifier: user.email || user.phone,
    type: "access"
  }
end

.decode(token) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
# File 'app/services/dscf/core/token_service.rb', line 12

def decode(token)
  return nil if token.blank?

  begin
    decoded = ::JWT.decode(token, key, true, algorithm: "HS256")
    decoded.first
  rescue ::JWT::ExpiredSignature
    raise AuthenticationError, "Token has expired"
  rescue ::JWT::DecodeError
    raise AuthenticationError, "Invalid token"
  end
end

.issue(payload, expires_in: 15.minutes) ⇒ Object



7
8
9
10
# File 'app/services/dscf/core/token_service.rb', line 7

def issue(payload, expires_in: 15.minutes)
  payload = payload.merge(exp: Time.current.to_i + expires_in.to_i)
  ::JWT.encode(payload, key, "HS256")
end

.keyObject



43
44
45
46
47
48
49
50
51
# File 'app/services/dscf/core/token_service.rb', line 43

def key
  @key ||= ENV.fetch("JWT_SECRET_KEY", nil) ||
           if Rails.env.test?
             "test_jwt_secret_key_for_testing_purposes_only_12345678901234567890"
           else
             Rails.application.credentials.secret_key_base
           end ||
           "fallback_secret_key_for_development_only_12345678901234567890"
end

.refresh_token_payload(user, device: nil, ip_address: nil) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'app/services/dscf/core/token_service.rb', line 25

def refresh_token_payload(user, device: nil, ip_address: nil)
  {
    user_id: user.id,
    identifier: user.email || user.phone,
    device: device,
    ip_address: ip_address,
    type: "refresh"
  }
end