Files
frontend/apps/sn/app/components/lib/auth/lib/auth-wrapper.tsx
T
2025-06-04 16:11:32 +09:00

88 lines
2.6 KiB
TypeScript

"use client";
import { useEffect } from "react";
import { useRouter, usePathname } from "next/navigation";
import axios from "axios";
import Cookies from "js-cookie";
import { useUserStore, type IUserInfo } from "@store";
import { getCookie } from "@utils";
import { LoginApi } from "../api/login-service";
import { tokenManager } from "../lib/token-manager";
const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
const ENDPOINT = {
USER_SERVICE: {
LOGIN: "/user-service/login",
USERS: "/user-service/api/v1/users",
SILENT_REFRESH: "/user-service/api/v1/users/token/refresh",
AUTHORIZATIONS: "/user-service/api/v1/authorizations",
ROLE_AUTHORIZATIONS: "/user-service/api/v1/role-authorizations",
},
};
const AuthWrapper = ({ children }: { children: React.ReactNode }) => {
const router = useRouter();
const pathname = usePathname(); // 현재 경로
const { userInfo, setUserInfo } = useUserStore((state) => state);
async function authCheck() {
const checkToken = getCookie(AUTH_USER_ID);
if (!checkToken) {
//TODO 나중에 수정해야....
const userId = "admin1gmail";
const password = "test1234!";
await LoginApi.login({ userId, password });
// window.location.href = "http://dev.onasys.co.kr/auth/login";
// throw new Error("Missing required authentication tokens");
}
const accessToken = tokenManager.getToken(CLAIM_NAME);
const tokenId = tokenManager.getToken(AUTH_USER_ID);
const response = await axios.get<IUserInfo>(
`${ENDPOINT.USER_SERVICE.USERS}/info/me`,
{
withCredentials: true,
headers: {
[CLAIM_NAME]: accessToken,
[AUTH_USER_ID]: tokenId ?? "",
},
},
);
if (!userInfo) setUserInfo(response.data);
}
useEffect(() => {
(async () => {
try {
await authCheck();
} catch (error) {
console.error("Auth check failed:", error);
try {
await LoginApi.silentRefresh();
await authCheck();
} catch (refreshError) {
console.error("Token refresh failed:", refreshError);
setUserInfo(null);
// TODO 운영에 반영 할때 수정해야.....
// 현재 경로가 로그인 페이지가 아닐 때만 redirect
// if (!pathname.startsWith("/auth/login")) {
// window.location.href = "http://dev.onasys.co.kr/auth/login";
// }
}
}
})();
}, [pathname]); // pathname도 의존성에 포함
return <>{children}</>;
};
export { AuthWrapper };