[cs] refactor: auth 리팩토링 (@common/auth)

This commit is contained in:
2026-04-01 17:06:56 +09:00
parent 011a68e5f2
commit 2f7d860b89
14 changed files with 798 additions and 93 deletions
@@ -1,3 +1,4 @@
import { getRemainingMs } from "@common/auth";
import {
ENDPOINT,
CLAIM_NAME,
@@ -10,7 +11,6 @@ import {
clearAuthToken,
setupRefreshTimer,
} from "../lib/token-manager";
import { getRemainingMs } from "../lib/jwt-utils";
function resolveLoginError(message: string | undefined): string {
switch (message) {
@@ -3,10 +3,11 @@
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { isAxiosError } from "axios";
import { getRemainingMs } from "@common/auth";
import { isAtLoginRedirectUrl } from "@common/network";
import { client } from "@/shared/api";
import type { IUserInfo } from "@/shared/store";
import { useUserStore } from "@/shared/lib";
import { isAtLoginRedirectUrl } from "@common/network";
import {
ENDPOINT,
AUTH_USER_ID,
@@ -14,7 +15,6 @@ import {
CLAIM_NAME,
} from "@/shared/config";
import { getToken, setupRefreshTimer } from "./token-manager";
import { getRemainingMs } from "./jwt-utils";
import { silentRefresh } from "../api/login-service";
const AuthWrapper = ({ children }: { children: React.ReactNode }) => {
@@ -1,32 +0,0 @@
interface JwtPayload {
exp?: number;
[key: string]: unknown;
}
/**
* JWT 토큰의 exp 클레임(Unix timestamp, 초 단위)을 반환합니다.
* 파싱 실패 시 null을 반환합니다.
*/
export function getJwtExpiry(token: string): number | null {
try {
const base64Payload = token.split(".")[1];
if (!base64Payload) return null;
const payload = JSON.parse(atob(base64Payload)) as JwtPayload;
return typeof payload.exp === "number" ? payload.exp : null;
} catch {
return null;
}
}
/**
* 토큰 만료 1분 전까지 남은 시간(ms)을 반환합니다.
* 이미 만료됐거나 파싱 실패 시 0을 반환합니다.
*/
export function getRemainingMs(token: string): number {
const exp = getJwtExpiry(token);
if (!exp) return 0;
const remainingMs = exp * 1000 - Date.now() - 60_000;
return Math.max(0, remainingMs);
}
+13 -60
View File
@@ -1,62 +1,15 @@
import { AUTH_USER_ID, CLAIM_NAME, COOKIE_DOMAIN } from "@/shared/config";
import { getCookie, setCookie, removeCookie } from "@/shared/lib";
import { createTokenManager } from "@common/auth";
import { authConfig } from "@/shared/config/auth";
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
export const tokenManager = createTokenManager(authConfig);
export function getToken(key: string): string | undefined {
return getCookie(key);
}
export function setToken(key: string, value: string): void {
const domain = getCookieDomain();
const isHttps =
typeof window !== "undefined" && window.location.protocol === "https:";
setCookie(key, value, {
secure: isHttps,
sameSite: "lax",
domain,
path: "/",
});
}
export function removeToken(key: string): void {
const domain = getCookieDomain();
removeCookie(key, { domain, path: "/" });
}
export function setupRefreshTimer(
callback: () => Promise<void>,
delayMs: number,
): void {
if (refreshTimer) {
clearTimeout(refreshTimer);
}
refreshTimer = setTimeout(() => {
callback().catch((error) => {
console.error("Silent refresh timer callback failed:", error);
});
}, delayMs);
}
export function clearAuthToken(): void {
if (refreshTimer) {
clearTimeout(refreshTimer);
refreshTimer = null;
}
removeToken(CLAIM_NAME);
removeToken(AUTH_USER_ID);
}
function getCookieDomain(): string | undefined {
if (typeof window === "undefined") return undefined;
if (COOKIE_DOMAIN) return COOKIE_DOMAIN;
const { hostname } = window.location;
if (hostname === "localhost" || hostname === "127.0.0.1") return undefined;
return hostname;
}
export const {
getToken,
setToken,
removeToken,
setupRefreshTimer,
clearAuthToken,
getAccessToken,
getRefreshToken,
getUserId,
} = tokenManager;
+16
View File
@@ -0,0 +1,16 @@
import type { AuthConfig } from "@common/auth";
import {
ACCESS_TOKEN,
AUTH_USER_ID,
CLAIM_NAME,
COOKIE_DOMAIN,
REFRESH_TOKEN,
} from "./env";
export const authConfig: AuthConfig = {
authUserId: AUTH_USER_ID || "token-id",
claimName: CLAIM_NAME || "Authorization",
cookieDomain: COOKIE_DOMAIN,
accessToken: ACCESS_TOKEN || "access-token",
refreshToken: REFRESH_TOKEN || "refresh-token",
};