summaryrefslogtreecommitdiff
path: root/app/controllers/services/token_generation_service.rb
blob: 8edce9c12922e06356fe3af5e9353007723df013 (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
26
27
# frozen_string_literal: true

module Services
  # 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
end