File size: 1,454 Bytes
d53e5b4 | 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 | 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();
};
|