summaryrefslogtreecommitdiff
path: root/app/controllers/authenticated_controller.rb
blob: cb4f34d12a81c8b17d1d2d829eb7241f428b6684 (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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# frozen_string_literal: true

# The father class of all the controllers that require authentication.
class AuthenticatedController < ApplicationController
  before_action :validate_jwt

  private

  def current_user_account
    return if decoded_token.nil?

    email = decoded_token[0]['data']
    @current_user_account ||= UserAccount.find_by(email:)
  end

  def current_user_role
    return if decoded_token.nil?

    decoded_token[0]['aud']
  end

  def authentication_token
    @authentication_token ||= request.headers[:authorization]&.sub(/^Bearer /, '')
  end

  def decoded_token
    @decoded_token ||= JWT.decode(authentication_token, ENV['HMAC_SECRET_KEY'], true, { algorithm: 'HS512' })
  rescue JWT::ExpiredSignature, JWT::DecodeError
    @decoded_token = nil
  end

  def validate_jwt
    return if valid_token

    render json: { error_message: 'Token inválido' }, status: :unauthorized
  end

  def valid_token
    !(decoded_token.nil? || current_user_account&.session_key.nil? || invalid_jti)
  end

  def invalid_jti
    return false if current_user_account.nil? || decoded_token.nil?

    current_user_account.session_key != decoded_token[0]['jti']
  end
end