import type { ReactNode } from 'react';
|
import { Navigate, useLocation } from 'react-router-dom';
|
import { useAuthStore } from '@/store/auth';
|
|
interface RouteGuardProps {
|
/** 不传则只校验登录状态 */
|
permission?: string;
|
children: ReactNode;
|
}
|
|
/**
|
* 路由守卫:
|
* 1. 未登录跳转登录页,并记录来源地址;
|
* 2. 已登录但缺少权限码时跳转 403。
|
*/
|
export default function RouteGuard({ permission, children }: RouteGuardProps) {
|
const token = useAuthStore((state) => state.token);
|
const hasPermission = useAuthStore((state) => state.hasPermission);
|
const location = useLocation();
|
|
if (!token) {
|
return (
|
<Navigate
|
to="/login"
|
replace
|
state={{ from: `${location.pathname}${location.search}` }}
|
/>
|
);
|
}
|
|
if (permission && !hasPermission(permission)) {
|
return <Navigate to="/403" replace />;
|
}
|
|
return <>{children}</>;
|
}
|