monorepo-microservice-rbac/apps/aorta/src/router/AuthGuard.tsx

30 lines
817 B
TypeScript
Raw Normal View History

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