| 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" }); | |
| } | |
| } |