Original
This commit is contained in:
26
apps/server/src/middleware/auth.ts
Normal file
26
apps/server/src/middleware/auth.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user