| const SUPABASE_URL = process.env.SUPABASE_URL || ''; | |
| const SUPABASE_ANON_KEY = process.env.SUPABASE_ANON_KEY || ''; | |
| async function authMiddleware(req, res, next) { | |
| const authHeader = req.headers.authorization; | |
| if (!authHeader || !authHeader.startsWith('Bearer ')) { | |
| return res.status(401).json({ error: 'Authorization required' }); | |
| } | |
| const token = authHeader.slice(7); | |
| // If no Supabase URL is set yet (local dev without env vars), mock the auth | |
| if (!SUPABASE_URL) { | |
| try { | |
| const jwt = require('jsonwebtoken'); | |
| const decoded = jwt.decode(token); | |
| req.user = { id: decoded?.sub || 'local-user' }; | |
| return next(); | |
| } catch { | |
| return res.status(401).json({ error: 'Invalid mock token' }); | |
| } | |
| } | |
| try { | |
| const response = await fetch(`${SUPABASE_URL}/auth/v1/user`, { | |
| headers: { | |
| 'Authorization': `Bearer ${token}`, | |
| 'apikey': SUPABASE_ANON_KEY | |
| } | |
| }); | |
| if (!response.ok) { | |
| throw new Error('Supabase token verification failed'); | |
| } | |
| const user = await response.json(); | |
| req.user = { id: user.id, email: user.email }; | |
| next(); | |
| } catch (err) { | |
| return res.status(401).json({ error: 'Invalid or expired token' }); | |
| } | |
| } | |
| module.exports = { authMiddleware }; | |