monorepo-microservice-rbac/apps/aorta/src/router/AuthGuard.tsx
2023-09-07 16:42:34 +08:00

30 lines
817 B
TypeScript

import { AuthFailedReplacePath } from "@/constant";
import { useLocation, useNavigate } from "react-router-dom";
import { pathToRegexp } from "path-to-regexp";
import { useDomain } from "@/hook/useDomain";
interface RouteGuardProps {
children?: React.ReactNode;
ignorePaths: string[];
}
export const RouteGuard = (props: RouteGuardProps) => {
const { children, ignorePaths } = props;
const { userDomainService } = useDomain();
const { user } = userDomainService;
const location = useLocation();
const navigate = useNavigate();
const ignore = ignorePaths.some((p) =>
pathToRegexp(p).test(location.pathname)
);
if (!ignore && !user.isLoggedIn) {
userDomainService.userAuth().then(({ success }) => {
if (!success) navigate(AuthFailedReplacePath);
});
}
return children;
};