/
ingvion
/
PlanerService
Обзор
Документация
Войти
/
ingvion
/
PlanerService
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Frontend/src/components/ProtectedRoute.jsx
51 строка
2 KB
lenadekart
Перенос блока рекомендаций AI в главное пространство страницы Dashboard, прочие улучшения
23 ноя 2025, 01:15
23 ноя 2025, 01:15
b033f6f
Код
Авторство
О чём код?
import { Navigate } from 'react-router-dom'; import AdminService from '../services/AdminService'; import StudentService from '../services/StudentService'; /** * Компонент для защиты маршрутов на основе ролей пользователя */ const ProtectedRoute = ({ children, allowedRoles }) => { let token = null; let redirectPath = '/login'; // Determine which token to check based on allowed roles if (allowedRoles.includes('student')) { token = StudentService.getToken(); redirectPath = '/login'; } else if (allowedRoles.includes('super_admin') || allowedRoles.includes('curator')) { token = AdminService.getToken(); redirectPath = '/admin/login'; } if (!token) { return <Navigate to={redirectPath} replace />; } try { const payload = JSON.parse(atob(token.split('.')[1])); const userRole = payload.role; if (!allowedRoles.includes(userRole)) { // Redirect based on role if (userRole === 'student') { return <Navigate to="/dashboard" replace />; } else if (userRole === 'super_admin' || userRole === 'curator') { return <Navigate to="/admin" replace />; } return <Navigate to={redirectPath} replace />; } return children; } catch (error) { // Clear the specific token that failed if (allowedRoles.includes('student')) { StudentService.logout(); } else { AdminService.logout(); } return <Navigate to={redirectPath} replace />; } }; export default ProtectedRoute;