Spaces:
Runtime error
Runtime error
| 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" }); | |
| } | |
| }; | |