diff options
author | HombreLaser <sebastian-440@live.com> | 2023-02-24 23:25:26 -0600 |
---|---|---|
committer | HombreLaser <sebastian-440@live.com> | 2023-02-24 23:25:26 -0600 |
commit | e1a240c563b0e10e0ceae7c167fdcde752f3d865 (patch) | |
tree | 05408f95e5896f243bcd010dd01153ad78f35d7d /app/controllers/authenticated_controller.rb | |
parent | 0307ed7be55784cc54a2055c22bc5465405832ea (diff) |
Añade autenticación
Diffstat (limited to 'app/controllers/authenticated_controller.rb')
-rw-r--r-- | app/controllers/authenticated_controller.rb | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/app/controllers/authenticated_controller.rb b/app/controllers/authenticated_controller.rb new file mode 100644 index 0000000..2602064 --- /dev/null +++ b/app/controllers/authenticated_controller.rb @@ -0,0 +1,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 |