128 lines
3.4 KiB
TypeScript
128 lines
3.4 KiB
TypeScript
import { AUTH_USER_ID, CLAIM_NAME } from "@/shared/config";
|
|
import { getCookie, setCookie, removeCookie } from "@/shared/lib";;
|
|
|
|
type JwtPayload = {
|
|
sub?: string;
|
|
exp?: number;
|
|
iat?: number;
|
|
[key: string]: unknown;
|
|
};
|
|
|
|
export class TokenManager {
|
|
private static instance: TokenManager;
|
|
private refreshTimer: NodeJS.Timeout | null = null;
|
|
|
|
private constructor() { }
|
|
|
|
public static getInstance(): TokenManager {
|
|
if (!TokenManager.instance) {
|
|
TokenManager.instance = new TokenManager();
|
|
}
|
|
return TokenManager.instance;
|
|
}
|
|
|
|
public getToken(key: string): string | undefined {
|
|
return getCookie(key);
|
|
}
|
|
|
|
private parseJwt(token: string): JwtPayload {
|
|
const parts = token.split(".");
|
|
if (parts.length !== 3) {
|
|
throw new Error("유효한 JWT 형식이 아닙니다.");
|
|
}
|
|
|
|
const base64Url = parts[1] ?? "";
|
|
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
|
|
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
|
|
const jsonPayload = decodeURIComponent(
|
|
atob(padded)
|
|
.split("")
|
|
.map((char) => `%${char.charCodeAt(0).toString(16).padStart(2, "0")}`)
|
|
.join("")
|
|
);
|
|
|
|
return JSON.parse(jsonPayload) as JwtPayload;
|
|
}
|
|
|
|
public getRemainingMsFromToken(key: string = CLAIM_NAME): number | null {
|
|
const token = this.getToken(key);
|
|
if (!token) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
const payload = this.parseJwt(token);
|
|
if (typeof payload.exp !== "number") {
|
|
return null;
|
|
}
|
|
|
|
return payload.exp * 1000 - Date.now();
|
|
} catch (error) {
|
|
console.error("JWT 파싱 오류:", error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public isExpiredToken(key: string = CLAIM_NAME): boolean {
|
|
const remainingMs = this.getRemainingMsFromToken(key);
|
|
return remainingMs === null || remainingMs <= 0;
|
|
}
|
|
|
|
public setToken(key: string, value: string): void {
|
|
// 환경에 따른 도메인 설정
|
|
//const domain = this.getCookieDomain();
|
|
|
|
setCookie(key, value, {
|
|
secure: window.location.protocol === "https:",
|
|
sameSite: "lax",
|
|
//domain: domain,
|
|
path: "/",
|
|
});
|
|
}
|
|
|
|
private getCookieDomain(): string | undefined {
|
|
const hostname = window.location.hostname;
|
|
|
|
// 개발 환경에서는 localhost 도메인 사용
|
|
if (hostname === "localhost" || hostname === "127.0.0.1") return undefined; // localhost에서는 도메인 설정하지 않음
|
|
|
|
// 운영 환경에서는 서브도메인을 포함한 최상위 도메인 사용
|
|
if (hostname.includes("hasuon.or.kr")) return ".hasuon.or.kr"; // 모든 서브도메인에서 공유
|
|
|
|
// 기타 환경에서는 현재 호스트명 사용
|
|
return hostname;
|
|
}
|
|
|
|
public removeToken(key: string): void {
|
|
removeCookie(key);
|
|
}
|
|
|
|
public setupRefreshTimer(
|
|
callback: () => Promise<void>,
|
|
expirationTime: number,
|
|
): void {
|
|
if (this.refreshTimer) {
|
|
clearTimeout(this.refreshTimer);
|
|
}
|
|
|
|
this.refreshTimer = setTimeout(() => {
|
|
callback().catch((error) => {
|
|
console.error("Silent refresh failed:", error);
|
|
this.clearAuthToken();
|
|
});
|
|
}, expirationTime - 60000);
|
|
}
|
|
|
|
public clearAuthToken(): void {
|
|
if (this.refreshTimer) {
|
|
clearTimeout(this.refreshTimer);
|
|
this.refreshTimer = null;
|
|
}
|
|
|
|
this.removeToken(CLAIM_NAME);
|
|
this.removeToken(AUTH_USER_ID);
|
|
}
|
|
}
|
|
|
|
export const tokenManager = TokenManager.getInstance();
|