("/auth/login", payload),
-};
\ No newline at end of file
diff --git a/src/app/(main)/layout.tsx b/src/app/(main)/layout.tsx
deleted file mode 100644
index 4d9def1..0000000
--- a/src/app/(main)/layout.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-const MainLayout = ({ children }: { children: React.ReactNode}) => {
- return (
-
- {/* 공통 헤더 */}
-
-
- {/* 메인 컨텐츠 영역 */}
-
- {/* 필요하면 사이드바 */}
- {/* */}
-
-
-
-
- );
-}
-
-export default MainLayout;
\ No newline at end of file
diff --git a/src/app/(main)/list/page.tsx b/src/app/(main)/list/page.tsx
deleted file mode 100644
index f698aec..0000000
--- a/src/app/(main)/list/page.tsx
+++ /dev/null
@@ -1,8 +0,0 @@
-const ListPage = () => {
- //const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
- //redirect(url);
-
- return (This is List Page
)
-}
-
-export default ListPage;
\ No newline at end of file
diff --git a/src/app/(main)/user/page.tsx b/src/app/(main)/user/page.tsx
deleted file mode 100644
index d8b794d..0000000
--- a/src/app/(main)/user/page.tsx
+++ /dev/null
@@ -1,8 +0,0 @@
-const UserPage = () => {
- //const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
- //redirect(url);
-
- return (This is User Page
)
-}
-
-export default UserPage;
\ No newline at end of file
diff --git a/src/app/(pages)/(main)/assign/list/page.tsx b/src/app/(pages)/(main)/assign/list/page.tsx
new file mode 100644
index 0000000..c8afa1c
--- /dev/null
+++ b/src/app/(pages)/(main)/assign/list/page.tsx
@@ -0,0 +1,8 @@
+const ListAssignPage = () => {
+ //const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
+ //redirect(url);
+
+ return (This is List Assign Page
)
+}
+
+export default ListAssignPage;
\ No newline at end of file
diff --git a/src/app/(pages)/(main)/assign/project/page.tsx b/src/app/(pages)/(main)/assign/project/page.tsx
new file mode 100644
index 0000000..b404abc
--- /dev/null
+++ b/src/app/(pages)/(main)/assign/project/page.tsx
@@ -0,0 +1,8 @@
+const ProjectAssignPage = () => {
+ //const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
+ //redirect(url);
+
+ return (This is Project Assign Page
)
+}
+
+export default ProjectAssignPage;
\ No newline at end of file
diff --git a/src/app/(pages)/(main)/layout.tsx b/src/app/(pages)/(main)/layout.tsx
new file mode 100644
index 0000000..3b66147
--- /dev/null
+++ b/src/app/(pages)/(main)/layout.tsx
@@ -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 (
+ <>
+
+ {children}
+
+ >
+ );
+}
\ No newline at end of file
diff --git a/src/app/(pages)/(main)/list/contact/page.tsx b/src/app/(pages)/(main)/list/contact/page.tsx
new file mode 100644
index 0000000..440d840
--- /dev/null
+++ b/src/app/(pages)/(main)/list/contact/page.tsx
@@ -0,0 +1,8 @@
+const ListContactPage = () => {
+ //const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
+ //redirect(url);
+
+ return (This is List Contact Page
)
+}
+
+export default ListContactPage;
\ No newline at end of file
diff --git a/src/app/(pages)/(main)/list/manage/page.tsx b/src/app/(pages)/(main)/list/manage/page.tsx
new file mode 100644
index 0000000..b46d16e
--- /dev/null
+++ b/src/app/(pages)/(main)/list/manage/page.tsx
@@ -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 (
+
+ This is Manage List Page {fontSize}
+
+ );
+};
+
+export default ListManagePage;
\ No newline at end of file
diff --git a/src/app/(pages)/(main)/manage/user/page.tsx b/src/app/(pages)/(main)/manage/user/page.tsx
new file mode 100644
index 0000000..89f71a9
--- /dev/null
+++ b/src/app/(pages)/(main)/manage/user/page.tsx
@@ -0,0 +1,8 @@
+const UserManagePage = () => {
+ //const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
+ //redirect(url);
+
+ return (This is User Manage Page
)
+}
+
+export default UserManagePage;
\ No newline at end of file
diff --git a/src/app/(pages)/(main)/message/template/email/page.tsx b/src/app/(pages)/(main)/message/template/email/page.tsx
new file mode 100644
index 0000000..70bacdc
--- /dev/null
+++ b/src/app/(pages)/(main)/message/template/email/page.tsx
@@ -0,0 +1,9 @@
+const EmailTemplatePage = () => {
+ //파라미터 받기
+ //const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
+ //redirect(url);
+
+ return (This is Email Template Page
)
+}
+
+export default EmailTemplatePage;
\ No newline at end of file
diff --git a/src/app/(pages)/(main)/message/template/text/page.tsx b/src/app/(pages)/(main)/message/template/text/page.tsx
new file mode 100644
index 0000000..61b3c94
--- /dev/null
+++ b/src/app/(pages)/(main)/message/template/text/page.tsx
@@ -0,0 +1,9 @@
+const TextTemplatePage = () => {
+ //파라미터 받기
+ //const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
+ //redirect(url);
+
+ return (This is Text Message Template Page
)
+}
+
+export default TextTemplatePage;
\ No newline at end of file
diff --git a/src/app/(main)/page.tsx b/src/app/(pages)/(main)/page.tsx
similarity index 100%
rename from src/app/(main)/page.tsx
rename to src/app/(pages)/(main)/page.tsx
diff --git a/src/app/(pages)/(main)/progress/contact/page.tsx b/src/app/(pages)/(main)/progress/contact/page.tsx
new file mode 100644
index 0000000..28c434d
--- /dev/null
+++ b/src/app/(pages)/(main)/progress/contact/page.tsx
@@ -0,0 +1,8 @@
+const ContactProgressPage = () => {
+ //const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
+ //redirect(url);
+
+ return (This is Contact Progress Page
)
+}
+
+export default ContactProgressPage;
\ No newline at end of file
diff --git a/src/app/(pages)/(main)/progress/fieldwork/page.tsx b/src/app/(pages)/(main)/progress/fieldwork/page.tsx
new file mode 100644
index 0000000..293ad58
--- /dev/null
+++ b/src/app/(pages)/(main)/progress/fieldwork/page.tsx
@@ -0,0 +1,8 @@
+const FieldworkProgressPage = () => {
+ //const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
+ //redirect(url);
+
+ return (This is Fieldwork Progress Page
)
+}
+
+export default FieldworkProgressPage;
\ No newline at end of file
diff --git a/src/app/(pages)/(main)/progress/message/page.tsx b/src/app/(pages)/(main)/progress/message/page.tsx
new file mode 100644
index 0000000..2896196
--- /dev/null
+++ b/src/app/(pages)/(main)/progress/message/page.tsx
@@ -0,0 +1,8 @@
+const MessageProgressPage = () => {
+ //const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
+ //redirect(url);
+
+ return (This is Message Progress Page
)
+}
+
+export default MessageProgressPage;
\ No newline at end of file
diff --git a/src/app/(pages)/(main)/project/info/page.tsx b/src/app/(pages)/(main)/project/info/page.tsx
new file mode 100644
index 0000000..83eb3bd
--- /dev/null
+++ b/src/app/(pages)/(main)/project/info/page.tsx
@@ -0,0 +1,8 @@
+const ProjectInfoPage = () => {
+ //const url = buildUrlWithParams("/login", searchParams, { ref: "root" });
+ //redirect(url);
+
+ return (This is Project Info Page
)
+}
+
+export default ProjectInfoPage;
\ No newline at end of file
diff --git a/src/app/(pages)/login/page.tsx b/src/app/(pages)/login/page.tsx
new file mode 100644
index 0000000..addf683
--- /dev/null
+++ b/src/app/(pages)/login/page.tsx
@@ -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(null);
+
+ const [userId, setUserId] = useState("");
+ const [userPw, setUserPw] = useState("");
+ const [seatNum, setSeatNum] = useState(getSeatNumberStorage());
+ const [loginType, setLoginType] = useState(getLoginTypeStorage());
+
+ const passwordInputRef = useRef(null);
+ const seatNumberInputRef = useRef(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(
+ "/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 = (e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ passwordInputRef.current?.focus();
+ }
+ };
+
+ const handlePwKeyDown: React.KeyboardEventHandler = (e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const seatNumberInput = seatNumberInputRef.current;
+ if(loginType === "call" && seatNumberInput?.value === ""){
+ seatNumberInput.focus();
+ }
+ else{
+ tryLogin();
+ }
+ }
+ };
+
+ const handleSeatNumberKeyDown: React.KeyboardEventHandler = (e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ tryLogin();
+ }
+ };
+
+ return (
+
+
+
+
+
+
+
+
+
+ setUserId(e.currentTarget.value)}
+ onKeyDown={handleIdKeyDown}
+ />
+
+
+
+
+ setUserPw(e.currentTarget.value)}
+ onKeyDown={handlePwKeyDown}
+ ref={passwordInputRef}
+ />
+
+
+ {loginType === "call"?
+
+
+ setSeatNum(e.currentTarget.value)}
+ onKeyDown={handleSeatNumberKeyDown}
+ ref={seatNumberInputRef}
+ />
+
+ :
+ null
+ }
+
+ {error && (
+
+ {error}
+
+ )}
+
+
+
+
+
+
+ );
+}
+
+export default LoginPage;
\ No newline at end of file
diff --git a/src/app/(pages)/logout/page.tsx b/src/app/(pages)/logout/page.tsx
new file mode 100644
index 0000000..69211ba
--- /dev/null
+++ b/src/app/(pages)/logout/page.tsx
@@ -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;
\ No newline at end of file
diff --git a/src/app/api/login/route.ts b/src/app/api/login/route.ts
index 2d01e07..81fee17 100644
--- a/src/app/api/login/route.ts
+++ b/src/app/api/login/route.ts
@@ -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("/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 });
}
}
diff --git a/src/app/api/logout/route.ts b/src/app/api/logout/route.ts
new file mode 100644
index 0000000..eade96c
--- /dev/null
+++ b/src/app/api/logout/route.ts
@@ -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;
+}
\ No newline at end of file
diff --git a/src/app/api/project/route.ts b/src/app/api/project/route.ts
new file mode 100644
index 0000000..d1a5974
--- /dev/null
+++ b/src/app/api/project/route.ts
@@ -0,0 +1,5 @@
+import {NextRequest} from "next/server";
+
+export const GET = async (req: NextRequest) => {
+
+}
\ No newline at end of file
diff --git a/src/app/favicon.ico b/src/app/favicon.ico
index 718d6fe..5172b57 100644
Binary files a/src/app/favicon.ico and b/src/app/favicon.ico differ
diff --git a/src/app/layout.tsx b/src/app/layout.tsx
index 11179e9..0726f0e 100644
--- a/src/app/layout.tsx
+++ b/src/app/layout.tsx
@@ -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 (
-
- {children}
+
+ {children}
);
diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx
deleted file mode 100644
index cfbb414..0000000
--- a/src/app/login/page.tsx
+++ /dev/null
@@ -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(null);
-
- const [userId, setUserId] = useState("");
- const [userPw, setUserPw] = useState("");
- const [seatNum, setSeatNum] = useState("");
-
- const tryLogin = () => {
- setError(null);
- setIsLoading(true);
-
- const data = nextApi.post("/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 (
-
-
-
-
-
-
-
-
-
- setUserId(e.currentTarget.value)}
- />
-
-
-
-
- setUserPw(e.currentTarget.value)}
- />
-
-
-
-
- setSeatNum(e.currentTarget.value)}
- />
-
-
- {error && (
-
- {error}
-
- )}
-
-
-
-
-
-
- );
-}
-
-export default LoginPage;
\ No newline at end of file
diff --git a/src/app/logout/page.tsx b/src/app/logout/page.tsx
deleted file mode 100644
index c841d5a..0000000
--- a/src/app/logout/page.tsx
+++ /dev/null
@@ -1,7 +0,0 @@
-import { redirect } from "next/navigation";
-
-const LogoutPage = () => {
- redirect("/login");
-}
-
-export default LogoutPage;
\ No newline at end of file
diff --git a/src/components/common/LoadingOverlay.tsx b/src/components/common/LoadingOverlay.tsx
new file mode 100644
index 0000000..84bcc34
--- /dev/null
+++ b/src/components/common/LoadingOverlay.tsx
@@ -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 (
+
+ {/* 심플 로딩 인디케이터 */}
+
+
+ );
+}
\ No newline at end of file
diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsx
new file mode 100644
index 0000000..81a15ed
--- /dev/null
+++ b/src/components/layout/Header.tsx
@@ -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 (
+
+
+
+ {/* 햄버거 메뉴 */}
+
+ {isMain? null :
+
+ }
+
+ {/* 로고 */}
+
onNavigate("/")}
+ >
+
+
+
+
+
+ {/* 상단 메뉴 */}
+
+
+
+ {/* 우측 컨트롤 */}
+
+
+
+
+ {fontSize}px
+
+
+
+
admin
+
+
+
+
+ );
+};
\ No newline at end of file
diff --git a/src/components/layout/MainLayout.tsx b/src/components/layout/MainLayout.tsx
new file mode 100644
index 0000000..49aacdc
--- /dev/null
+++ b/src/components/layout/MainLayout.tsx
@@ -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>(() => {
+ const initial: Record = {};
+
+ 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 (
+
+ {/* 헤더 - 고정 폰트 크기 */}
+
setMenuOpen((prev) => !prev)}
+ onNavigate={movePage}
+ decreaseFontSize={decreaseFontSize}
+ increaseFontSize={increaseFontSize}
+ />
+
+ {/* 본문 */}
+
+ {/* 사이드바 - 고정 폰트 크기 */}
+ {!isMain && (
+
+ )}
+
+ {/* 메인 콘텐츠만 가변 폰트 크기 적용 */}
+
+ {children}
+
+
+
+ {/* 모바일 오버레이 */}
+ {!isMain && menuOpen && (
+ setMenuOpen(false)}
+ />
+ )}
+
+ );
+};
+
+export default MainLayout;
\ No newline at end of file
diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsx
new file mode 100644
index 0000000..396d633
--- /dev/null
+++ b/src/components/layout/Sidebar.tsx
@@ -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;
+ 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 (
+
+ );
+};
\ No newline at end of file
diff --git a/src/components/providers/AppProvider.tsx b/src/components/providers/AppProvider.tsx
new file mode 100644
index 0000000..8ea7a31
--- /dev/null
+++ b/src/components/providers/AppProvider.tsx
@@ -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 (
+
+
+ {children}
+
+ );
+}
\ No newline at end of file
diff --git a/src/config/commonConst.ts b/src/config/commonConst.ts
new file mode 100644
index 0000000..7a80de8
--- /dev/null
+++ b/src/config/commonConst.ts
@@ -0,0 +1,7 @@
+const commonConst = {
+ fontSizeDefault: 14,
+ fontSizeMin: 12,
+ fontSizeMax: 24,
+} as const;
+
+export default commonConst;
\ No newline at end of file
diff --git a/src/config/menu.data.ts b/src/config/menu.data.ts
new file mode 100644
index 0000000..9d5897b
--- /dev/null
+++ b/src/config/menu.data.ts
@@ -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",
+ }
+];
\ No newline at end of file
diff --git a/src/config/menu.types.ts b/src/config/menu.types.ts
new file mode 100644
index 0000000..3d98f62
--- /dev/null
+++ b/src/config/menu.types.ts
@@ -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[];
+};
\ No newline at end of file
diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts
new file mode 100644
index 0000000..fd82658
--- /dev/null
+++ b/src/hooks/useAuth.ts
@@ -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,
+ };
+}
\ No newline at end of file
diff --git a/src/hooks/useFontSize.ts b/src/hooks/useFontSize.ts
new file mode 100644
index 0000000..e614e0d
--- /dev/null
+++ b/src/hooks/useFontSize.ts
@@ -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(() => {
+ // 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;
+}
\ No newline at end of file
diff --git a/src/hooks/useLoading.ts b/src/hooks/useLoading.ts
new file mode 100644
index 0000000..06703b7
--- /dev/null
+++ b/src/hooks/useLoading.ts
@@ -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 (fn: () => Promise): Promise => {
+ showLoading();
+ try {
+ return await fn();
+ } finally {
+ hideLoading();
+ }
+ },
+ [showLoading, hideLoading],
+ );
+
+ const withLoading = useCallback(
+ (fn: () => T): T => {
+ showLoading();
+ try {
+ return fn();
+ } finally {
+ hideLoading();
+ }
+ },
+ [showLoading, hideLoading],
+ );
+
+ return {
+ isLoading,
+ showLoading,
+ hideLoading,
+ withLoading,
+ withLoadingAsync,
+ } as const;
+}
\ No newline at end of file
diff --git a/src/hooks/useSelectedProject.ts b/src/hooks/useSelectedProject.ts
new file mode 100644
index 0000000..1b59141
--- /dev/null
+++ b/src/hooks/useSelectedProject.ts
@@ -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;
+}
\ No newline at end of file
diff --git a/src/hooks/useStorage.ts b/src/hooks/useStorage.ts
new file mode 100644
index 0000000..977f591
--- /dev/null
+++ b/src/hooks/useStorage.ts
@@ -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;
+};
\ No newline at end of file
diff --git a/src/lib/env.client.ts b/src/lib/env.client.ts
index d1dff90..6beac26 100644
--- a/src/lib/env.client.ts
+++ b/src/lib/env.client.ts
@@ -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");
}
\ No newline at end of file
diff --git a/src/lib/env.server.ts b/src/lib/env.server.ts
index 4c3aefb..0847b17 100644
--- a/src/lib/env.server.ts
+++ b/src/lib/env.server.ts
@@ -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들 추가 가능
};
\ No newline at end of file
diff --git a/src/lib/http-client.ts b/src/lib/http-client.ts
index 52fb1dc..a3a5720 100644
--- a/src/lib/http-client.ts
+++ b/src/lib/http-client.ts
@@ -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 (path: string, options: RequestOptions = {}): Promise => {
// 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 &&
diff --git a/src/lib/security.ts b/src/lib/security.ts
new file mode 100644
index 0000000..b602ae8
--- /dev/null
+++ b/src/lib/security.ts
@@ -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);
+ }
+}
diff --git a/src/lib/server-api.ts b/src/lib/server-api.ts
new file mode 100644
index 0000000..8a86125
--- /dev/null
+++ b/src/lib/server-api.ts
@@ -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);
+}
\ No newline at end of file
diff --git a/src/store/cookie/cookie-keys.ts b/src/store/cookie/cookie-keys.ts
new file mode 100644
index 0000000..cb505a1
--- /dev/null
+++ b/src/store/cookie/cookie-keys.ts
@@ -0,0 +1,11 @@
+export const CookieKeys = {
+ FontSize: "kri_fontSize",
+ // 필요하면 여기 계속 추가 (예: Theme: "kri_theme", ...)
+} as const;
+
+export const CookieType: Record = {
+ [CookieKeys.FontSize]: "persistence",
+};
+
+
+export type CookieKey = (typeof CookieKeys)[keyof typeof CookieKeys];
\ No newline at end of file
diff --git a/src/store/cookie/cookie.ts b/src/store/cookie/cookie.ts
new file mode 100644
index 0000000..d8a5314
--- /dev/null
+++ b/src/store/cookie/cookie.ts
@@ -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) {
+ if (!isBrowser()) return;
+
+ try {
+ document.cookie = buildCookieString(key, "", {
+ ...(options ?? {}),
+ days: -1, // 과거로 설정해서 삭제
+ });
+ } catch {
+ // 무시
+ }
+ },
+};
\ No newline at end of file
diff --git a/src/store/jotai/auth.ts b/src/store/jotai/auth.ts
new file mode 100644
index 0000000..a181b9c
--- /dev/null
+++ b/src/store/jotai/auth.ts
@@ -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(
+ StorageKeys.AuthState,
+ initialAuthState,
+);
\ No newline at end of file
diff --git a/src/store/jotai/loading.ts b/src/store/jotai/loading.ts
new file mode 100644
index 0000000..0ac0876
--- /dev/null
+++ b/src/store/jotai/loading.ts
@@ -0,0 +1,8 @@
+"use client";
+
+import { atom } from "jotai";
+
+/**
+ * 전역 로딩 상태
+ */
+export const loadingAtom = atom(false);
\ No newline at end of file
diff --git a/src/store/jotai/project.ts b/src/store/jotai/project.ts
new file mode 100644
index 0000000..6b3b6c4
--- /dev/null
+++ b/src/store/jotai/project.ts
@@ -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(
+ StorageKeys.SelectedProject,
+ null,
+ );
\ No newline at end of file
diff --git a/src/store/jotai/utils.ts b/src/store/jotai/utils.ts
new file mode 100644
index 0000000..1f287d0
--- /dev/null
+++ b/src/store/jotai/utils.ts
@@ -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 = (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 = (
+ key: StorageKey,
+ initialValue: T,
+) => {
+ const realInitialValue = loadInitialState("local", key, initialValue);
+ const baseAtom: PrimitiveAtom = atom(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 = (
+ key: StorageKey,
+ initialValue: T,
+) => {
+ const realInitialValue = loadInitialState("session", key, initialValue);
+ const baseAtom: PrimitiveAtom = atom(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;
+}
\ No newline at end of file
diff --git a/src/store/storage/secure-storage.ts b/src/store/storage/secure-storage.ts
new file mode 100644
index 0000000..56d6aef
--- /dev/null
+++ b/src/store/storage/secure-storage.ts
@@ -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();
+};
\ No newline at end of file
diff --git a/src/store/storage/storage-keys.ts b/src/store/storage/storage-keys.ts
new file mode 100644
index 0000000..faf4366
--- /dev/null
+++ b/src/store/storage/storage-keys.ts
@@ -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 = {
+ [StorageKeys.AuthState]: "local",
+ [StorageKeys.SeatNumber]: "local",
+ [StorageKeys.LoginType]: "local",
+ [StorageKeys.SelectedProject]: "session",
+};
+
+export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];
\ No newline at end of file
diff --git a/src/types/auth.ts b/src/types/auth.ts
index 7a2b320..c123218 100644
--- a/src/types/auth.ts
+++ b/src/types/auth.ts
@@ -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;
};
\ No newline at end of file