48 lines
1.1 KiB
TypeScript
48 lines
1.1 KiB
TypeScript
|
import { AuthFailedReplacePath } from "@/constant";
|
||
|
import { useLocation, useNavigate } from "react-router-dom";
|
||
|
import { useEffect } from "react";
|
||
|
import { useDomain } from "@/hook/useDomain";
|
||
|
import { message } from "antd";
|
||
|
|
||
|
interface GuardProps {
|
||
|
element: JSX.Element;
|
||
|
auth?: boolean;
|
||
|
title?: string;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 守卫
|
||
|
*/
|
||
|
export const Guard = (props: GuardProps) => {
|
||
|
const location = useLocation();
|
||
|
const navigate = useNavigate();
|
||
|
const { userDomainService } = useDomain();
|
||
|
const [messageApi, contextHolder] = message.useMessage();
|
||
|
const { isLoggedIn } = userDomainService.user;
|
||
|
|
||
|
useEffect(() => {
|
||
|
if (props.auth && !isLoggedIn) {
|
||
|
userDomainService.userAuth().then((result: any) => {
|
||
|
const { success, msg } = result;
|
||
|
if (!success) {
|
||
|
messageApi.error(msg);
|
||
|
navigate(AuthFailedReplacePath);
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
return () => {};
|
||
|
}, [navigate]);
|
||
|
|
||
|
useEffect(() => {
|
||
|
if (props?.title) document.title = props?.title;
|
||
|
return () => {};
|
||
|
}, [location.pathname]);
|
||
|
|
||
|
return (
|
||
|
<>
|
||
|
{contextHolder}
|
||
|
{props.element}
|
||
|
</>
|
||
|
);
|
||
|
};
|