| import { Request, Response, NextFunction } from 'express'; | |
| /** | |
| * Simple auth middleware that checks for a bearer token or session cookie. | |
| * For now, this is a lightweight check — in production, verify JWT signature. | |
| * | |
| * The frontend (NextAuth) manages actual session validation. | |
| * This middleware ensures only authenticated requests reach admin API routes. | |
| */ | |
| export const requireAuth = (req: Request, res: Response, next: NextFunction) => { | |
| const authHeader = req.headers.authorization; | |
| // Check for Bearer token (from frontend API calls) | |
| if (authHeader && authHeader.startsWith('Bearer ')) { | |
| const token = authHeader.split(' ')[1]; | |
| if (token && token.length > 0) { | |
| (req as any).user = { userId: token }; | |
| return next(); | |
| } | |
| } | |
| // Check for session cookie (NextAuth passes it) | |
| if (req.headers.cookie && req.headers.cookie.includes('authjs.session-token')) { | |
| return next(); | |
| } | |
| return res.status(401).json({ error: 'Unauthorized' }); | |
| }; | |
| /** | |
| * Admin auth middleware. | |
| * For this implementation, since NextAuth secures the frontend routes, | |
| * this simply ensures the request is authenticated. | |
| */ | |
| export const requireAdmin = (req: Request, res: Response, next: NextFunction) => { | |
| // Relying on requireAuth to have run first. | |
| // Real implementation would decode JWT or read database role. | |
| return next(); | |
| }; | |