51 lines
1.2 KiB
TypeScript
51 lines
1.2 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect } from "react";
|
|
import { client } from "@/shared/api";
|
|
import type { IUserInfo } from "@/shared/store";
|
|
import { getCookie, useUserStore } from "@/shared/lib";
|
|
import { isAtLoginRedirectUrl } from "@common/network";
|
|
import {
|
|
ENDPOINT,
|
|
AUTH_USER_ID,
|
|
AUTH_LOGIN_REDIRECT_URL,
|
|
} from "@/shared/config";
|
|
|
|
const AuthWrapper = ({ children }: { children: React.ReactNode }) => {
|
|
const { userInfo, setUserInfo } = useUserStore((state) => state);
|
|
|
|
async function authCheck() {
|
|
if (isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL)) {
|
|
return;
|
|
}
|
|
|
|
const userId = getCookie(AUTH_USER_ID);
|
|
if (!userId) {
|
|
throw new Error("Missing required authentication tokens");
|
|
}
|
|
|
|
const response = await client.get<IUserInfo>(
|
|
`${ENDPOINT.USER_SERVICE.USERS}/info/me`,
|
|
);
|
|
if (!userInfo) setUserInfo(response.data);
|
|
}
|
|
|
|
useEffect(() => {
|
|
(async () => {
|
|
try {
|
|
await authCheck();
|
|
} catch (error) {
|
|
console.error(error);
|
|
setUserInfo(null);
|
|
if (!isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL)) {
|
|
window.location.assign(AUTH_LOGIN_REDIRECT_URL);
|
|
}
|
|
}
|
|
})();
|
|
}, []);
|
|
|
|
return <>{children}</>;
|
|
};
|
|
|
|
export { AuthWrapper };
|