blob: 26020640f6ac4ec8877241b99ec78d8e8dca3795 (
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
|
# frozen_string_literal: true
# The father class of all the controllers that require authentication.
class AuthenticatedController < ApplicationController
before_action :validate_jwt
private
def validate_jwt
return if valid_token
render json: { error_message: 'Token inválido' }, status: :unauthorized
end
def decoded_token
@decoded_token ||= JWT.decode(authentication_token, ENV['HMAC_SECRET_KEY'], true, { algorithm: 'HS512' })
rescue JWT::ExpiredSignature
@decoded_token = nil
end
def current_user_account
return if decoded_token.nil?
email = decoded_token[0]['data']
@current_user_account ||= UserAccount.find_by(email:)
end
def authentication_token
@authentication_token ||= request.headers[:authorization]&.sub(/^Bearer /, '')
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
|