import { Injectable, NestMiddleware, UnauthorizedException, } from '@nestjs/common'; import type { Request, Response, NextFunction } from 'express'; export interface AuthenticatedUser { id: string; role: string; permissions: string[]; } export interface AuthenticatedRequest extends Request { user?: AuthenticatedUser; } @Injectable() export class AuthMiddleware implements NestMiddleware { use(req: AuthenticatedRequest, _res: Response, next: NextFunction): void { const userId = req.headers['x-user-id'] as string | undefined; const role = req.headers['x-user-role'] as string | undefined; const permissionsHeader = req.headers['x-user-permissions'] as | string | undefined; if (!userId || !role) { throw new UnauthorizedException( 'Missing authentication headers (x-user-id, x-user-role)', ); } req.user = { id: userId, role, permissions: permissionsHeader ? permissionsHeader.split(',') : [], }; next(); } }