Spaces:
Runtime error
Runtime error
File size: 1,683 Bytes
1804b24 1604e70 1804b24 | 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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | import { Request, Response, NextFunction } from "express";
import { createClient } from "@supabase/supabase-js";
import { logger } from "../lib/logger";
let supabaseInstance: any = null;
function getSupabase() {
if (supabaseInstance) return supabaseInstance;
const supabaseUrl = process.env.SUPABASE_URL || process.env.VITE_SUPABASE_URL;
const supabaseAnonKey = process.env.SUPABASE_ANON_KEY || process.env.VITE_SUPABASE_ANON_KEY;
if (!supabaseUrl || !supabaseAnonKey) {
logger.warn("Supabase credentials not found. Authentication will fail.");
}
supabaseInstance = createClient(supabaseUrl || "", supabaseAnonKey || "");
return supabaseInstance;
}
declare global {
namespace Express {
interface Request {
user?: {
id: string;
email?: string;
};
}
}
}
export const requireAuth = async (req: Request, res: Response, next: NextFunction) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return res.status(401).json({ error: "Unauthorized: Missing or invalid token" });
}
const token = authHeader.split(" ")[1];
try {
const supabase = getSupabase();
const { data: { user }, error } = await supabase.auth.getUser(token);
if (error || !user) {
logger.error({ error }, "Error verifying Supabase token");
return res.status(401).json({ error: "Unauthorized: Invalid token" });
}
req.user = {
id: user.id,
email: user.email,
};
next();
} catch (error) {
logger.error({ error }, "Unexpected error verifying token");
return res.status(500).json({ error: "Internal Server Error" });
}
};
|