diff --git a/nest-backend/src/middleware/auth.ts b/nest-backend/src/middleware/auth.ts index c1957cc..1c3f27a 100644 --- a/nest-backend/src/middleware/auth.ts +++ b/nest-backend/src/middleware/auth.ts @@ -1,5 +1,6 @@ import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; +import prisma from '../lib/prisma.js'; export interface JwtPayload { userId: string; @@ -15,7 +16,7 @@ declare global { } } -export function authenticate(req: Request, res: Response, next: NextFunction): void { +export async function authenticate(req: Request, res: Response, next: NextFunction): Promise { const header = req.headers.authorization; if (!header?.startsWith('Bearer ')) { res.status(401).json({ error: 'Missing or invalid Authorization header' }); @@ -25,7 +26,21 @@ export function authenticate(req: Request, res: Response, next: NextFunction): v const token = header.slice(7); try { const payload = jwt.verify(token, process.env.JWT_SECRET!) as JwtPayload; - req.user = payload; + const user = await prisma.user.findUnique({ + where: { id: payload.userId }, + select: { id: true, role: true, isAdmin: true, isBanned: true }, + }); + + if (!user || user.isBanned) { + res.status(401).json({ error: 'Token user no longer exists or is banned. Please login again.' }); + return; + } + + req.user = { + userId: user.id, + role: user.role, + isAdmin: user.isAdmin, + }; next(); } catch { res.status(401).json({ error: 'Token expired or invalid' });