| // src/router/Guards.jsx |
| import React from 'react' |
| import { Navigate, Outlet, useLocation } from 'react-router-dom' |
| import { getAuthToken, getUserInfo } from '../utils/auth' |
| |
| /** 登录检查:有 token 才放行,否则跳到 /login */ |
| export function RequireAuth({ children }) { |
| const token = getAuthToken() |
| const loc = useLocation() |
| if (!token) { |
| return <Navigate to="/login" state={{ from: loc }} replace /> |
| } |
| return children ?? <Outlet /> |
| } |
| |
| /** 角色检查:只有 allowedRoles 内的角色才能访问 */ |
| export function RequireRole({ allowedRoles, children }) { |
| const user = getUserInfo() |
| // user 里应该有 .role |
| if (!user || !allowedRoles.includes(user.role)) { |
| return <Navigate to="/login" replace /> |
| } |
| return children ?? <Outlet /> |
| } |