27 lines
755 B
TypeScript
27 lines
755 B
TypeScript
import { Request, Response, NextFunction } from 'express';
|
|
import jwt from 'jsonwebtoken';
|
|
import { config } from '../config';
|
|
|
|
export interface AuthRequest extends Request {
|
|
userId?: string;
|
|
}
|
|
|
|
export function authenticateToken(req: AuthRequest, res: Response, next: NextFunction) {
|
|
const authHeader = req.headers['authorization'];
|
|
const token = authHeader && authHeader.split(' ')[1];
|
|
|
|
if (!token) {
|
|
res.status(401).json({ error: 'Требуется авторизация' });
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const decoded = jwt.verify(token, config.jwtSecret) as { userId: string };
|
|
req.userId = decoded.userId;
|
|
next();
|
|
} catch {
|
|
res.status(403).json({ error: 'Недействительный токен' });
|
|
return;
|
|
}
|
|
}
|