/
aaronair
/
Test_task_rt_solution
Обзор
Документация
Войти
/
aaronair
/
Test_task_rt_solution
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
backend/src/middleware/auth.ts
31 строка
1 KB
aaronair
Решение
03 июн 2026, 15:04
03 июн 2026, 15:04
72ced40
Код
Авторство
О чём код?
import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; const JWT_SECRET = process.env.JWT_SECRET || 'your_jwt_secret_key'; export interface AuthenticatedRequest extends Request { user?: { id: string; email: string; role: 'user' | 'admin' }; } // Проверка: залогинен ли пользователь вообще export const verifyToken = (req: AuthenticatedRequest, res: Response, next: NextFunction): any => { const token = req.headers['authorization']?.split(' ')[1]; if (!token) return res.status(401).json({ error: 'Доступ запрещен. Токен отсутствует.' }); try { const decoded = jwt.verify(token, JWT_SECRET) as any; req.user = decoded; next(); } catch (err) { return res.status(403).json({ error: 'Невалидный или просроченный токен' }); } }; // Проверка: является ли пользователь Администратором export const requireAdmin = (req: AuthenticatedRequest, res: Response, next: NextFunction): any => { if (!req.user || req.user.role !== 'admin') { return res.status(403).json({ error: 'Недостаточно прав. Требуется роль admin.' }); } next(); };