75 lines
2.2 KiB
TypeScript
75 lines
2.2 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
|
|
import { isAxiosError } from "axios";
|
|
|
|
import { client } from "@/shared/api";
|
|
import { AUTH_LOGIN_REDIRECT_URL, AUTH_USER_ID, CLAIM_NAME, ENDPOINT } from "@/shared/config";
|
|
import { useUserStore } from "@/shared/lib";
|
|
import type { IUserInfo } from "@/shared/store";
|
|
import { getRemainingMs } from "@common/auth";
|
|
import { isAtLoginRedirectUrl } from "@common/network";
|
|
|
|
import { authService } from "../api/auth-service";
|
|
|
|
import { getToken, setupRefreshTimer } from "./token-manager";
|
|
|
|
const AuthWrapper = ({ children }: { children: React.ReactNode }) => {
|
|
const router = useRouter();
|
|
const userInfo = useUserStore((state) => state.userInfo);
|
|
const setUserInfo = useUserStore((state) => state.setUserInfo);
|
|
|
|
useEffect(() => {
|
|
const token = getToken(CLAIM_NAME);
|
|
if (token) {
|
|
const remainingMs = getRemainingMs(token);
|
|
if (remainingMs > 0) {
|
|
console.log(`[AuthWrapper] Refresh timer set: ${remainingMs}ms (${remainingMs / 1000}s)`);
|
|
setupRefreshTimer(authService.silentRefresh, remainingMs);
|
|
}
|
|
}
|
|
|
|
if (isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL)) return;
|
|
|
|
async function authCheck() {
|
|
const userId = getToken(AUTH_USER_ID);
|
|
if (!userId) {
|
|
router.replace(AUTH_LOGIN_REDIRECT_URL);
|
|
return;
|
|
}
|
|
|
|
if (userInfo) return;
|
|
|
|
const response = await client.get<IUserInfo>(`${ENDPOINT.USER_SERVICE.USERS}/info/me`);
|
|
setUserInfo(response.data);
|
|
}
|
|
|
|
authCheck().catch((error) => {
|
|
if (isAxiosError(error) && error.response?.status === 401) return;
|
|
console.error(error);
|
|
setUserInfo(null);
|
|
if (!isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL)) {
|
|
router.replace(AUTH_LOGIN_REDIRECT_URL);
|
|
}
|
|
});
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
function handleAuthLogout() {
|
|
setUserInfo(null);
|
|
if (!isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL)) {
|
|
router.replace(AUTH_LOGIN_REDIRECT_URL);
|
|
}
|
|
}
|
|
|
|
window.addEventListener("auth:logout", handleAuthLogout);
|
|
return () => window.removeEventListener("auth:logout", handleAuthLogout);
|
|
}, []);
|
|
|
|
return <>{children}</>;
|
|
};
|
|
|
|
export { AuthWrapper };
|