49 lines
1.3 KiB
TypeScript
49 lines
1.3 KiB
TypeScript
import { Request, Response, NextFunction } from 'express';
|
|
import jwt from 'jsonwebtoken';
|
|
|
|
const JWT_SECRET = process.env.JWT_SECRET || 'goura_super_secret_key_123';
|
|
|
|
export interface AuthRequest extends Request {
|
|
user?: {
|
|
id: number;
|
|
email: string;
|
|
isAdmin: boolean;
|
|
};
|
|
}
|
|
|
|
export const authenticateToken = (req: AuthRequest, res: Response, next: NextFunction) => {
|
|
const token = req.cookies.token;
|
|
|
|
if (!token) {
|
|
return res.status(401).json({ error: 'Accès refusé. Session manquante.' });
|
|
}
|
|
|
|
try {
|
|
const verified = jwt.verify(token, JWT_SECRET) as any;
|
|
req.user = verified;
|
|
next();
|
|
} catch (err) {
|
|
res.status(403).json({ error: 'Session invalide ou expirée.' });
|
|
}
|
|
};
|
|
|
|
// Middleware pour Socket.io avec extraction de cookie
|
|
export const socketAuthMiddleware = (socket: any, next: (err?: Error) => void) => {
|
|
const cookieHeader = socket.request.headers.cookie;
|
|
if (!cookieHeader) return next(new Error('Authentication error'));
|
|
|
|
const token = cookieHeader.split(';').find((c: string) => c.trim().startsWith('token='))?.split('=')[1];
|
|
|
|
if (!token) {
|
|
return next(new Error('Authentication error'));
|
|
}
|
|
|
|
try {
|
|
const verified = jwt.verify(token, JWT_SECRET);
|
|
socket.user = verified;
|
|
next();
|
|
} catch (err) {
|
|
next(new Error('Authentication error'));
|
|
}
|
|
};
|