Files
api/app/controllers/concerns/authorize_request.rb
T
Jason Jordan 9853d58469
CI / scan_ruby (push) Failing after 2m13s
CI / lint (push) Failing after 20s
Its been a while
2026-07-23 10:41:46 -04:00

34 lines
972 B
Ruby

# this concern checks the token and finds the user
# if token is invalid or missing, we block the request
# usage: just add `before_action :authorize_request` in any controller you wanna protect
# I keep things simple, if you want to make it better it's you choice
module AuthorizeRequest
extend ActiveSupport::Concern
included do
before_action :authorize_request
end
private
def authorize_request
header = request.headers["Authorization"]
token = header.split(" ").last if header
begin
decoded = JsonWebToken.decode(token)
# check if token is retired (logged out)
if RetiredToken.retired?(decoded[:jti])
render json: { error: "Token has been revoked" }, status: :unauthorized
return
end
@current_user = User.find(decoded[:user_id])
rescue ActiveRecord::RecordNotFound, StandardError => e
render json: { error: "unauthorized: #{e.message}" }, status: :unauthorized
end
end
end