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

51
src/hooks/useAuth.ts Normal file
View File

@@ -0,0 +1,51 @@
"use client";
import { useCallback } from "react";
import { useAtom } from "jotai";
import { authStateAtom, type AuthState } from "@/store/jotai/auth";
import type { LoginUser } from "@/types/auth";
export const useAuth = () => {
const [auth, setAuth] = useAtom(authStateAtom);;
// 로그인 성공 후 LoginResponse 를 바로 넣어줄 수 있게
const setFromLoginResponse = useCallback(
(res: LoginUser, loginSeatNumber:string|null = null) => {
setAuth({
user: res,
seatNumber: loginSeatNumber,
});
},
[setAuth],
);
const updateAuth = useCallback(
(next: AuthState | ((prev: AuthState) => AuthState)) => {
setAuth(next);
},
[setAuth],
);
const logout = useCallback(() => {
// 저장소의 인증 정보(암호화 localStorage + session cache) 즉시 제거하여
// 리다이렉트/새로고침 시 재하이드레이션되는 문제를 방지
try {
} catch {
// 스토리지 접근 실패는 무시하고 메모리 상태만이라도 초기화
}
// 메모리 상태도 초기화
setAuth({
user: null,
seatNumber: null,
});
}, [setAuth]);
return {
auth,
setAuth: updateAuth,
setFromLoginResponse,
logout,
};
}

106
src/hooks/useFontSize.ts Normal file
View File

@@ -0,0 +1,106 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { cookieStore } from "@/store/cookie/cookie";
import { CookieKeys } from "@/store/cookie/cookie-keys";
import commonConst from "@/config/commonConst";
const MIN_FONT_SIZE = 12;
const MAX_FONT_SIZE = 24;
const DEFAULT_DAYS = 365;
const clampFontSize = (size: number) => {
return Math.min(MAX_FONT_SIZE, Math.max(MIN_FONT_SIZE, size));
}
/**
* 쿠키에서 폰트 사이즈 읽기
*/
const readFontSizeFromCookie = (defaultSize: number): number => {
const raw = cookieStore.get(CookieKeys.FontSize);
if (!raw) return defaultSize;
const parsed = parseInt(raw, 10);
if (Number.isNaN(parsed)) return defaultSize;
return clampFontSize(parsed);
}
/**
* 쿠키에 폰트 사이즈 저장
*/
const writeFontSizeToCookie = (size: number) => {
const clamped = clampFontSize(size);
cookieStore.set(CookieKeys.FontSize, String(clamped), {
days: DEFAULT_DAYS,
path: "/",
sameSite: "Lax",
});
}
type UseFontSizeOptions = {
/**
* 클라이언트 마운트 시 쿠키에서 초기값을 다시 읽어올지 여부
* - true: (기본값) 쿠키에서 읽어옴
* - false: 전달받은 defaultSize를 그대로 사용 (SSR 값 유지, FOUC 방지)
*/
hydrateFromCookie?: boolean;
}
export const useFontSize = (
defaultSize: number = commonConst.fontSizeDefault,
options: UseFontSizeOptions = {},
) => {
const { hydrateFromCookie = true } = options;
const [fontSize, setFontSize] = useState<number>(() => {
// SSR로 전달된 초기값을 신뢰해야 하는 경우 쿠키 재조회 생략
if (!hydrateFromCookie) return clampFontSize(defaultSize);
return readFontSizeFromCookie(defaultSize);
});
// CSS 변수 동기화
useEffect(() => {
if (typeof document === "undefined") return;
document.documentElement.style.setProperty(
"--content-font-size",
`${fontSize}px`,
);
}, [fontSize]);
// 다른 컴포넌트/페이지에서 변경한 폰트 크기와 상태 동기화
// 요청사항 반영: 브로드캐스트 수신 시 event.detail 대신 "쿠키"를 다시 읽어 반영한다.
useEffect(() => {
if (typeof window === "undefined") return;
const handler = (_e: Event) => {
// 쿠키에 저장된 최신 값을 읽어 상태를 동기화한다.
// 기본값은 현재 상태값을 폴백으로 사용하여 불필요한 변경을 방지한다.
const next = readFontSizeFromCookie(fontSize);
setFontSize(next);
};
window.addEventListener("fontSizeChange", handler as EventListener);
return () => window.removeEventListener("fontSizeChange", handler as EventListener);
}, []);
const updateFontSize = useCallback((next: number) => {
const clamped = clampFontSize(next);
setFontSize(clamped);
writeFontSizeToCookie(clamped);
// 전역 이벤트로 다른 훅 인스턴스들에 변경 사항 전파
if (typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent("fontSizeChange", { detail: clamped }));
}
}, []);
return [fontSize, updateFontSize] as const;
}
export const useFontSizeValue = (
options: UseFontSizeOptions = {},
) => {
const defaultSize = commonConst.fontSizeDefault;
const [fontSize] = useFontSize(defaultSize, options);
return fontSize;
}

56
src/hooks/useLoading.ts Normal file
View File

@@ -0,0 +1,56 @@
"use client";
import { useAtom } from "jotai";
import { useCallback } from "react";
import { loadingAtom } from "@/store/jotai/loading";
export const useLoading = () => {
const [isLoading, setIsLoading] = useAtom(loadingAtom);
const showLoading = useCallback(() => {
setIsLoading(true);
}, [setIsLoading]);
const hideLoading = useCallback(() => {
setIsLoading(false);
}, [setIsLoading]);
/**
* 비동기 함수 호출 시 편하게 쓸 수 있는 래퍼
*
* 예)
* const { withLoading } = useLoading();
* await withLoading(() => apiCall());
*/
const withLoadingAsync = useCallback(
async <T,>(fn: () => Promise<T>): Promise<T> => {
showLoading();
try {
return await fn();
} finally {
hideLoading();
}
},
[showLoading, hideLoading],
);
const withLoading = useCallback(
<T,>(fn: () => T): T => {
showLoading();
try {
return fn();
} finally {
hideLoading();
}
},
[showLoading, hideLoading],
);
return {
isLoading,
showLoading,
hideLoading,
withLoading,
withLoadingAsync,
} as const;
}

View File

@@ -0,0 +1,16 @@
"use client";
import { useAtom } from "jotai";
import { selectedProjectAtom } from "@/store/jotai/project";
export const useSelectedProject = () => {
const [selectedProject, setSelectedProject] = useAtom(selectedProjectAtom);
const clearSelectedProject = () => setSelectedProject(null);
return {
selectedProject,
setSelectedProject,
clearSelectedProject,
} as const;
}

49
src/hooks/useStorage.ts Normal file
View File

@@ -0,0 +1,49 @@
"use client";
import {
setLocalStorage,
getLocalStorage,
removeLocalStorage,
setSessionStorage,
getSessionStorage,
removeSessionStorage,
} from "@/store/storage/secure-storage";
import { StorageKey, StorageType } from "@/store/storage/storage-keys";
/**
* 사용법:
* const { set, get, remove } = useStorage(StorageKeys.SeatNumber);
*/
export const useStorage = (key: StorageKey) => {
const storageType = StorageType[key]; // "local" | "session"
const set = (value: any): void => {
if (storageType === "session") {
setSessionStorage(key, value);
} else {
setLocalStorage(key, value);
}
};
const get = (): any => {
if (storageType === "session") {
return getSessionStorage(key);
} else {
return getLocalStorage(key);
}
};
const remove = (): void => {
if (storageType === "session") {
removeSessionStorage(key);
} else {
removeLocalStorage(key);
}
};
return {
set,
get,
remove,
} as const;
};