File size: 1,023 Bytes
ccc21f3 01abfc5 ccc21f3 01abfc5 ccc21f3 01abfc5 ccc21f3 01abfc5 ccc21f3 01abfc5 | 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 | import type { Request, Response, NextFunction } from "express";
import { createClient } from "@supabase/supabase-js";
export interface AuthedRequest extends Request {
userId: string;
userEmail: string | null;
}
const supabase = createClient(
process.env.SUPABASE_URL || "",
process.env.SUPABASE_SERVICE_ROLE_KEY || ""
);
export async function requireAuth(
req: Request,
res: Response,
next: NextFunction,
): Promise<void> {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith("Bearer ")) {
res.status(401).json({ error: "Unauthorized" });
return;
}
const token = authHeader.split(" ")[1];
try {
const { data: { user }, error } = await supabase.auth.getUser(token);
if (error || !user) {
res.status(401).json({ error: "Unauthorized" });
return;
}
(req as AuthedRequest).userId = user.id;
(req as AuthedRequest).userEmail = user.email ?? null;
next();
} catch (err) {
res.status(401).json({ error: "Unauthorized" });
}
} |