Spaces:
Running
Running
| import type { Request, Response, NextFunction } from 'express'; | |
| import jwt from 'jsonwebtoken'; | |
| import { config } from '../config/env.js'; | |
| export interface AuthRequest extends Request { | |
| userId?: string; | |
| } | |
| export function requireAuth(req: AuthRequest, res: Response, next: NextFunction) { | |
| const token = req.cookies?.token || req.headers.authorization?.replace('Bearer ', ''); | |
| if (!token) { | |
| res.status(401).json({ error: true, message: 'Authentification requise' }); | |
| return; | |
| } | |
| try { | |
| const payload = jwt.verify(token, config.JWT_SECRET) as { userId: string }; | |
| req.userId = payload.userId; | |
| next(); | |
| } catch { | |
| res.status(401).json({ error: true, message: 'Token invalide ou expiré' }); | |
| } | |
| } | |