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,12 +0,0 @@
import { createHttpClient } from "@/lib/http-client";
import {LoginRequest, LoginResponse} from "@/types/auth";
import {serverEnv} from "@/lib/env.server";
console.log("[server] API_INTRANET =", serverEnv.API_INTRANET);
const http = createHttpClient(serverEnv.API_INTRANET);
// 인트라넷 백엔드로 실제 로그인 요청
export const intranetApi = {
login: (payload: LoginRequest) =>
http.post<LoginResponse>("/auth/login", payload),
};

View File

@@ -1,20 +0,0 @@
const MainLayout = ({ children }: { children: React.ReactNode}) => {
return (
<div className="min-h-screen flex flex-col">
{/* 공통 헤더 */}
<header className="h-14 border-b px-4 flex items-center">
<h1 className="font-semibold">Contact Admin</h1>
</header>
{/* 메인 컨텐츠 영역 */}
<main className="flex-1 flex">
{/* 필요하면 사이드바 */}
{/* <aside className="w-60 border-r">사이드바</aside> */}
<section className="flex-1 p-4">{children}</section>
</main>
</div>
);
}
export default MainLayout;

View File

@@ -1,8 +0,0 @@
const ListPage = () => {
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is List Page</div>)
}
export default ListPage;

View File

@@ -1,8 +0,0 @@
const UserPage = () => {
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is User Page</div>)
}
export default UserPage;

View File

@@ -0,0 +1,8 @@
const ListAssignPage = () => {
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is List Assign Page</div>)
}
export default ListAssignPage;

View File

@@ -0,0 +1,8 @@
const ProjectAssignPage = () => {
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is Project Assign Page</div>)
}
export default ProjectAssignPage;

View File

@@ -0,0 +1,40 @@
import MainLayout from "@/components/layout/MainLayout";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import {CookieKeys} from "@/store/cookie/cookie-keys";
import commonConst from "@/config/commonConst";
function parseFontSize(raw: string | undefined | null) {
if (!raw) return commonConst.fontSizeMin;
const parsed = parseInt(raw, 10);
if (Number.isNaN(parsed)) return commonConst.fontSizeMin;
return Math.min(
commonConst.fontSizeMax,
Math.max(commonConst.fontSizeMin, parsed),
);
}
export default async function MainLayoutWrapper({
children,
}: {
children: React.ReactNode;
}) {
const cookieStore = await cookies();
const cookie = cookieStore.get(CookieKeys.FontSize);
const accessToken = cookieStore.get("access_token")?.value;
const initialFontSize = parseFontSize(cookie?.value);
if (!accessToken) {
redirect("/logout");
}
return (
<>
<MainLayout initialFontSize={initialFontSize}>
{children}
</MainLayout>
</>
);
}

View File

@@ -0,0 +1,8 @@
const ListContactPage = () => {
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is List Contact Page</div>)
}
export default ListContactPage;

View File

@@ -0,0 +1,21 @@
"use client";
import {useFontSizeValue} from "@/hooks/useFontSize";
import {useEffect, useState} from "react";
const ListManagePage = () => {
const fontSize = useFontSizeValue();
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return null;
return (
<div>
This is Manage List Page <span>{fontSize}</span>
</div>
);
};
export default ListManagePage;

View File

@@ -0,0 +1,8 @@
const UserManagePage = () => {
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is User Manage Page</div>)
}
export default UserManagePage;

View File

@@ -0,0 +1,9 @@
const EmailTemplatePage = () => {
//파라미터 받기
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is Email Template Page</div>)
}
export default EmailTemplatePage;

View File

@@ -0,0 +1,9 @@
const TextTemplatePage = () => {
//파라미터 받기
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is Text Message Template Page</div>)
}
export default TextTemplatePage;

View File

@@ -0,0 +1,8 @@
const ContactProgressPage = () => {
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is Contact Progress Page</div>)
}
export default ContactProgressPage;

View File

@@ -0,0 +1,8 @@
const FieldworkProgressPage = () => {
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is Fieldwork Progress Page</div>)
}
export default FieldworkProgressPage;

View File

@@ -0,0 +1,8 @@
const MessageProgressPage = () => {
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is Message Progress Page</div>)
}
export default MessageProgressPage;

View File

@@ -0,0 +1,8 @@
const ProjectInfoPage = () => {
//const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
//redirect(url);
return (<div>This is Project Info Page</div>)
}
export default ProjectInfoPage;

View File

@@ -0,0 +1,209 @@
"use client";
import Image from "next/image";
import {Button} from "@/components/ui/button";
import {Card, CardContent, CardHeader} from "@/components/ui/card";
import {Input} from "@/components/ui/input";
import React, {useEffect, useRef, useState} from "react";
import {HttpError, nextApi} from "@/lib/http-client";
import {useRouter, useSearchParams} from "next/navigation";
import {LoginUser} from "@/types/auth";
import { useAuth } from "@/hooks/useAuth";
import { useLoading } from "@/hooks/useLoading";
import { useStorage } from "@/hooks/useStorage"
import { StorageKeys } from "@/store/storage/storage-keys";
const LoginPage = () => {
const router = useRouter();
const searchParams = useSearchParams();
const { setFromLoginResponse } = useAuth();
const { withLoadingAsync } = useLoading();
const { get: getSeatNumberStorage, set: setSeatNumberStorage } = useStorage(StorageKeys.SeatNumber);
const { get: getLoginTypeStorage, set: setLoginTypeStorage } = useStorage(StorageKeys.LoginType);
const [error, setError] = useState<string | null>(null);
const [userId, setUserId] = useState<string>("");
const [userPw, setUserPw] = useState<string>("");
const [seatNum, setSeatNum] = useState<string>(getSeatNumberStorage());
const [loginType, setLoginType] = useState<string>(getLoginTypeStorage());
const passwordInputRef = useRef<HTMLInputElement | null>(null);
const seatNumberInputRef = useRef<HTMLInputElement | null>(null);
const tryLogin = () => {
if(!userId){
alert("아이디를 입력해 주세요");
}
if(!userPw){
alert("PW를 입력해 주세요");
}
if(loginType === "call" && !seatNum){
alert("자리번호를 입력해 주세요");
}
setError(null);
const loginRequestBody = {userId, userPw};
const loginRequestOptions = {autoLogoutOnAuthError: false};
// withLoading 래퍼로 API 호출 전/후 로딩 표시를 자동으로 처리
return withLoadingAsync(() =>
nextApi.post<LoginUser>(
"/api/login", loginRequestBody, loginRequestOptions
).then(async (data) => { // Jotai 기반 전역 인증 상태 갱신
setFromLoginResponse(data, seatNum);
// 요구사항: 페이지 이동 전에 SeatNumber를 secure-local-storage에 저장
try {
setSeatNumberStorage(seatNum);
setLoginTypeStorage(loginType);
} catch (e) {
// 저장 실패는 치명적이지 않으므로 콘솔 로깅만
console.warn("Failed to persist SeatNumber to secure storage:", e);
}
// 메인 페이지로 이동 (보호 라우트 진입)
router.replace("/");
}).catch((err) => {
if (err instanceof HttpError) {
if (err.status === 401 || err.status === 403) {
setError("아이디 또는 비밀번호를 다시 확인해주세요.");
} else {
setError(`로그인에 실패했습니다. (status: ${err.status})`);
}
} else {
console.error(err);
setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
}
})
);
}
// URL 쿼리 파라미터에서 type 수신
useEffect(() => {
const typeParam = searchParams.get("type") ?? "";
let seatNumTemp = "";
if(typeParam === "call") {
seatNumTemp = getSeatNumberStorage();
}
setSeatNum(seatNumTemp);
setLoginType(typeParam);
}, [searchParams]);
const handleIdKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") {
e.preventDefault();
passwordInputRef.current?.focus();
}
};
const handlePwKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") {
e.preventDefault();
const seatNumberInput = seatNumberInputRef.current;
if(loginType === "call" && seatNumberInput?.value === ""){
seatNumberInput.focus();
}
else{
tryLogin();
}
}
};
const handleSeatNumberKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") {
e.preventDefault();
tryLogin();
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 p-4">
<Card className="w-full max-w-md shadow-xl">
<CardHeader className="space-y-4 pb-8">
<div className="flex justify-center">
<div className="w-60 h-32 flex items-center justify-center">
<Image
src="/kri_logo.png" // public/kri_logo.png
alt="KRI 로고"
width={500} // 원하는 크기로 줄이기
height={500}
className="object-contain ml-10"
priority
/>
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">ID</label>
<Input
id="id"
name="id"
type="text"
required
placeholder="아이디를 입력하세요"
value={userId}
onChange={(e) => setUserId(e.currentTarget.value)}
onKeyDown={handleIdKeyDown}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Password</label>
<Input
id="password"
name="password"
type="password"
autoComplete="current-password"
required
placeholder="PW를 입력하세요"
value={userPw}
onChange={(e) => setUserPw(e.currentTarget.value)}
onKeyDown={handlePwKeyDown}
ref={passwordInputRef}
/>
</div>
{loginType === "call"?
<div className="space-y-2">
<label className="text-sm font-medium">자리번호 (면접원)</label>
<Input
id="seatNum"
name="seatNum"
type="text"
placeholder="자리번호를 입력하세요"
value={seatNum}
onChange={(e) => setSeatNum(e.currentTarget.value)}
onKeyDown={handleSeatNumberKeyDown}
ref={seatNumberInputRef}
/>
</div>
:
null
}
{error && (
<p className="text-sm text-red-500">
{error}
</p>
)}
<Button
type="submit"
className="w-full mt-6 h-11"
onClick={(e) => {
e.preventDefault();
tryLogin();
}}
>
로그인
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
export default LoginPage;

View File

@@ -0,0 +1,42 @@
'use client'
import { useRouter } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import {useSelectedProject} from "@/hooks/useSelectedProject";
import {useStorage} from "@/hooks/useStorage";
import {StorageKeys} from "@/store/storage/storage-keys";
import {useEffect} from "react";
import {nextApi} from "@/lib/http-client";
import {useLoading} from "@/hooks/useLoading";
const LogoutPage = () => {
const { get: getLoginTypeStorage, set: setLoginTypeStorage } = useStorage(StorageKeys.LoginType);
const { logout } = useAuth();
const { clearSelectedProject } = useSelectedProject();
const { withLoadingAsync } = useLoading();
const router = useRouter();
useEffect(() => {
const runLogout = async () => {
clearSelectedProject();
logout();
try {
await nextApi.del("/api/logout", {});
} catch (e) {
console.error("로그아웃 API 호출 실패", e);
}
const loginType = getLoginTypeStorage();
const loginUrl = loginType === "call" ? "/login?type=call" : "/login";
router.replace(loginUrl);
};
withLoadingAsync(runLogout);
}, []);
// Nothing to render while redirecting
return null;
}
export default LogoutPage;

View File

@@ -1,24 +1,37 @@
import { NextRequest, NextResponse } from "next/server";
import { intranetApi } from "@/api/auth";
import {LoginRequest} from "@/types/auth";
import {LoginRequest, LoginUser} from "@/types/auth";
import {serverEnv} from "@/lib/env.server";
import {createContactApi} from "@/lib/server-api";
//실제 Backend
type LoginResponse = {
accessToken: string;
user: LoginUser;
};
export const POST = async (req: NextRequest) => {
try {
const body = (await req.json()) as LoginRequest;
const result = await intranetApi.login({
userId: body.userId,
userPw: body.userPw,
});
const contactApi = await createContactApi();
return NextResponse.json(result, { status: 200 });
const body = (await req.json()) as LoginRequest;
const result = await contactApi.post<LoginResponse>("/auth/login", body);
const res = NextResponse.json(result.user, { status: 200 });
res.cookies.set("access_token", result.accessToken, {
httpOnly: true,
secure: serverEnv.ENV === "prod",
sameSite: "lax",
path: "/",
maxAge: 24 * 60 * 60, // 24시간
});
return res;
} catch (error : unknown) {
console.error("login error:", error);
const err = error as { status?: number; data?: unknown };
const status = typeof err.status === "number" ? err.status : 500;
const payload = err.data !== undefined ? err.data : { message: "서버에서 오류 응답을 받았습니다." };
const err = error as { status?: number; data?: unknown };
const status = typeof err.status === "number" ? err.status : 500;
const payload = err.data !== undefined ? err.data : { message: "서버에서 오류 응답을 받았습니다." };
return NextResponse.json(payload, { status });
return NextResponse.json(payload, { status });
}
}

View File

@@ -0,0 +1,16 @@
import { NextResponse } from "next/server";
import {serverEnv} from "@/lib/env.server";
export async function DELETE() {
const res = NextResponse.json({ ok: true });
res.cookies.set("access_token", "", {
httpOnly: true,
secure: serverEnv.ENV === "prod",
sameSite: "lax",
path: "/",
maxAge: 0,
});
return res;
}

View File

@@ -0,0 +1,5 @@
import {NextRequest} from "next/server";
export const GET = async (req: NextRequest) => {
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -1,5 +1,6 @@
import type { Metadata } from "next";
import {Geist, Geist_Mono} from "next/font/google";
import { AppProvider } from "@/components/providers/AppProvider";
import "./globals.css";
const geistSans = Geist({
@@ -13,17 +14,17 @@ const geistMono = Geist_Mono({
});
export const metadata: Metadata = {
title: "Contact",
description: "Contact system",
title: "KRI Contact",
description: "KRI Contact 시스템",
};
const RootLayout = ({ children }: { children: React.ReactNode}) => {
return (
<html lang="ko">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<AppProvider>{children}</AppProvider>
</body>
</html>
);

View File

@@ -1,129 +0,0 @@
"use client";
import {Button} from "@/components/ui/button";
import {Card, CardContent, CardHeader} from "@/components/ui/card";
import {Input} from "@/components/ui/input";
import {MouseEventHandler, useState} from "react";
import {HttpError, nextApi} from "@/lib/http-client";
import {useRouter} from "next/navigation";
import {LoginResponse} from "@/types/auth";
const LoginPage = () => {
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [userId, setUserId] = useState<string>("");
const [userPw, setUserPw] = useState<string>("");
const [seatNum, setSeatNum] = useState<string>("");
const tryLogin = () => {
setError(null);
setIsLoading(true);
const data = nextApi.post<LoginResponse>("/api/login", {
userId,
userPw,
}).then((data) => {
console.log(data)
// 🔐 토큰 저장 예시 (실제에선 cookie, secure storage 등으로 변경 가능)
/*if (typeof window !== "undefined") {
localStorage.setItem("accessToken", data.accessToken);
}*/
// 로그인 성공 후 메인으로 이동 (원하는 경로로 변경)
//router.push("/");
}).catch((err) => {
if (err instanceof HttpError) {
if (err.status === 401) {
setError("이메일 또는 비밀번호를 다시 확인해주세요.");
} else {
setError(`로그인에 실패했습니다. (status: ${err.status})`);
}
} else {
console.error(err);
setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
}
})
.finally(() => {
setIsLoading(false);
});
}
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 p-4">
<Card className="w-full max-w-md shadow-xl">
<CardHeader className="space-y-4 pb-8">
<div className="flex justify-center">
<div className="w-32 h-32 bg-blue-600 rounded-2xl flex items-center justify-center">
<span className="text-white text-4xl font-bold">LOGO</span>
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">ID</label>
<Input
id="id"
name="id"
type="text"
required
placeholder="아이디를 입력하세요"
value={userId}
onChange={(e) => setUserId(e.currentTarget.value)}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Password</label>
<Input
id="password"
name="password"
type="password"
autoComplete="current-password"
required
placeholder="••••••••"
value={userPw}
onChange={(e) => setUserPw(e.currentTarget.value)}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">자리번호 (면접원)</label>
<Input
id="seatNum"
name="seatNum"
type="text"
placeholder="자리번호를 입력하세요"
value={seatNum}
onChange={(e) => setSeatNum(e.currentTarget.value)}
/>
</div>
{error && (
<p className="text-sm text-red-500">
{error}
</p>
)}
<Button
type="submit"
className="w-full mt-6 h-11"
disabled={isLoading}
onClick={(e) => {
e.preventDefault();
tryLogin();
}}
>
{isLoading ? "로그인 중..." : "로그인"}
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
export default LoginPage;

View File

@@ -1,7 +0,0 @@
import { redirect } from "next/navigation";
const LogoutPage = () => {
redirect("/login");
}
export default LogoutPage;

View File

@@ -0,0 +1,17 @@
"use client";
import { useAtomValue } from "jotai";
import { loadingAtom } from "@/store/jotai/loading";
export function LoadingOverlay() {
const isLoading = useAtomValue(loadingAtom);
if (!isLoading) return null;
return (
<div className="fixed inset-0 z-[9999] bg-black/70 flex items-center justify-center">
{/* 심플 로딩 인디케이터 */}
<div className="h-12 w-12 rounded-full border-4 border-gray-400 border-t-white animate-spin" />
</div>
);
}

View File

@@ -0,0 +1,120 @@
"use client";
import { Button } from "@/components/ui/button";
import { Menu, X, ZoomIn, ZoomOut, LogOut } from "lucide-react";
import Image from "next/image";
import { topMenus } from "@/config/menu.data";
interface HeaderProps {
isMain: boolean;
menuOpen: boolean;
activeTopId: string;
fontSize: number;
handleIsProjectMenu: (isProjectMenu: boolean) => void;
onToggleMenu: () => void;
onNavigate: (path: string) => void;
decreaseFontSize: () => void;
increaseFontSize: () => void;
}
export const Header = ({
isMain,
menuOpen,
activeTopId,
fontSize,
handleIsProjectMenu,
onToggleMenu,
onNavigate,
decreaseFontSize,
increaseFontSize,
}: HeaderProps) => {
return (
<header className="bg-white border-b border-gray-200 sticky top-0 z-40">
<div className="flex items-center justify-between px-4 h-16">
<div className="flex items-center gap-4">
{/* 햄버거 메뉴 */}
<div className="w-5">
{isMain? null :
<Button
variant="ghost"
size="icon"
className="cursor-pointer"
onClick={() => onToggleMenu()}
>
{menuOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
</Button>
}
</div>
{/* 로고 */}
<div
className="flex items-center gap-2 cursor-pointer"
onClick={() => onNavigate("/")}
>
<div className="w-20 h-10 flex items-center justify-center">
<Image
src="/kri_logo.png"
alt="KRI 로고"
width={120}
height={40}
className="object-contain"
priority
/>
</div>
</div>
{/* 상단 메뉴 */}
<nav className="flex items-center gap-1 ml-25">
{topMenus.map((m) => (
<Button
key={m.id}
variant={activeTopId === m.id ? "default" : "ghost"}
className="cursor-pointer"
onClick={() => {
handleIsProjectMenu(m.id === "project");
onNavigate(m.path);
}}
>
{m.label}
</Button>
))}
</nav>
</div>
{/* 우측 컨트롤 */}
<div className="flex items-center gap-4">
<div className="flex items-center gap-1 border-r pr-4">
<Button
variant="ghost"
size="icon"
onClick={() => decreaseFontSize()}
title="폰트 작게"
>
<ZoomOut className="w-4 h-4" />
</Button>
<span className="text-xs text-gray-500 min-w-[3rem] text-center">
{fontSize}px
</span>
<Button
variant="ghost"
size="icon"
onClick={() => increaseFontSize()}
title="폰트 크게"
>
<ZoomIn className="w-4 h-4" />
</Button>
</div>
<span className="text-sm text-gray-600 hidden sm:inline">admin</span>
<Button
variant="ghost"
size="sm"
className="gap-2"
onClick={() => onNavigate("/logout")}
>
<LogOut className="w-4 h-4" />
<span className="hidden sm:inline">로그아웃</span>
</Button>
</div>
</div>
</header>
);
};

View File

@@ -0,0 +1,127 @@
"use client";
import {useState, useEffect, ReactNode} from "react";
import { usePathname, useRouter } from "next/navigation";
import { Header } from "@/components/layout/Header";
import { Sidebar } from "@/components/layout/Sidebar";
import {useFontSize} from "@/hooks/useFontSize";
import {projectSideMenus, manageSideMenus, topMenus} from "@/config/menu.data";
import commonConst from "@/config/commonConst";
type MainLayoutProps = {
children: ReactNode;
initialFontSize: number; // 🔥 추가
};
const MainLayout = ({ children, initialFontSize }: MainLayoutProps) => {
const router = useRouter();
const pathname = usePathname();
const [isProjectMenu, setIsProjectMenu] = useState(false);
const [menuOpen, setMenuOpen] = useState(true);
const [fontSize, setFontSize] = useFontSize(initialFontSize, { hydrateFromCookie: false });
const isMain = pathname === "/";
const activeTop = topMenus.find((m) => m.match?.(pathname)) ?? topMenus[0];
const sideMenus = pathname.startsWith("/manage") ? manageSideMenus : projectSideMenus;
// 2단 메뉴 open 상태
const [openMenus, setOpenMenus] = useState<Record<string, boolean>>(() => {
const initial: Record<string, boolean> = {};
sideMenus.forEach((item) => {
if (
item.children &&
item.children.some(
(child) =>
pathname === child.path || pathname.startsWith(child.path + "/")
)
) {
initial[item.id] = true;
}
});
return initial;
});
const handleIsProjectMenu = (isProject: boolean) => {
setIsProjectMenu(isProject);
}
const movePage = (path: string) => {
router.push(path);
};
const toggleSideMenu = (id: string) => {
setOpenMenus((prev) => ({ ...prev, [id]: !prev[id] }));
};
const decreaseFontSize = () =>{
setFontSize(Math.max(commonConst.fontSizeMin, fontSize - 2));
}
const increaseFontSize = () =>{
setFontSize(Math.min(commonConst.fontSizeMax, fontSize + 2));
}
// CSS 변수 동기화
useEffect(() => {
if (typeof document === "undefined") return;
document.documentElement.style.setProperty(
"--content-font-size",
`${fontSize}px`,
);
}, [fontSize]);
return (
<div className="min-h-screen bg-gray-50">
{/* 헤더 - 고정 폰트 크기 */}
<Header
isMain={isMain}
menuOpen={menuOpen}
activeTopId={activeTop.id}
fontSize={fontSize}
handleIsProjectMenu={handleIsProjectMenu}
onToggleMenu={() => setMenuOpen((prev) => !prev)}
onNavigate={movePage}
decreaseFontSize={decreaseFontSize}
increaseFontSize={increaseFontSize}
/>
{/* 본문 */}
<div className="flex">
{/* 사이드바 - 고정 폰트 크기 */}
{!isMain && (
<Sidebar
isProjectMenu={isProjectMenu}
sideMenus={sideMenus}
isOpen={menuOpen}
pathname={pathname}
openMenus={openMenus}
onToggleMenu={toggleSideMenu}
onNavigate={movePage}
/>
)}
{/* 메인 콘텐츠만 가변 폰트 크기 적용 */}
<main
className="flex-1"
// 전역 CSS 변수(--content-font-size)를 실제 렌더에 적용
// SSR 단계에서의 초기 폰트 값을 FOUC 없이 유지하기 위해 fallback을 함께 지정
style={{ fontSize: `var(--content-font-size, ${initialFontSize}px)` }}
>
{children}
</main>
</div>
{/* 모바일 오버레이 */}
{!isMain && menuOpen && (
<div
className="fixed inset-0 z-20 lg:hidden"
onClick={() => setMenuOpen(false)}
/>
)}
</div>
);
};
export default MainLayout;

View File

@@ -0,0 +1,130 @@
"use client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ChevronDown } from "lucide-react";
import { SideMenuItem } from "@/config/menu.types";
interface SidebarProps {
isProjectMenu: boolean;
sideMenus: SideMenuItem[];
isOpen: boolean;
pathname: string;
openMenus: Record<string, boolean>;
onToggleMenu: (id: string) => void;
onNavigate: (path: string) => void;
}
export const Sidebar = ({
isProjectMenu,
sideMenus,
isOpen,
pathname,
openMenus,
onToggleMenu,
onNavigate,
}: SidebarProps) => {
const isSideActive = (item: SideMenuItem, current: string) => {
if (item.path) {
return current === item.path || current.startsWith(item.path + "/");
}
if (item.children) {
return item.children.some(
(c) => current === c.path || current.startsWith(c.path + "/")
);
}
return false;
};
return (
<aside
className={`
fixed lg:static top-16 lg:top-0 left-0
h-[calc(100vh-4rem)] bg-white border-r border-gray-200
transition-all duration-300 z-30 overflow-y-auto
lg:translate-x-0
${
isOpen
? "w-64 translate-x-0"
: "w-64 -translate-x-full lg:w-0 lg:border-r-0"
}
`}
>
<div className="p-4 space-y-4 overflow-y-auto h-full">
{isProjectMenu?
<div className="space-y-2">
<Input
type="text"
placeholder="프로젝트 검색..."
className="w-full"
/>
</div>
: null
}
{/* 좌측 메뉴 */}
<nav className="space-y-1">
{sideMenus.map((item) => {
const hasChildren = !!item.children?.length;
const opened = openMenus[item.id] ?? false;
const active = isSideActive(item, pathname);
if (!hasChildren && item.path) {
return (
<Button
key={item.id}
variant={active ? "secondary" : "ghost"}
className="w-full justify-start"
onClick={() => onNavigate(item.path!)}
>
<item.icon className="w-4 h-4" />
<span className="ml-2">{item.label}</span>
</Button>
);
}
return (
<div key={item.id} className="space-y-1">
<Button
variant={active ? "secondary" : "ghost"}
className="w-full justify-between"
onClick={() => onToggleMenu(item.id)}
>
<span className="flex items-center">
<item.icon className="w-4 h-4" />
<span className="ml-2">{item.label}</span>
</span>
<ChevronDown
className={`w-4 h-4 transition-transform ${
opened ? "rotate-180" : ""
}`}
/>
</Button>
{opened && item.children && (
<div className="ml-6 space-y-1">
{item.children.map((child) => {
const childActive =
pathname === child.path ||
pathname.startsWith(child.path + "/");
return (
<Button
key={child.id}
variant={childActive ? "secondary" : "ghost"}
className="w-full justify-start"
onClick={() => onNavigate(child.path)}
>
<span className="ml-1">{child.label}</span>
</Button>
);
})}
</div>
)}
</div>
);
})}
</nav>
</div>
</aside>
);
};

View File

@@ -0,0 +1,13 @@
"use client";
import { Provider as JotaiProvider } from "jotai";
import { LoadingOverlay } from "@/components/common/LoadingOverlay";
export function AppProvider({ children }: { children: React.ReactNode }) {
return (
<JotaiProvider>
<LoadingOverlay />
{children}
</JotaiProvider>
);
}

View File

@@ -0,0 +1,7 @@
const commonConst = {
fontSizeDefault: 14,
fontSizeMin: 12,
fontSizeMax: 24,
} as const;
export default commonConst;

80
src/config/menu.data.ts Normal file
View File

@@ -0,0 +1,80 @@
import {
BarChart3,
FolderKanban,
List,
MessageSquare,
Users,
UserRoundPenIcon,
} from "lucide-react";
import type { TopMenuItem, SideMenuItem } from "./menu.types";
export const topMenus: TopMenuItem[] = [
{
id: "project",
label: "프로젝트",
path: "/",
match: (pathname) =>
pathname === "/" || !pathname.startsWith("/manage"),
},
{
id: "manage",
label: "관리",
path: "/manage/user",
match: (pathname) => pathname.startsWith("/manage"),
},
];
export const projectSideMenus: SideMenuItem[] = [
{
id: "project-info",
label: "프로젝트 정보",
icon: FolderKanban,
path: "/project/info",
},
{
id: "assign",
label: "면접원 배정",
icon: Users,
children: [
{ id: "assign-project", label: "프로젝트 배정", path: "/assign/project" },
{ id: "assign-list", label: "리스트 배정", path: "/assign/list" },
],
},
{
id: "list",
label: "리스트",
icon: List,
children: [
{ id: "list-main", label: "리스트 관리", path: "/list/manage" },
{ id: "list-contact", label: "컨택 진행", path: "/list/contact" },
],
},
{
id: "message",
label: "문자/메일 템플릿",
icon: MessageSquare,
children: [
{ id: "message-template-text", label: "문자 템플릿 관리", path: "/message/template/text" },
{ id: "message-template-email", label: "이메일 템플릿 관리", path: "/message/template/email" },
],
},
{
id: "progress",
label: "현황",
icon: BarChart3,
children: [
{ id: "progress-fieldwork", label: "실사 현황", path: "/progress/fieldwork" },
{ id: "progress-contact", label: "컨택 현황", path: "/progress/contact" },
{ id: "progress-message", label: "발송 현황", path: "/progress/message" },
],
},
];
export const manageSideMenus: SideMenuItem[] = [
{
id: "user-manage",
label: "사용자 관리",
icon: UserRoundPenIcon,
path: "/manage/user",
}
];

25
src/config/menu.types.ts Normal file
View File

@@ -0,0 +1,25 @@
import type { LucideIcon } from "lucide-react";
export type TopMenuItem = {
id: string;
label: string;
path: string;
/** 현재 경로가 이 탭에 해당하는지 판별하는 함수 */
match?: (pathname: string) => boolean;
};
export type SideSubMenuItem = {
id: string;
label: string;
path: string;
};
export type SideMenuItem = {
id: string;
label: string;
icon: LucideIcon;
/** 단일 메뉴일 경우 path 사용 */
path?: string;
/** children이 있으면 2단 메뉴(접었다 펴는 타입) */
children?: SideSubMenuItem[];
};

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;
};

View File

@@ -1,8 +1,17 @@
export const clientEnv = {
API_BASE: process.env.NEXT_PUBLIC_API_BASE as string,
// 다른 클라이언트 전용 env들 추가 가능
ENV: process.env.NEXT_PUBLIC_ENV as string,
API_BASE: process.env.NEXT_PUBLIC_API_BASE as string,
STORE_KEY: process.env.NEXT_PUBLIC_STORE_KEY as string,
// 다른 클라이언트 전용 env들 추가 가능
};
if (!clientEnv.ENV) {
throw new Error("Missing env: NEXT_PUBLIC_ENV");
}
if (!clientEnv.API_BASE) {
throw new Error("Missing env: NEXT_PUBLIC_API_BASE");
}
if (!clientEnv.STORE_KEY) {
throw new Error("Missing env: NEXT_PUBLIC_STORE_KEY");
}

View File

@@ -1,10 +1,11 @@
const required = (name: string) => {
const v = process.env[name];
if (!v) throw new Error(`Missing env: ${name}`);
return v;
const v = process.env[name];
if (!v) throw new Error(`Missing env: ${name}`);
return v;
};
export const serverEnv = {
API_INTRANET: required("API_INTRANET"),
ENV: required("ENV"),
API_CONTACT_SERVER: required("API_CONTACT_SERVER"),
// 다른 서버 전용 env들 추가 가능
};

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 &&

196
src/lib/security.ts Normal file
View File

@@ -0,0 +1,196 @@
import CryptoJS from "crypto-js";
const KEY = CryptoJS.enc.Utf8.parse("kr!-c0nTacT-fr0nT-CrypT0-Key-STR");
const IV = CryptoJS.enc.Utf8.parse("kr!-c0nTacT-IVST");
export type WordArray = CryptoJS.lib.WordArray;
export class Security {
public static encryptBase64UrlObject(input: unknown): string {
const data = JSON.stringify(input);
return this.encryptBase64Url(data);
}
public static decryptBase64UrlObject(input: string): unknown {
const data = this.decryptBase64Url(input);
return JSON.parse(data);
}
public static encryptBase64Object(input: unknown): string {
const data = JSON.stringify(input);
return this.encryptBase64(data);
}
public static decryptBase64Object(input: string): unknown {
const data = this.decryptBase64(input);
return JSON.parse(data);
}
public static encryptBase64Url(input: string): string {
const data = this.decodeUtf8(input);
const params = this.encrypt(data);
return this.encodeBase64Url(params);
}
public static decryptBase64Url(input: string): string {
const data = this.decodeBase64Url(input);
const decryptedData = this.decrypt(data);
return this.encodeUtf8(decryptedData);
}
public static encryptBase64(input: string): string {
const data = this.decodeUtf8(input);
const params = this.encrypt(data);
return this.encodeBase64(params);
}
public static decryptBase64(input: string): string {
try {
const data = this.decodeBase64(input);
const decryptedData = this.decrypt(data);
return this.encodeUtf8(decryptedData);
} catch (error) {
console.error("SecurityFunction.decryptBase64 오류:", {
input: input?.substring(0, 50) + "...", // 처음 50자만 로그
error: error instanceof Error ? error.message : String(error),
});
throw error;
}
}
public static encrypt(input: WordArray): WordArray {
const params = CryptoJS.AES.encrypt(input, KEY, {
iv: IV,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC,
});
return params.ciphertext;
}
public static decrypt(input: WordArray): WordArray {
const params = CryptoJS.lib.CipherParams.create({
ciphertext: input,
});
return CryptoJS.AES.decrypt(params, KEY, {
iv: IV,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC,
});
}
public static convertUint8ArrayToWordArray(input: Uint8Array): WordArray {
const words: number[] = [];
let i = 0;
while (i < input.length) {
const word =
(input[i++] << 24) |
(input[i++] << 16) |
(input[i++] << 8) |
input[i++];
words.push(word);
}
return CryptoJS.lib.WordArray.create(words, words.length * 4);
}
public static convertWordArrayToUint8Array(input: WordArray): Uint8Array {
const array = new Uint8Array(input.words.length << 2);
for (let i = 0, j = 0; i < input.words.length; i++) {
const word = input.words[i];
array[j++] = word >> 24;
array[j++] = (word >> 16) & 0xff;
array[j++] = (word >> 8) & 0xff;
array[j++] = word & 0xff;
}
return array;
}
public static computeHmacSha256Hex(input: WordArray, key: WordArray): string {
return this.encodeHex(this.computeHmacSha256(input, key));
}
public static computeHmacSha256(input: WordArray, key: WordArray): WordArray {
return CryptoJS.HmacSHA256(input, key);
}
public static computeSha256Hex(input: WordArray): string {
return this.encodeHex(this.computeSha256(input));
}
public static computeSha256(input: WordArray): WordArray {
return CryptoJS.SHA256(input);
}
private static convertToSpecialChars(base64: string): string {
return Array.from(base64)
.map((char) => char.charCodeAt(0).toString(2).padStart(16, "0"))
.map((binary) => binary.replace(/0/g, "\u200b").replace(/1/g, "\u200c"))
.join("ㅤ");
}
private static convertFromSpecialChars(input: string): string {
return input
.split("ㅤ")
.map((bin) => bin.replace(/\u200b/g, "0").replace(/\u200c/g, "1"))
.map((binary) => String.fromCharCode(parseInt(binary, 2)))
.join("");
}
public static encodeBase64UrlUtf8(input: string): string {
return this.encodeBase64Url(this.decodeUtf8(input));
}
public static decodeBase64UrlUtf8(input: string): string {
return this.encodeUtf8(this.decodeBase64Url(input));
}
public static encodeBase64Url(input: WordArray): string {
const base64url = CryptoJS.enc.Base64url.stringify(input);
return this.convertToSpecialChars(base64url);
}
public static decodeBase64Url(input: string): WordArray {
try {
const base64url = this.convertFromSpecialChars(input);
return CryptoJS.enc.Base64url.parse(base64url);
} catch {
return CryptoJS.enc.Base64url.parse(input);
}
}
public static encodeBase64Utf8(input: string): string {
return this.encodeBase64(this.decodeUtf8(input));
}
public static decodeBase64Utf8(input: string): string {
return this.encodeUtf8(this.decodeBase64(input));
}
public static encodeBase64(input: WordArray): string {
const base64 = CryptoJS.enc.Base64.stringify(input);
return this.convertToSpecialChars(base64);
}
public static decodeBase64(input: string): WordArray {
try {
const base64 = this.convertFromSpecialChars(input);
return CryptoJS.enc.Base64.parse(base64);
} catch {
return CryptoJS.enc.Base64.parse(input);
}
}
public static encodeHex(input: WordArray): string {
return CryptoJS.enc.Hex.stringify(input);
}
public static decodeHex(input: string): WordArray {
return CryptoJS.enc.Hex.parse(input);
}
public static encodeUtf8(input: WordArray): string {
return CryptoJS.enc.Utf8.stringify(input);
}
public static decodeUtf8(input: string): WordArray {
return CryptoJS.enc.Utf8.parse(input);
}
}

17
src/lib/server-api.ts Normal file
View File

@@ -0,0 +1,17 @@
import { cookies } from "next/headers";
import { createHttpClient } from "@/lib/http-client";
import { serverEnv } from "@/lib/env.server";
const createServerApi = async (rootUrl: string) => {
const cookieStore = await cookies();
const accessToken = cookieStore.get("access_token")?.value ?? null;
return createHttpClient(rootUrl, {
getToken: () => accessToken, // 이미 위에서 읽은 값만 참조
defaultTimeoutMs: 10_000,
});
};
export const createContactApi = () => {
return createServerApi(serverEnv.API_CONTACT_SERVER);
}

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];

View File

@@ -4,13 +4,8 @@ export type LoginRequest = {
};
export type LoginUser = {
id: string;
name: string;
email: string;
};
export type LoginResponse = {
accessToken: string;
refreshToken?: string;
user: LoginUser;
userId: string;
userName: string;
userTeam: string;
userRole: number;
};