251121_01_ENH : 로그인 및 인증 저장, api통신 시 자동으로 accessKey 붙게 조치

This commit is contained in:
2025-11-21 15:33:51 +09:00
parent 0707c91d41
commit 74de3d58f7
63 changed files with 2056 additions and 261 deletions

View File

@@ -1,4 +1,3 @@
// src/lib/http-client.ts
import { clientEnv } from "@/lib/env.client";
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
@@ -57,6 +56,12 @@ export type RequestOptions = {
suppressAlert?: boolean;
/** Hook for 401 responses */
onAuthError?: () => void;
/**
* 401/403(토큰 만료 포함) 수신 시 자동으로 /logout 으로 이동할지 여부
* - 기본값: true
* - 요청 단위로 false 설정하면 자동 로그아웃을 건너뜁니다.
*/
autoLogoutOnAuthError?: boolean;
/** Force treat response as text (skip JSON parse) */
expectText?: boolean;
};
@@ -116,9 +121,25 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
const request = async <T = unknown>(path: string, options: RequestOptions = {}): Promise<T> => {
// 1) URL
const replaced = replacePathParams(path, options.pathParams);
const url = /^https?:\/\//i.test(replaced)
? new URL(replaced)
: new URL(replaced, baseURL);
// NOTE:
// new URL('/x', 'http://host/base') => 'http://host/x' (pathname from base is dropped)
// We want to preserve base pathname (e.g., '/api/v1') when caller passes an absolute path like '/auth/login'.
let url: URL;
if (/^https?:\/\//i.test(replaced)) {
// Fully-qualified URL: use as-is
url = new URL(replaced);
} else if (replaced.startsWith('/')) {
// Absolute-like path: merge with base's pathname
const base = new URL(baseURL);
const joinedPath = `${base.pathname.replace(/\/+$/, '')}/${replaced.replace(/^\/+/, '')}`;
url = new URL(base.toString());
url.pathname = joinedPath;
} else {
// Relative path: URL API will correctly join with base pathname
url = new URL(replaced, new URL(baseURL));
}
appendQuery(url, options.query);
// 2) headers (defaults + token + per-call)
@@ -168,9 +189,25 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
// 7) error (HTTP status 에러)
if (!res.ok) {
const autoLogout = options.autoLogoutOnAuthError ?? true;
const suppressAlert = options.suppressAlert ?? true;
// 401 훅 호출 (기존 동작 유지)
if (res.status === 401) options.onAuthError?.();
if (!options.suppressAlert && typeof window !== "undefined") {
// 401 또는 403 (토큰 만료 포함) 시 자동 로그아웃 처리
if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") {
// 사용자 알림은 띄우지 않고 바로 로그아웃 라우팅으로 이동
try {
window.location.replace("/logout");
} catch {
// noop
}
// 이후 로직 진행을 막기 위해 에러를 던지기
throw new HttpError(res.status, parsed, url.toString(), res.headers);
}
if (!suppressAlert && typeof window !== "undefined") {
const serverMsg =
typeof parsed === "object" &&
parsed !== null &&