summaryrefslogtreecommitdiff
path: root/app/services/token_generation_service.rb
blob: 3af1e3face37f6da6b7ab4b8dbe996f878200dd0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# frozen_string_literal: true

# The service responsible for JWT generation.
class TokenGenerationService
  def initialize(params)
    @email = params[:email]
    @role = params[:role]
    @user_account = UserAccount.find_by(email: @email)
  end

  def call(refresh_token_expiration)
    @user_account.update_attribute(:session_key, SecureRandom.hex(16))
    { token: generate_token(DateTime.current + 30.minutes), refresh: generate_token(refresh_token_expiration.to_i) }
  end

  private

  def generate_token(expiration)
    JWT.encode(payload.merge({ exp: expiration.to_i }), ENV['HMAC_SECRET_KEY'], 'HS512')
  end

  def payload
    { data: @email, aud: @role, jti: @user_account.session_key }
  end
end