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

@@ -0,0 +1,11 @@
export const CookieKeys = {
FontSize: "kri_fontSize",
// 필요하면 여기 계속 추가 (예: Theme: "kri_theme", ...)
} as const;
export const CookieType: Record<CookieKey, "session" | "persistence-http-only" | "persistence"> = {
[CookieKeys.FontSize]: "persistence",
};
export type CookieKey = (typeof CookieKeys)[keyof typeof CookieKeys];

105
src/store/cookie/cookie.ts Normal file
View File

@@ -0,0 +1,105 @@
"use client";
import type { CookieKey } from "./cookie-keys";
export type CookieSetOptions = {
days?: number; // 만료일: 기본 365일
path?: string; // 기본 "/"
secure?: boolean;
sameSite?: "Lax" | "Strict" | "None";
};
function isBrowser() {
return typeof document !== "undefined";
}
function buildCookieString(
key: CookieKey,
value: string,
options: CookieSetOptions = {},
): string {
const {
days = 365,
path = "/",
secure = false,
sameSite = "Lax",
} = options;
let cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
// 만료일
if (Number.isFinite(days)) {
const expires = new Date();
expires.setDate(expires.getDate() + days);
cookie += `; Expires=${expires.toUTCString()}`;
}
if (path) {
cookie += `; Path=${path}`;
}
if (secure) {
cookie += "; Secure";
}
if (sameSite) {
cookie += `; SameSite=${sameSite}`;
}
return cookie;
}
export const cookieStore = {
/**
* 문자열 값 가져오기 (없으면 null)
*/
get(key: CookieKey): string | null {
if (!isBrowser()) return null;
try {
const name = encodeURIComponent(key) + "=";
const cookies = document.cookie ? document.cookie.split("; ") : [];
for (const c of cookies) {
if (c.startsWith(name)) {
const value = c.substring(name.length);
return decodeURIComponent(value);
}
}
return null;
} catch {
return null;
}
},
/**
* 문자열 값 저장
*/
set(key: CookieKey, value: string, options?: CookieSetOptions) {
if (!isBrowser()) return;
try {
const cookie = buildCookieString(key, value, options);
document.cookie = cookie;
} catch {
// 쿠키 설정 실패는 조용히 무시
}
},
/**
* 쿠키 삭제
*/
remove(key: CookieKey, options?: Omit<CookieSetOptions, "days">) {
if (!isBrowser()) return;
try {
document.cookie = buildCookieString(key, "", {
...(options ?? {}),
days: -1, // 과거로 설정해서 삭제
});
} catch {
// 무시
}
},
};

22
src/store/jotai/auth.ts Normal file
View File

@@ -0,0 +1,22 @@
"use client";
import { createLocalStorageAtom } from "@/store/jotai/utils";
import { StorageKeys } from "@/store/storage/storage-keys";
import type { LoginUser } from "@/types/auth";
export type AuthState = {
user: LoginUser | null;
seatNumber: string | null;
};
const initialAuthState: AuthState = {
user: null,
seatNumber: null,
};
/**
* AES 암호화된 localStorage 기반 로그인 상태 Atom
*/
export const authStateAtom = createLocalStorageAtom<AuthState>(
StorageKeys.AuthState,
initialAuthState,
);

View File

@@ -0,0 +1,8 @@
"use client";
import { atom } from "jotai";
/**
* 전역 로딩 상태
*/
export const loadingAtom = atom(false);

View File

@@ -0,0 +1,23 @@
"use client";
import { StorageKeys } from "@/store/storage/storage-keys";
import {createSessionStorageAtom} from "@/store/jotai/utils";
import {AuthState} from "@/store/jotai/auth";
export type SelectedProject = {
id: string;
name: string;
// 필요하면 여기서 추가 (code, status 등)
};
/**
* 탭별로 유지되는 선택 프로젝트 정보
* - 새로고침: 유지
* - 같은 탭: 유지
* - 탭/브라우저 닫으면: 삭제
*/
export const selectedProjectAtom =
createSessionStorageAtom<SelectedProject | null>(
StorageKeys.SelectedProject,
null,
);

118
src/store/jotai/utils.ts Normal file
View File

@@ -0,0 +1,118 @@
"use client";
import { atom, type PrimitiveAtom } from "jotai";
import {
setLocalStorage,
getLocalStorage,
removeLocalStorage,
setSessionStorage,
getSessionStorage,
removeSessionStorage
} from "@/store/storage/secure-storage";
import {StorageKey} from "@/store/storage/storage-keys";
const loadInitialState = <T>(storageType: "local"|"session", key: StorageKey, initialValue: T): T => {
if (typeof window === "undefined") {
// SSR 시에는 그냥 기본값 사용
return initialValue;
}
const stored = storageType == "local" ? getLocalStorage(key) : getSessionStorage(key);
if (stored && typeof stored === "object") {
return stored as T;
}
return initialValue;
}
/**
* localStorage(AES 암호화) + Jotai 연동용 Atom 생성기
* - initialValue: SSR 시/최초 렌더 시 기본값
* - 마운트 후 localStorage에서 실제 값 읽어와서 덮어씀
*/
export const createLocalStorageAtom = <T>(
key: StorageKey,
initialValue: T,
) => {
const realInitialValue = loadInitialState("local", key, initialValue);
const baseAtom: PrimitiveAtom<T> = atom<T>(realInitialValue);
// 하이드레이션(저장소 주입)과 사용자 set 경합 방지용 플래그
let wasOverridden = false; // 마운트 이후 사용자가 값을 쓴 적이 있는지
const persistentAtom = atom(
(get) => get(baseAtom),
(get, set, update: T | ((prev: T) => T)) => {
const prev = get(baseAtom);
const next =
typeof update === "function"
? (update as (prev: T) => T)(prev)
: update;
// 메모리 상태 갱신
set(baseAtom, next);
// 사용자 쓰기 발생 표시 (하이드레이션이 도착해도 무시하도록)
wasOverridden = true;
// 값이 초기값과 동일하면 키 제거로 처리하여 '비움'을 명확히 함
const isInitial = (() => {
try {
return JSON.stringify(next) === JSON.stringify(realInitialValue);
} catch {
// 비교 실패 시 보수적으로 저장하도록 함
return false;
}
})();
if (isInitial) {
// 암호화 localStorage 및 캐시 제거
removeLocalStorage(key);
} else {
// 동기 API로 캐시를 먼저 기록하고 암호화 저장은 백그라운드 처리
setLocalStorage(key, next);
}
},
);
return persistentAtom;
}
/**
* sessionStorage + Jotai 연동용 Atom 생성기
* - 탭 단위로 유지, 탭/브라우저 닫히면 삭제
* - 새로고침 시 유지
*/
export const createSessionStorageAtom = <T>(
key: StorageKey,
initialValue: T,
) => {
const realInitialValue = loadInitialState("session", key, initialValue);
const baseAtom: PrimitiveAtom<T> = atom<T>(realInitialValue);
const persistentAtom = atom(
(get) => get(baseAtom),
(get, set, update: T | ((prev: T) => T)) => {
const prev = get(baseAtom);
const next =
typeof update === "function"
? (update as (prev: T) => T)(prev)
: update;
set(baseAtom, next);
if (typeof window === "undefined") return;
try {
if (next === null || (next as unknown) === undefined) {
removeSessionStorage(key)
} else {
setSessionStorage(key, next);
}
} catch {
// sessionStorage 에러는 조용히 무시
}
},
);
return persistentAtom;
}

View File

@@ -0,0 +1,128 @@
import { Security } from "@/lib/security";
import {clientEnv} from "@/lib/env.client";
type StorageValue = any; // 요청대로 any 유지
// --- 내부 헬퍼 함수들 ---
const getDecryptedValue = (value: string): StorageValue => {
try {
if (!value || value.trim() === "") {
return null;
}
const decryptValue = clientEnv.ENV ==="prod" ? Security.decryptBase64(value) : value;
if (!decryptValue || decryptValue.trim() === "") {
return null;
}
return JSON.parse(decryptValue);
} catch (error) {
// 손상된 데이터인 경우 null 반환
return null;
}
};
const getEncryptedValue = (value: StorageValue): string => {
const stringifyValue = JSON.stringify(value);
return clientEnv.ENV ==="prod" ? Security.encryptBase64(stringifyValue) : stringifyValue;
};
// --- LocalStorage 함수들 ---
export const setLocalStorage = (key: string, value: StorageValue): void => {
try {
const encryptValue = getEncryptedValue(value);
localStorage.setItem(key, encryptValue);
} catch (error) {
// 필요하면 로깅 추가
}
};
export const getLocalStorage = (key: string): StorageValue => {
try {
const encryptValue: string | null = localStorage.getItem(key);
if (encryptValue === null || encryptValue === "") {
return null;
}
let value: StorageValue = null;
try {
// 암호화된 값 복호화 시도
value = getDecryptedValue(encryptValue);
} catch (decryptError) {
// 복호화 실패 시 평문으로 파싱 시도 (fallback)
try {
value = JSON.parse(encryptValue);
} catch (fallbackError) {
// 완전히 실패한 경우 저장된 데이터 제거
localStorage.removeItem(key);
return null;
}
}
return value;
} catch (error) {
return null;
}
};
export const removeLocalStorage = (key: string): void => {
localStorage.removeItem(key);
};
export const clearLocalStorage = (): void => {
localStorage.clear();
};
// --- SessionStorage 함수들 ---
// 세션스토리지는 테스트/실제 서버 모두 암호화 없음
export const setSessionStorage = (key: string, value: StorageValue): void => {
try {
const encryptValue = getEncryptedValue(value);
sessionStorage.setItem(key, encryptValue);
} catch (error) {
// 필요하면 로깅 추가
}
};
export const getSessionStorage = (key: string): StorageValue => {
try {
const encryptValue: string | null = sessionStorage.getItem(key);
if (encryptValue === null || encryptValue === "") {
return null;
}
let value: StorageValue = null;
try {
// 암호화된 값 복호화 시도
value = getDecryptedValue(encryptValue);
} catch (decryptError) {
// 복호화 실패 시 평문으로 파싱 시도 (fallback)
try {
value = JSON.parse(encryptValue);
} catch (fallbackError) {
// 완전히 실패한 경우 저장된 데이터 제거
localStorage.removeItem(key);
return null;
}
}
return value;
} catch (error) {
return null;
}
};
export const removeSessionStorage = (key: string): void => {
sessionStorage.removeItem(key);
};
export const clearSessionStorage = (): void => {
sessionStorage.clear();
};

View File

@@ -0,0 +1,17 @@
export const StorageKeys = {
AuthState: "kri:authState",
SeatNumber: "kri:seatNumber",
LoginType: "kri:loginType",
SelectedProject: "kri:selectedProject",
//SidebarCollapsed: "kri:sidebarCollapsed",
// 필요하면 여기 계속 추가
} as const;
export const StorageType: Record<StorageKey, "local" | "session"> = {
[StorageKeys.AuthState]: "local",
[StorageKeys.SeatNumber]: "local",
[StorageKeys.LoginType]: "local",
[StorageKeys.SelectedProject]: "session",
};
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];