import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; export interface AuthPayload { userId: string; email: string; roles: string[]; products: string[]; settings: Record; } declare global { namespace Express { interface Request { auth?: AuthPayload; } } } export function requireAuth( req: Request, res: Response, next: NextFunction ): void { const token = req.cookies?.accessToken ?? extractBearer( req ); if ( !token ) { res.status( 401 ).json( { error: 'Not authenticated' } ); return; } try { req.auth = jwt.verify( token, process.env.JWT_SECRET ?? '' ) as AuthPayload; next(); } catch { res.status( 401 ).json( { error: 'Invalid token' } ); } } function extractBearer( req: Request ): string | undefined { const auth = req.headers.authorization; if ( auth?.startsWith( 'Bearer ' ) ) return auth.slice( 7 ); return undefined; }