40 lines
1.0 KiB
TypeScript
40 lines
1.0 KiB
TypeScript
import React from 'react';
|
|
import { Navigate, useLocation } from 'react-router-dom';
|
|
import { useSelector } from 'react-redux';
|
|
import type { RootState } from '@/store';
|
|
|
|
interface ProtectedRouteProps {
|
|
children: React.ReactNode;
|
|
requiresAuth?: boolean;
|
|
}
|
|
|
|
/**
|
|
* 路由权限守卫组件
|
|
*
|
|
* 功能:
|
|
* 1. 检查用户登录状态
|
|
* 2. 未登录跳转到登录页
|
|
*
|
|
* 注意:
|
|
* - 路由已经是根据用户菜单动态生成的,所以不需要再次检查权限
|
|
* - 只需要检查登录状态即可
|
|
*/
|
|
const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
|
|
children,
|
|
requiresAuth = true
|
|
}) => {
|
|
const location = useLocation();
|
|
const token = useSelector((state: RootState) => state.user.token);
|
|
|
|
// 检查是否需要认证
|
|
if (requiresAuth && !token) {
|
|
// 未登录,跳转到登录页,并记录原始路径用于登录后跳转
|
|
return <Navigate to="/login" state={{ from: location.pathname }} replace />;
|
|
}
|
|
|
|
// 已登录或不需要认证,允许访问
|
|
return <>{children}</>;
|
|
};
|
|
|
|
export default ProtectedRoute;
|