Files
api/app/controllers/concerns/authorize_request.rb
T

34 lines
972 B
Ruby
Raw Normal View History

2026-05-18 13:17:28 -04:00
# 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)
2026-07-23 10:41:46 -04:00
# check if token is retired (logged out)
if RetiredToken.retired?(decoded[:jti])
2026-05-18 13:17:28 -04:00
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