Files

26 lines
726 B
Ruby

class ApplicationController < ActionController::API
include ActionController::HttpAuthentication::Token::ControllerMethods
before_action :authenticate_request!
attr_reader :current_user
private
def authenticate_request!
token = extract_token
return render json: { error: "Unauthorized" }, status: :unauthorized unless token
decoded = JwtService.decode(token)
@current_user = User.find_by(id: decoded[:user_id]) if decoded
render json: { error: "Unauthorized" }, status: :unauthorized unless @current_user
end
def extract_token
auth_header = request.headers["Authorization"]
return auth_header.split(" ").last if auth_header&.start_with?("Bearer ")
params[:token]
end
end