2025-12-25 10:48:35 +08:00
|
|
|
import React from 'react';
|
|
|
|
|
import { Navigate, useLocation } from 'react-router-dom';
|
|
|
|
|
import { Spin } from 'antd';
|
|
|
|
|
import { useAuth } from '../context/AuthContext';
|
|
|
|
|
|
|
|
|
|
const ProtectedRoute = ({ children, requiredPermission }) => {
|
|
|
|
|
const { user, token, loading, initialized } = useAuth();
|
|
|
|
|
const location = useLocation();
|
|
|
|
|
|
|
|
|
|
if (!initialized) {
|
|
|
|
|
return (
|
|
|
|
|
<div style={{
|
|
|
|
|
display: 'flex',
|
2026-01-20 11:28:53 +08:00
|
|
|
flexDirection: 'column',
|
2025-12-25 10:48:35 +08:00
|
|
|
justifyContent: 'center',
|
|
|
|
|
alignItems: 'center',
|
2026-01-20 11:28:53 +08:00
|
|
|
height: '100vh',
|
|
|
|
|
gap: '16px'
|
2025-12-25 10:48:35 +08:00
|
|
|
}}>
|
2026-01-20 11:28:53 +08:00
|
|
|
<Spin size="large" />
|
|
|
|
|
<span style={{ color: '#8c8c8c', fontSize: '14px' }}>加载中...</span>
|
2025-12-25 10:48:35 +08:00
|
|
|
</div>
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!token) {
|
|
|
|
|
return <Navigate to="/login" state={{ from: location }} replace />;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (requiredPermission && !user) {
|
|
|
|
|
return <Navigate to="/" replace />;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return children;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default ProtectedRoute;
|