diff --git a/.agent/rules/doc-rule.md b/.agent/rules/doc-rule.md new file mode 100644 index 0000000..9d4e8e0 --- /dev/null +++ b/.agent/rules/doc-rule.md @@ -0,0 +1,333 @@ +--- +trigger: manual +--- + +# 역할 + +시니어 프론트엔드 엔지니어이자 "문서화 전문가". +목표: **코드 변경 없이 주석만 추가**하여 신규 개발자가 파일을 열었을 때 5분 내에 '사용자 행동 흐름'과 '데이터 흐름'을 파악할 수 있게 만든다. + +# 기술 스택 + +- TypeScript + React/Next.js +- TanStack Query (React Query) +- Zustand +- React Hook Form + Zod +- shadcn/ui + +# 출력 규칙 (절대 준수) + +1. **코드 로직 변경 금지**: 타입/런타임/동작/변수명/import 변경 절대 금지 +2. **주석만 추가**: TSDoc/라인주석/블록주석만 삽입 +3. **충분한 인라인 주석**: state, handler, JSX 각 영역에 주석 추가 (과하지 않게 적당히) +4. **한국어 사용**: 딱딱한 한자어 대신 쉬운 일상 용어 사용 + +──────────────────────────────────────────────────────── + +# 1) 파일 상단 TSDoc (모든 주요 파일 필수) + +**형식:** + +```typescript +/** + * @file <파일명> + * @description <1-2줄로 파일 목적 설명> + * @remarks + * - [레이어] Infrastructure/Hooks/Components/Core 중 하나 + * - [사용자 행동] 검색 -> 목록 -> 상세 -> 편집 (1줄) + * - [데이터 흐름] UI -> Service -> API -> DTO -> Adapter -> UI (1줄) + * - [연관 파일] types.ts, useXXXQuery.ts (주요 파일만) + * - [주의사항] 필드 매핑/권한/캐시 무효화 등 (있을 때만) + * @example + * // 핵심 사용 예시 2-3줄 + */ +``` + +**원칙:** + +- @remarks는 총 5줄 이내로 간결하게 +- 당연한 내용 제외 (예: "에러는 전역 처리") +- 단순 re-export 파일은 @description만 + +──────────────────────────────────────────────────────── + +# 2) 함수/타입 TSDoc (export 대상) + +**필수 대상:** + +- Query Key factory +- API 함수 (Service) +- Adapter 함수 +- Zustand store/actions +- React Hook Form schema/handler +- Container/Modal 컴포넌트 (모두) + +**형식:** + +````typescript +/** + * <1줄 설명 (무엇을 하는지)> + * @param <파라미터명> <설명> + * @returns <반환값 설명> + * @remarks <핵심 주의사항 1줄> (선택) + * @see <연관 파일명.tsx의 함수명 - 어떤 역할로 호출하는지> + */ + +## 2-1. 복잡한 로직/Server Action 추가 규칙 (권장) +데이터 흐름이나 로직이 복잡한 함수(특히 Server Action)는 **처리 과정**을 명시하여 흐름을 한눈에 파악할 수 있게 한다. + +**형식:** +```typescript +/** + * [함수명] + * + * <상세 설명> + * + * 처리 과정: + * 1. <데이터 추출/준비> + * 2. <검증 로직> + * 3. <외부 API/DB 호출> + * 4. <분기 처리 (성공/실패)> + * 5. <결과 반환/리다이렉트> + * + * @param ... + */ +```` + +```` + +## ⭐ @see 강화 규칙 (필수) + +모든 함수/컴포넌트에 **@see를 적극적으로 추가**하여 호출 관계를 명확히 한다. + +**@see 작성 패턴:** + +```typescript +/** + * @see OpptyDetailHeader.tsx - handleApprovalClick()에서 다이얼로그 열기 + * @see useContractApproval.ts - onConfirm 콜백으로 날짜 전달 + */ + +/** + * @see LeadDetailPage.tsx - 리드 상세 페이지에서 목록 조회 + * @see LeadSearchForm.tsx - 검색 폼 제출 시 호출 + */ +```` + +**@see 필수 포함 정보:** + +1. **파일명** - 어떤 파일에서 호출하는지 +2. **함수/이벤트명** - 어떤 함수나 이벤트에서 호출하는지 +3. **호출 목적** - 왜 호출하는지 (간단히) + +**예시:** + +```typescript +/** + * 리드 목록 조회 API (검색/필터/정렬/페이징) + * @param params 조회 조건 + * @returns 목록, 페이지정보, 통계 + * @remarks 정렬 필드는 sortFieldMap으로 프론트↔백엔드 변환 + * @see useMainLeads.ts - useQuery의 queryFn으로 호출 + * @see LeadTableContainer.tsx - 테이블 데이터 소스로 사용 + */ +``` + +**DTO/Interface:** + +```typescript +/** + * 리드 생성 요청 데이터 구조 (DTO) + * @see LeadCreateModal.tsx - 리드 생성 폼 제출 시 사용 + */ +export interface CreateLeadRequest { ... } +``` + +**Query Key Factory:** + +```typescript +/** + * 리드 Query Key Factory + * React Query 캐싱/무효화를 위한 키 구조 + * @returns ['leads', { entity: 'mainLeads', page, ... }] 형태 + * @see useLeadsQuery.ts - queryKey로 사용 + * @see useLeadMutations.ts - invalidateQueries 대상 + */ +export const leadKeys = { ... } + +/** 메인 리드 목록 키 */ +mainLeads: (...) => [...], +``` + +──────────────────────────────────────────────────────── + +# 3) 인라인 주석 (적극 활용) + +## 3-1. State 주석 (필수) + +모든 useState/useRef에 역할 주석 추가 + +```typescript +// [State] 선택된 날짜 (기본값: 오늘) +const [selectedDate, setSelectedDate] = useState(new Date()); + +// [State] 캘린더 팝오버 열림 상태 +const [isCalendarOpen, setIsCalendarOpen] = useState(false); + +// [Ref] 파일 input 참조 (프로그래밍 방식 클릭용) +const fileInputRef = useRef(null); +``` + +## 3-2. Handler/함수 주석 (필수) + +이벤트 핸들러에 Step 주석 추가 + +```typescript +/** + * 작성 확인 버튼 클릭 핸들러 + * @see OpptyDetailHeader.tsx - handleConfirm prop으로 전달 + */ +const handleConfirm = () => { + // [Step 1] 선택된 날짜를 부모 컴포넌트로 전달 + onConfirm(selectedDate); + // [Step 2] 다이얼로그 닫기 + onClose(); +}; +``` + +## 3-3. JSX 영역 주석 (필수) + +UI 구조를 파악하기 쉽게 영역별 주석 추가 + +```tsx +return ( + + {/* ========== 헤더 영역 ========== */} + + 제목 + + + {/* ========== 본문: 날짜 선택 영역 ========== */} +
+ {/* 날짜 선택 Popover */} + + {/* 트리거 버튼: 현재 선택된 날짜 표시 */} + ... + {/* 캘린더 컨텐츠: 한국어 로케일 */} + ... + +
+ + {/* ========== 하단: 액션 버튼 영역 ========== */} +
+ + +
+
+); +``` + +**JSX 주석 규칙:** + +- `{/* ========== 영역명 ========== */}` - 큰 섹션 구분 +- `{/* 설명 */}` - 개별 요소 설명 +- 스크롤 없이 UI 구조 파악 가능하게 + +──────────────────────────────────────────────────────── + +# 4) 함수 내부 Step 주석 + +**대상:** +조건/분기/데이터 변환/API 호출/상태 변경이 있는 함수 + +**형식:** + +```typescript +// [Step 1] <무엇을 하는지 간결하게> +// [Step 2] <다음 단계> +// [Step 3] <최종 단계> +``` + +**규칙:** + +- 각 Step은 1줄로 +- 반드시 1번부터 순차적으로 +- "무엇을", "왜"를 명확하게 + +**예시:** + +```typescript +export const getMainLeads = async (params) => { + // [Step 1] UI 정렬 필드를 백엔드 컬럼명으로 매핑 + const mappedField = sortFieldMap[sortField] || sortField; + + // [Step 2] API 요청 파라미터 구성 + const requestParams = { ... }; + + // [Step 3] 리드 목록 조회 API 호출 + const { data } = await axiosInstance.get(...); + + // [Step 4] 응답 데이터 검증 및 기본값 설정 + let dataList = data?.data?.list || []; + + // [Step 5] UI 모델로 변환 및 결과 반환 + return { list: dataList.map(convertToRow), ... }; +} +``` + +──────────────────────────────────────────────────────── + +# 5) 레이어별 특수 규칙 + +## 5-1. Service/API + +- **Step 주석**: API 호출 흐름을 단계별로 명시 +- **@see**: 이 API를 호출하는 모든 훅/컴포넌트 명시 + +## 5-2. Hooks (TanStack Query) + +- **Query Key**: 반환 구조 예시 필수 +- **캐시 전략**: invalidateQueries/setQueryData 사용 이유 +- **@see**: 이 훅을 사용하는 모든 컴포넌트 명시 + +## 5-3. Adapters + +- **간단한 변환**: 주석 불필요 +- **복잡한 변환**: 입력→출력 1줄 설명 + 변환 규칙 + +## 5-4. Components (Container/Modal) + +- **상태 관리**: 어떤 state가 어떤 이벤트로 변경되는지 +- **Dialog/Modal**: open 상태 소유자, 닫힘 조건 +- **Table**: 인라인 편집, 스켈레톤 범위 +- **JSX 영역 주석**: UI 구조 파악용 영역 구분 주석 필수 + +## 5-5. Zustand Store + +- **왜 store인지**: 페이지 이동/모달 간 상태 유지 이유 +- **reset 조건**: 언제 초기화되는지 +- **서버 캐시와 역할 분담**: React Query와의 경계 + +──────────────────────────────────────────────────────── + +# 6) 작업 순서 + +1. 파일 레이어 판별 (Infrastructure/Hooks/UI/Core) +2. 파일 상단 TSDoc 추가 (@see 포함) +3. export 대상에 TSDoc 추가 (@see 필수) +4. State/Ref에 인라인 주석 추가 +5. Handler 함수에 TSDoc + Step 주석 추가 +6. JSX 영역별 구분 주석 추가 +7. Query Key Factory에 반환 구조 예시 추가 + +# 제약사항 + +- **@author는 jihoon87.lee 고정** +- **@see는 필수**: 호출 관계 명확히 +- **Step 주석은 1줄**: 간결하게 +- **JSX 주석 필수**: UI 구조 파악용 +- **@see는 파일명 + 함수명 + 역할**: 전체 경로 불필요 + +# 지금부터 작업 + +내가 주는 코드를 위 규칙에 맞게 "주석만" 보강하라. diff --git a/.env.example b/.env.example index 7264df2..9a1a0d9 100644 --- a/.env.example +++ b/.env.example @@ -4,3 +4,6 @@ NEXT_PUBLIC_SUPABASE_URL= NEXT_PUBLIC_SUPABASE_ANON_KEY= + +# 세션 타임아웃 (분 단위) +NEXT_PUBLIC_SESSION_TIMEOUT_MINUTES=30 diff --git a/app/(home)/page.tsx b/app/(home)/page.tsx index db50939..6601058 100644 --- a/app/(home)/page.tsx +++ b/app/(home)/page.tsx @@ -1,3 +1,13 @@ +/** + * @file app/(home)/page.tsx + * @description 서비스 메인 랜딩 페이지 + * @remarks + * - [레이어] Pages (Server Component) + * - [역할] 비로그인 유저 유입, 브랜드 소개, 로그인/대시보드 유도 + * - [구성요소] Header, Hero Section (Spline 3D), Feature Section (Bento Grid) + * - [데이터 흐름] Server Auth Check -> Client Component Props + */ + import Link from "next/link"; import { Button } from "@/components/ui/button"; import { createClient } from "@/utils/supabase/server"; @@ -5,106 +15,209 @@ import { Header } from "@/features/layout/components/header"; import { AUTH_ROUTES } from "@/features/auth/constants"; import { SplineScene } from "@/features/home/components/spline-scene"; +/** + * 메인 페이지 컴포넌트 (비동기 서버 컴포넌트) + * @returns Landing Page Elements + * @see layout.tsx - RootLayout 내에서 렌더링 + * @see spline-scene.tsx - 3D 인터랙션 + */ export default async function HomePage() { + // [Step 1] 서버 사이드 인증 상태 확인 const supabase = await createClient(); const { data: { user }, } = await supabase.auth.getUser(); return ( -
+
-
-
-
-
-

- 투자의 미래,{" "} - - 자동화하세요 - -

-

- AutoTrade는 최첨단 알고리즘을 통해 당신의 암호화폐 투자를 24시간 - 관리합니다. 감정에 휘둘리지 않는 투자를 경험하세요. -

-
- {user ? ( - - ) : ( - - )} - {!user && ( - - )} -
+
+ {/* Background Pattern */} +
+ +
+
+ {/* Badge */} +
+ + The Future of Trading
-
- {/* Spline Scene Container */} -
+

+ 투자의 미래를
+ + 자동화하세요 + +

+ +

+ AutoTrade는 최첨단 알고리즘을 통해 24시간 암호화폐 시장을 + 분석합니다. +
+ 감정 없는 데이터 기반 투자로 안정적인 수익을 경험해보세요. +

+ +
+ {user ? ( + + ) : ( + + )} + {!user && ( + + )} +
+ + {/* Spline Scene - Centered & Wide */} +
+
+ {/* Glow Effect */} +
+
-
-
-

- 주요 기능 + {/* Features Section - Bento Grid */} +
+
+

+ 강력한 기능,{" "} + 직관적인 경험

-

+

성공적인 투자를 위해 필요한 모든 도구가 준비되어 있습니다.

-
- {[ - { - title: "실시간 모니터링", - description: - "시장 상황을 실시간으로 분석하고 최적의 타이밍을 포착합니다.", - }, - { - title: "알고리즘 트레이딩", - description: - "검증된 전략을 기반으로 자동으로 매수와 매도를 실행합니다.", - }, - { - title: "포트폴리오 관리", - description: - "자산 분배와 리스크 관리를 통해 안정적인 수익을 추구합니다.", - }, - ].map((feature, index) => ( -
-
-
-

{feature.title}

-

- {feature.description} -

-
+ +
+ {/* Feature 1 */} +
+
+
+ + + +
+
+

실시간 모니터링

+

+ 초당 수천 건의 트랜잭션을 실시간으로 분석합니다. +
+ 시장 변동성을 놓치지 않고 최적의 진입 시점을 포착하세요. +

- ))} +
+
+ + {/* Feature 2 (Tall) */} +
+
+
+ + + +
+

알고리즘 트레이딩

+

+ 24시간 멈추지 않는 자동 매매 시스템입니다. +

+
+ {[ + "추세 추종 전략", + "변동성 돌파", + "AI 예측 모델", + "리스크 관리", + ].map((item) => ( +
+
+ {item} +
+ ))} +
+
+
+
+ + {/* Feature 3 */} +
+
+
+ + + +
+
+

스마트 포트폴리오

+

+ 목표 수익률 달성 시 자동으로 이익을 실현하고, MDD를 + 최소화하여 +
+ 시장이 하락할 때도 당신의 자산을 안전하게 지킵니다. +

+
+
+
+

diff --git a/app/(main)/dashboard/page.tsx b/app/(main)/dashboard/page.tsx index 4b731e7..3d5af51 100644 --- a/app/(main)/dashboard/page.tsx +++ b/app/(main)/dashboard/page.tsx @@ -1,12 +1,24 @@ +/** + * @file app/(main)/dashboard/page.tsx + * @description 사용자 대시보드 메인 페이지 (보호된 라우트) + * @remarks + * - [레이어] Pages (Server Component) + * - [역할] 사용자 자산 현황, 최근 활동, 통계 요약을 보여줌 + * - [권한] 로그인한 사용자만 접근 가능 (Middleware에 의해 보호됨) + */ + import { createClient } from "@/utils/supabase/server"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Activity, CreditCard, DollarSign, Users } from "lucide-react"; +/** + * 대시보드 페이지 (비동기 서버 컴포넌트) + * @returns Dashboard Grid Layout + */ export default async function DashboardPage() { + // [Step 1] 세션 확인 (Middleware가 1차 방어하지만, 데이터 접근 시 2차 확인) const supabase = await createClient(); - const { - data: { user }, - } = await supabase.auth.getUser(); + await supabase.auth.getUser(); return (
diff --git a/app/globals.css b/app/globals.css index 6cf72ed..43d30c9 100644 --- a/app/globals.css +++ b/app/globals.css @@ -8,6 +8,7 @@ --color-foreground: var(--foreground); --font-sans: var(--font-geist-sans); --font-mono: var(--font-geist-mono); + --font-heading: var(--font-heading); --color-sidebar-ring: var(--sidebar-ring); --color-sidebar-border: var(--sidebar-border); --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); @@ -44,6 +45,19 @@ --radius-2xl: calc(var(--radius) + 8px); --radius-3xl: calc(var(--radius) + 12px); --radius-4xl: calc(var(--radius) + 16px); + + --animate-gradient-x: gradient-x 15s ease infinite; + + @keyframes gradient-x { + 0%, 100% { + background-size: 200% 200%; + background-position: left center; + } + 50% { + background-size: 200% 200%; + background-position: right center; + } + } } :root { diff --git a/app/layout.tsx b/app/layout.tsx index f823401..6aa9c2e 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -1,6 +1,18 @@ +/** + * @file app/layout.tsx + * @description 애플리케이션의 최상위 루트 레이아웃 (RootLayout) + * @remarks + * - [레이어] Infrastructure/Layout + * - [역할] 전역 스타일(Font/CSS), 테마(Provider), 세션 관리(Manager) 초기화 + * - [데이터 흐름] Providers -> Children + * - [연관 파일] globals.css, theme-provider.tsx + */ + import type { Metadata } from "next"; -import { Geist, Geist_Mono } from "next/font/google"; +import { Geist, Geist_Mono, Outfit } from "next/font/google"; import { QueryProvider } from "@/providers/query-provider"; +import { ThemeProvider } from "@/components/theme-provider"; +import { SessionManager } from "@/features/auth/components/session-manager"; import "./globals.css"; const geistSans = Geist({ @@ -13,22 +25,43 @@ const geistMono = Geist_Mono({ subsets: ["latin"], }); +const outfit = Outfit({ + variable: "--font-heading", + subsets: ["latin"], + display: "swap", +}); + export const metadata: Metadata = { title: "AutoTrade", description: "Automated Crypto Trading Platform", }; +/** + * RootLayout 컴포넌트 + * @param children 렌더링할 자식 컴포넌트 + * @returns HTML 구조 및 전역 Provider 래퍼 + * @see theme-provider.tsx - 다크모드 지원 + * @see session-manager.tsx - 세션 타임아웃 감지 + */ export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( - + - {children} + + + {children} + ); diff --git a/components/form-message.tsx b/components/form-message.tsx index 78c3d5b..a18a680 100644 --- a/components/form-message.tsx +++ b/components/form-message.tsx @@ -1,16 +1,23 @@ +/** + * @file components/form-message.tsx + * @description 폼 제출 결과(성공/에러) 메시지를 표시하는 컴포넌트 + * @remarks + * - [레이어] Components/UI/Feedback + * - [기능] URL 쿼리 파라미터(`message`)를 감지하여 표시 후 URL 정리 + * - [UX] 메시지 확인 후 새로고침 시 메시지가 남지 않도록 히스토리 정리 (History API) + */ + "use client"; import { useEffect } from "react"; -import { usePathname, useRouter, useSearchParams } from "next/navigation"; +import { usePathname, useSearchParams } from "next/navigation"; /** - * [FormMessage 컴포넌트] - * - 로그인/회원가입 실패 메시지를 보여줍니다. - * - [UX 개선] 메시지가 보인 후, URL에서 ?message=... 부분을 지워서 - * 새로고침 시 메시지가 다시 뜨지 않도록 합니다. + * 폼 메시지 컴포넌트 + * @param message 표시할 메시지 텍스트 + * @returns 메시지 박스 또는 null */ export default function FormMessage({ message }: { message: string }) { - const router = useRouter(); const pathname = usePathname(); const searchParams = useSearchParams(); diff --git a/components/theme-provider.tsx b/components/theme-provider.tsx new file mode 100644 index 0000000..aa58aaf --- /dev/null +++ b/components/theme-provider.tsx @@ -0,0 +1,25 @@ +/** + * @file components/theme-provider.tsx + * @description next-themes 라이브러리를 사용한 테마 제공자 (Wrapper) + * @remarks + * - [레이어] Infrastructure/Provider + * - [역할] 앱 전역에 테마 컨텍스트 주입 (Light/Dark 모드 지원) + * - [연관 파일] layout.tsx (사용처) + */ + +"use client"; + +import * as React from "react"; +import { ThemeProvider as NextThemesProvider } from "next-themes"; + +/** + * ThemeProvider 컴포넌트 + * @param props next-themes Provider props + * @returns NextThemesProvider 래퍼 + */ +export function ThemeProvider({ + children, + ...props +}: React.ComponentProps) { + return {children}; +} diff --git a/components/theme-toggle.tsx b/components/theme-toggle.tsx new file mode 100644 index 0000000..bd9ca0c --- /dev/null +++ b/components/theme-toggle.tsx @@ -0,0 +1,59 @@ +/** + * @file components/theme-toggle.tsx + * @description 라이트/다크/시스템 테마 전환 토글 버튼 + * @remarks + * - [레이어] Components/UI + * - [사용자 행동] 버튼 클릭 -> 드롭다운 메뉴 -> 테마 선택 -> 즉시 반영 + * - [연관 파일] theme-provider.tsx (next-themes) + */ + +"use client"; + +import * as React from "react"; +import { Moon, Sun } from "lucide-react"; +import { useTheme } from "next-themes"; + +import { Button } from "@/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; + +/** + * 테마 토글 컴포넌트 + * @remarks next-themes의 useTheme 훅 사용 + * @returns Dropdown 메뉴 형태의 테마 선택기 + */ +export function ThemeToggle() { + const { setTheme } = useTheme(); + + return ( + + {/* ========== 트리거 버튼 ========== */} + + + + + {/* ========== 메뉴 컨텐츠 (우측 정렬) ========== */} + + setTheme("light")}> + Light + + setTheme("dark")}> + Dark + + setTheme("system")}> + System + + + + ); +} diff --git a/components/ui/alert-dialog.tsx b/components/ui/alert-dialog.tsx new file mode 100644 index 0000000..5b06414 --- /dev/null +++ b/components/ui/alert-dialog.tsx @@ -0,0 +1,150 @@ +/** + * @file components/ui/alert-dialog.tsx + * @description 알림 대화상자 (Alert Dialog) 컴포넌트 (Shadcn/ui) + * @remarks + * - [레이어] Components/UI/Primitive + * - [기능] 중요한 작업 확인 컨텍스트 제공 (로그아웃 경고 등) + * @see session-manager.tsx - 로그아웃 경고에 사용 + */ + +"use client"; + +import * as React from "react"; +import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"; + +import { cn } from "@/lib/utils"; +import { buttonVariants } from "@/components/ui/button"; + +const AlertDialog = AlertDialogPrimitive.Root; + +const AlertDialogTrigger = AlertDialogPrimitive.Trigger; + +const AlertDialogPortal = AlertDialogPrimitive.Portal; + +const AlertDialogOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName; + +const AlertDialogContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + + +)); +AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName; + +const AlertDialogHeader = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+); +AlertDialogHeader.displayName = "AlertDialogHeader"; + +const AlertDialogFooter = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+); +AlertDialogFooter.displayName = "AlertDialogFooter"; + +const AlertDialogTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName; + +const AlertDialogDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogDescription.displayName = + AlertDialogPrimitive.Description.displayName; + +const AlertDialogAction = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName; + +const AlertDialogCancel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName; + +export { + AlertDialog, + AlertDialogPortal, + AlertDialogOverlay, + AlertDialogTrigger, + AlertDialogContent, + AlertDialogHeader, + AlertDialogFooter, + AlertDialogTitle, + AlertDialogDescription, + AlertDialogAction, + AlertDialogCancel, +}; diff --git a/features/auth/actions.ts b/features/auth/actions.ts index b763964..0e86be2 100644 --- a/features/auth/actions.ts +++ b/features/auth/actions.ts @@ -1,4 +1,14 @@ -"use server"; +/** + * @file features/auth/actions.ts + * @description 인증 관련 서버 액션 (Server Actions) 모음 + * @remarks + * - [레이어] Service/API (Server Actions) + * - [역할] 로그인, 회원가입, 로그아웃, 비밀번호 재설정 등 인증 로직 처리 + * - [데이터 흐름] Client Form -> Server Action -> Supabase Auth -> Client Redirect + * - [연관 파일] login-form.tsx, signup-form.tsx, utils/supabase/server.ts + */ + +"use server"; import { revalidatePath } from "next/cache"; import { cookies } from "next/headers"; @@ -17,14 +27,9 @@ import { getAuthErrorMessage } from "./errors"; // ======================================== /** - * [FormData 추출 헬퍼] - * - * FormData에서 이메일과 비밀번호를 안전하게 추출합니다. - * - 이메일은 trim()으로 공백 제거 - * - null/undefined 방지를 위해 기본값 "" 사용 - * - * @param formData - HTML form에서 전달된 FormData 객체 - * @returns AuthFormData - 추출된 이메일과 비밀번호 + * FormData 추출 헬퍼 (이메일/비밀번호) + * @param formData HTML form 데이터 + * @returns 이메일(trim 적용), 비밀번호 */ function extractAuthData(formData: FormData): AuthFormData { const email = (formData.get("email") as string)?.trim() || ""; @@ -34,22 +39,13 @@ function extractAuthData(formData: FormData): AuthFormData { } /** - * [비밀번호 강도 검증 함수] - * - * 안전한 비밀번호인지 검사합니다. - * - * 비밀번호 정책: - * - 최소 8자 이상 - * - 대문자 1개 이상 포함 - * - 소문자 1개 이상 포함 - * - 숫자 1개 이상 포함 - * - 특수문자 1개 이상 포함 (!@#$%^&*(),.?":{}|<> 등) - * - * @param password - 검증할 비밀번호 - * @returns AuthError | null - 에러가 있으면 에러 객체, 없으면 null + * 비밀번호 강도 검증 함수 + * @param password 검증할 비밀번호 + * @returns 에러 객체 또는 null + * @remarks 최소 8자, 대/소문자, 숫자, 특수문자 포함 필수 */ function validatePassword(password: string): AuthError | null { - // 1. 최소 길이 체크 (8자 이상) + // [Step 1] 최소 길이 체크 (8자 이상) if (password.length < 8) { return { message: AUTH_ERROR_MESSAGES.PASSWORD_TOO_SHORT, @@ -57,7 +53,7 @@ function validatePassword(password: string): AuthError | null { }; } - // 2. 대문자 포함 여부 + // [Step 2] 대문자 포함 여부 if (!/[A-Z]/.test(password)) { return { message: AUTH_ERROR_MESSAGES.PASSWORD_TOO_WEAK, @@ -65,7 +61,7 @@ function validatePassword(password: string): AuthError | null { }; } - // 3. 소문자 포함 여부 + // [Step 3] 소문자 포함 여부 if (!/[a-z]/.test(password)) { return { message: AUTH_ERROR_MESSAGES.PASSWORD_TOO_WEAK, @@ -73,7 +69,7 @@ function validatePassword(password: string): AuthError | null { }; } - // 4. 숫자 포함 여부 + // [Step 4] 숫자 포함 여부 if (!/[0-9]/.test(password)) { return { message: AUTH_ERROR_MESSAGES.PASSWORD_TOO_WEAK, @@ -81,7 +77,7 @@ function validatePassword(password: string): AuthError | null { }; } - // 5. 특수문자 포함 여부 + // [Step 5] 특수문자 포함 여부 if (!/[!@#$%^&*(),.?":{}|<>]/.test(password)) { return { message: AUTH_ERROR_MESSAGES.PASSWORD_TOO_WEAK, @@ -89,26 +85,20 @@ function validatePassword(password: string): AuthError | null { }; } - // 모든 검증 통과 + // [Step 6] 모든 검증 통과 return null; } /** - * [입력값 검증 함수] - * - * 사용자가 입력한 이메일과 비밀번호의 유효성을 검사합니다. - * - * 검증 항목: - * 1. 빈 값 체크 - 이메일 또는 비밀번호가 비어있는지 확인 - * 2. 이메일 형식 - '@' 포함 여부로 간단한 형식 검증 - * 3. 비밀번호 강도 - 8자 이상, 대소문자/숫자/특수문자 포함 확인 - * - * @param email - 사용자 이메일 - * @param password - 사용자 비밀번호 - * @returns AuthError | null - 에러가 있으면 에러 객체, 없으면 null + * 입력값 유효성 검증 함수 + * @param email 사용자 이메일 + * @param password 사용자 비밀번호 + * @returns 에러 객체 또는 null + * @see login - 로그인 액션에서 호출 + * @see signup - 회원가입 액션에서 호출 */ function validateAuthInput(email: string, password: string): AuthError | null { - // 1. 빈 값 체크 + // [Step 1] 빈 값 체크 if (!email || !password) { return { message: AUTH_ERROR_MESSAGES.EMPTY_FIELDS, @@ -116,7 +106,7 @@ function validateAuthInput(email: string, password: string): AuthError | null { }; } - // 2. 이메일 형식 체크 (간단한 @ 포함 여부 확인) + // [Step 2] 이메일 형식 체크 (간단한 @ 포함 여부 확인) if (!email.includes("@")) { return { message: AUTH_ERROR_MESSAGES.INVALID_EMAIL, @@ -124,36 +114,19 @@ function validateAuthInput(email: string, password: string): AuthError | null { }; } - // 3. 비밀번호 강도 체크 + // [Step 3] 비밀번호 강도 체크 const passwordValidation = validatePassword(password); if (passwordValidation) { return passwordValidation; } - // 모든 검증 통과 + // [Step 4] 검증 통과 return null; } -/** - * [에러 메시지 번역 헬퍼] - * - * Supabase의 영문 에러 메시지를 사용자 친화적인 한글로 변환합니다. - * - * @param error - Supabase에서 받은 에러 메시지 - * @returns string - 한글로 번역된 에러 메시지 - */ -// 에러 메시지는 getAuthErrorMessage로 통일합니다. - // ======================================== // Server Actions (서버 액션) // ======================================== -// 흐름 요약 (어디서 호출되는지) -// - /login: features/auth/components/login-form.tsx -> login, signInWithGoogle, signInWithKakao -// - /signup: features/auth/components/signup-form.tsx -> signup -// - /forgot-password: app/forgot-password/page.tsx -> requestPasswordReset -// - /reset-password: features/auth/components/reset-password-form.tsx -> updatePassword -// - 메인(/): app/page.tsx -> signout -// - OAuth: signInWithGoogle/Kakao -> Supabase -> /auth/callback 라우트 /** * [로그인 액션] @@ -164,17 +137,17 @@ function validateAuthInput(email: string, password: string): AuthError | null { * 1. FormData에서 이메일/비밀번호 추출 * 2. 입력값 유효성 검증 (빈 값, 이메일 형식, 비밀번호 길이) * 3. Supabase Auth를 통한 로그인 시도 - * 4. 성공 시 메인 페이지로 리다이렉트 - * 5. 실패 시 에러 메시지와 함께 로그인 페이지로 리다이렉트 + * 4. 로그인 실패 시 에러 메시지와 함께 로그인 페이지로 리다이렉트 + * 5. 로그인 성공 시 캐시 무효화 및 메인 페이지로 리다이렉트 * - * @param formData - HTML form에서 전달된 FormData (이메일, 비밀번호 포함) + * @param formData 이메일, 비밀번호가 포함된 FormData + * @see login-form.tsx - 로그인 폼 제출 시 호출 */ export async function login(formData: FormData) { - // 호출: features/auth/components/login-form.tsx (로그인 폼 action) - // 1. FormData에서 이메일/비밀번호 추출 + // [Step 1] FormData에서 이메일/비밀번호 추출 const { email, password } = extractAuthData(formData); - // 2. 입력값 유효성 검증 + // [Step 2] 입력값 유효성 검증 const validationError = validateAuthInput(email, password); if (validationError) { return redirect( @@ -182,21 +155,20 @@ export async function login(formData: FormData) { ); } - // 3. Supabase 클라이언트 생성 및 로그인 시도 + // [Step 3] Supabase 클라이언트 생성 및 로그인 시도 const supabase = await createClient(); const { error } = await supabase.auth.signInWithPassword({ email, password, }); - // 4. 로그인 실패 시 에러 처리 + // [Step 4] 로그인 실패 시 에러 처리 if (error) { const message = getAuthErrorMessage(error); return redirect(`/login?message=${encodeURIComponent(message)}`); } - // 5. 로그인 성공 - 캐시 무효화 및 메인 페이지로 리다이렉트 - // revalidatePath: Next.js 캐시를 무효화하여 최신 인증 상태 반영 + // [Step 5] 로그인 성공 - 캐시 무효화 및 메인 페이지로 리다이렉트 revalidatePath("/", "layout"); redirect("/"); } @@ -214,14 +186,14 @@ export async function login(formData: FormData) { * 5-1. 즉시 세션 생성 시: 메인 페이지로 리다이렉트 (바로 로그인됨) * 5-2. 이메일 인증 필요 시: 로그인 페이지로 리다이렉트 (안내 메시지 포함) * - * @param formData - HTML form에서 전달된 FormData (이메일, 비밀번호 포함) + * @param formData 이메일, 비밀번호가 포함된 FormData + * @see signup-form.tsx - 회원가입 폼 제출 시 호출 */ export async function signup(formData: FormData) { - // 호출: features/auth/components/signup-form.tsx (회원가입 폼 action) - // 1. FormData에서 이메일/비밀번호 추출 + // [Step 1] FormData에서 이메일/비밀번호 추출 const { email, password } = extractAuthData(formData); - // 2. 입력값 유효성 검증 + // [Step 2] 입력값 유효성 검증 const validationError = validateAuthInput(email, password); if (validationError) { return redirect( @@ -229,35 +201,31 @@ export async function signup(formData: FormData) { ); } - // 3. Supabase 클라이언트 생성 및 회원가입 시도 + // [Step 3] Supabase 클라이언트 생성 및 회원가입 시도 const supabase = await createClient(); const { data, error } = await supabase.auth.signUp({ email, password, options: { // 이메일 인증 완료 후 리다이렉트될 URL - // 로컬 개발 환경: http://localhost:3001/auth/callback - // 프로덕션: NEXT_PUBLIC_BASE_URL 환경 변수에 설정된 주소 emailRedirectTo: `${process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3001"}/auth/callback?auth_type=signup`, }, }); - // 4. 회원가입 실패 시 에러 처리 + // [Step 4] 회원가입 실패 시 에러 처리 if (error) { const message = getAuthErrorMessage(error); return redirect(`/signup?message=${encodeURIComponent(message)}`); } - // 5. 회원가입 성공 - 세션 생성 여부에 따라 분기 처리 + // [Step 5] 회원가입 성공 처리 if (data.session) { - // 5-1. 즉시 세션이 생성된 경우 (이메일 인증 불필요) - // → 바로 메인 페이지로 이동 + // [Case 1] 즉시 세션 생성됨 (이메일 인증 불필요) revalidatePath("/", "layout"); redirect("/"); } - // 5-2. 이메일 인증이 필요한 경우 - // → 로그인 페이지로 이동 + 안내 메시지 + // [Case 2] 이메일 인증 필요 (로그인 페이지로 이동) revalidatePath("/", "layout"); redirect( `/login?message=${encodeURIComponent("회원가입이 완료되었습니다. 이메일을 확인하여 인증을 완료해 주세요.")}`, @@ -270,21 +238,23 @@ export async function signup(formData: FormData) { * 현재 세션을 종료하고 로그인 페이지로 이동합니다. * * 처리 과정: - * 1. Supabase Auth 세션 종료 - * 2. 캐시 무효화하여 인증 상태 갱신 + * 1. Supabase Auth 세션 종료 (서버 + 클라이언트 쿠키 삭제) + * 2. Next.js 캐시 무효화하여 인증 상태 갱신 * 3. 로그인 페이지로 리다이렉트 + * + * @see user-menu.tsx - 로그아웃 메뉴 클릭 시 호출 + * @see session-manager.tsx - 세션 타임아웃 시 호출 */ export async function signout() { - // 호출: app/page.tsx (로그아웃 버튼의 formAction) const supabase = await createClient(); - // 1. Supabase 세션 종료 (서버 + 클라이언트 쿠키 삭제) + // [Step 1] Supabase 세션 종료 (서버 + 클라이언트 쿠키 삭제) await supabase.auth.signOut(); - // 2. Next.js 캐시 무효화 + // [Step 2] Next.js 캐시 무효화 revalidatePath("/", "layout"); - // 3. 로그인 페이지로 리다이렉트 + // [Step 3] 로그인 페이지로 리다이렉트 redirect("/"); } @@ -292,10 +262,7 @@ export async function signout() { * [비밀번호 재설정 요청 액션] * * 사용자 이메일로 비밀번호 재설정 링크를 발송합니다. - * - * 보안 고려사항: - * - 이메일 존재 여부와 관계없이 동일한 성공 메시지 표시 - * - 이메일 열거 공격(Email Enumeration) 방지 + * 보안을 위해 이메일 존재 여부와 관계없이 동일한 메시지를 표시합니다. * * 처리 과정: * 1. FormData에서 이메일 추출 @@ -303,14 +270,14 @@ export async function signout() { * 3. Supabase를 통한 재설정 링크 발송 * 4. 성공 메시지와 함께 로그인 페이지로 리다이렉트 * - * @param formData - 이메일이 포함된 FormData + * @param formData 이메일 포함 + * @see forgot-password/page.tsx - 비밀번호 찾기 폼 제출 시 호출 */ export async function requestPasswordReset(formData: FormData) { - // 호출: app/forgot-password/page.tsx (비밀번호 재설정 요청 폼) - // 1. FormData에서 이메일 추출 + // [Step 1] FormData에서 이메일 추출 const email = (formData.get("email") as string)?.trim() || ""; - // 2. 이메일 검증 + // [Step 2] 이메일 유효성 검증 if (!email) { return redirect( `/forgot-password?message=${encodeURIComponent(AUTH_ERROR_MESSAGES.EMPTY_EMAIL)}`, @@ -323,20 +290,20 @@ export async function requestPasswordReset(formData: FormData) { ); } - // 3. Supabase를 통한 재설정 링크 발송 + // [Step 3] Supabase를 통한 재설정 링크 발송 const supabase = await createClient(); const { error } = await supabase.auth.resetPasswordForEmail(email, { redirectTo: `${process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3001"}/reset-password`, }); - // 4. 에러 처리 + // [Step 4] 에러 처리 if (error) { console.error("Password reset error:", error.message); const message = getAuthErrorMessage(error); return redirect(`/forgot-password?message=${encodeURIComponent(message)}`); } - // 5. 성공 메시지 표시 + // [Step 5] 성공 메시지 표시 (보안상 항상 성공 메시지 리턴 권장) redirect( `/login?message=${encodeURIComponent(AUTH_ERROR_MESSAGES.PASSWORD_RESET_SENT)}`, ); @@ -349,36 +316,44 @@ export async function requestPasswordReset(formData: FormData) { * * 처리 과정: * 1. FormData에서 새 비밀번호 추출 - * 2. 비밀번호 길이 검증 + * 2. 비밀번호 길이 및 강도 검증 * 3. Supabase를 통한 비밀번호 업데이트 - * 4. 성공 시 로그인 페이지로 리다이렉트 + * 4. 실패 시 에러 메시지 반환 + * 5. 성공 시 세션/쿠키 정리 후 로그아웃 및 캐시 무효화 + * 6. 성공 결과 반환 * - * @param formData - 새 비밀번호가 포함된 FormData + * @param formData 새 비밀번호 포함 + * @see reset-password-form.tsx - 비밀번호 재설정 폼 제출 시 호출 */ export async function updatePassword(formData: FormData) { - // 호출: features/auth/components/reset-password-form.tsx (재설정 폼) + // [Step 1] 새 비밀번호 추출 const password = (formData.get("password") as string) || ""; + // [Step 2] 비밀번호 강도 검증 const passwordValidation = validatePassword(password); if (passwordValidation) { return { ok: false, message: passwordValidation.message }; } + // [Step 3] Supabase를 통한 비밀번호 업데이트 const supabase = await createClient(); const { error } = await supabase.auth.updateUser({ password: password, }); + // [Step 4] 에러 처리 if (error) { const message = getAuthErrorMessage(error); return { ok: false, message }; } + // [Step 5] 세션 및 쿠키 정리 후 로그아웃 const cookieStore = await cookies(); cookieStore.delete(RECOVERY_COOKIE_NAME); await supabase.auth.signOut(); revalidatePath("/", "layout"); + // [Step 6] 성공 응답 반환 return { ok: true, message: AUTH_ERROR_MESSAGES.PASSWORD_RESET_SUCCESS, @@ -390,53 +365,47 @@ export async function updatePassword(formData: FormData) { // ======================================== /** - * [OAuth 로그인 헬퍼 함수] + * [OAuth 로그인 공통 헬퍼] * - * Google, Kakao 등의 소셜 로그인 제공자를 통해 인증을 수행합니다. + * 처리 과정: + * 1. Supabase OAuth 로그인 URL 생성 (PKCE) + * 2. 생성 중 에러 발생 시 로그인 페이지로 리다이렉트 (에러 메시지 포함) + * 3. 성공 시 해당 OAuth 제공자 페이지(data.url)로 리다이렉트 * - * PKCE (Proof Key for Code Exchange) 플로우: - * 1. 이 함수가 signInWithOAuth를 호출하면 Supabase가 OAuth URL 반환 - * 2. 사용자를 해당 OAuth 제공자(Google/Kakao) 로그인 페이지로 리다이렉트 - * 3. 사용자가 로그인 및 권한 동의 - * 4. OAuth 제공자가 /auth/callback?code=xxx로 리다이렉트 - * 5. callback 라우트에서 code를 세션으로 교환 (exchangeCodeForSession) - * 6. 메인 페이지로 최종 리다이렉트 - * - * 자동 회원가입: - * - 첫 로그인 시 auth.users 테이블에 자동으로 사용자 생성 - * - 이메일, provider, metadata(프로필 사진, 이름 등) 저장 - * - 기존 사용자는 그냥 로그인 - * - * @param provider - OAuth 제공자 ('google' | 'kakao') + * @param provider 'google' | 'kakao' + * @param extraOptions 추가 옵션 (예: prompt) + * @see signInWithGoogle + * @see signInWithKakao */ -async function signInWithProvider(provider: "google" | "kakao") { - // 호출: 아래 signInWithGoogle / signInWithKakao에서 공통 사용 +async function signInWithProvider( + provider: "google" | "kakao", + extraOptions: { queryParams?: { [key: string]: string } } = {}, +) { const supabase = await createClient(); - // 1. OAuth 인증 시작 + // [Step 1] OAuth 인증 시작 (URL 생성) const { data, error } = await supabase.auth.signInWithOAuth({ provider, options: { // PKCE 플로우를 위한 콜백 URL - // OAuth 제공자 인증 후 이 URL로 code와 함께 리다이렉트됨 redirectTo: `${process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3001"}/auth/callback`, + ...extraOptions, }, }); - // 2. 에러 처리 + // [Step 2] 에러 처리 if (error) { console.error(`[${provider} OAuth] 로그인 실패:`, error.message); const message = getAuthErrorMessage(error); return redirect(`/login?message=${encodeURIComponent(message)}`); } - // 3. OAuth 제공자 로그인 페이지로 리다이렉트 - // data.url은 Google/Kakao의 인증 페이지 URL + // [Step 3] OAuth 제공자 로그인 페이지로 리다이렉트 if (data.url) { redirect(data.url); } - // 4. URL이 없는 경우 (예상치 못한 상황) + // [Step 4] URL 생성 실패 시 에러 처리 redirect( `/login?message=${encodeURIComponent("로그인 처리 중 오류가 발생했습니다.")}`, ); @@ -444,36 +413,16 @@ async function signInWithProvider(provider: "google" | "kakao") { /** * [Google 로그인 액션] - * - * Google 계정으로 로그인합니다. - * "Google로 로그인" 버튼에서 호출됩니다. - * - * 처리 과정: - * 1. signInWithOAuth 호출하여 Google OAuth URL 받기 - * 2. Google 로그인 페이지로 리다이렉트 - * 3. (사용자가 Google에서 로그인 및 권한 동의) - * 4. /auth/callback으로 돌아와서 세션 생성 - * 5. 메인 페이지로 이동 + * @see login-form.tsx - 구글 로그인 버튼 클릭 시 호출 */ export async function signInWithGoogle() { - // 호출: features/auth/components/login-form.tsx (Google 로그인 버튼) return signInWithProvider("google"); } /** * [Kakao 로그인 액션] - * - * Kakao 계정으로 로그인합니다. - * "Kakao로 로그인" 버튼에서 호출됩니다. - * - * 처리 과정: - * 1. signInWithOAuth 호출하여 Kakao OAuth URL 받기 - * 2. Kakao 로그인 페이지로 리다이렉트 - * 3. (사용자가 Kakao에서 로그인 및 권한 동의) - * 4. /auth/callback으로 돌아와서 세션 생성 - * 5. 메인 페이지로 이동 + * @see login-form.tsx - 카카오 로그인 버튼 클릭 시 호출 */ export async function signInWithKakao() { - // 호출: features/auth/components/login-form.tsx (Kakao 로그인 버튼) - return signInWithProvider("kakao"); + return signInWithProvider("kakao", { queryParams: { prompt: "login" } }); } diff --git a/features/auth/components/session-manager.tsx b/features/auth/components/session-manager.tsx new file mode 100644 index 0000000..ce12027 --- /dev/null +++ b/features/auth/components/session-manager.tsx @@ -0,0 +1,148 @@ +/** + * @file features/auth/components/session-manager.tsx + * @description 사용자 세션 타임아웃 및 자동 로그아웃 관리 컴포넌트 + * @remarks + * - [레이어] Components/Infrastructure + * - [사용자 행동] 로그인 -> 활동 감지 -> 비활동 -> (경고) -> 로그아웃 + * - [데이터 흐름] Event -> Zustand Store -> Timer -> Logout + * - [연관 파일] stores/session-store.ts, features/auth/constants.ts + */ + +"use client"; + +import { useEffect, useState, useCallback } from "react"; +import { createClient } from "@/utils/supabase/client"; +import { useRouter, usePathname } from "next/navigation"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { useSessionStore } from "@/stores/session-store"; +import { SESSION_TIMEOUT_MS } from "@/features/auth/constants"; +// import { toast } from "sonner"; // Unused for now + +// 설정: 경고 표시 시간 (타임아웃 1분 전) - 현재 미사용 (즉시 로그아웃) +// const WARNING_MS = 60 * 1000; + +/** + * 세션 관리자 컴포넌트 + * 사용자 활동을 감지하여 세션 연장 및 타임아웃 처리 + * @returns 숨겨진 기능성 컴포넌트 (Global Layout에 포함) + * @remarks RootLayout에 포함되어 전역적으로 동작 + * @see layout.tsx - RootLayout에서 렌더링 + * @see session-store.ts - 마지막 활동 시간 관리 + */ +export function SessionManager() { + const router = useRouter(); + const pathname = usePathname(); + + // [State] 타임아웃 경고 모달 표시 여부 (현재 미사용) + const [showWarning, setShowWarning] = useState(false); + + // 인증 페이지에서는 동작하지 않음 + const isAuthPage = ["/login", "/signup", "/forgot-password"].includes( + pathname, + ); + + const { setLastActive } = useSessionStore(); + + /** + * 로그아웃 처리 핸들러 + * @see session-timer.tsx - 타임아웃 시 동일한 로직 필요 가능성 있음 + */ + const handleLogout = useCallback(async () => { + // [Step 1] Supabase 클라이언트 생성 + const supabase = createClient(); + + // [Step 2] 서버 사이드 로그아웃 요청 + await supabase.auth.signOut(); + + // [Step 3] 로컬 스토어 및 세션 정보 초기화 + useSessionStore.persist.clearStorage(); + + // [Step 4] 로그인 페이지로 리다이렉트 및 메시지 표시 + router.push("/login?message=세션이 만료되었습니다. 다시 로그인해주세요."); + router.refresh(); + }, [router]); + + useEffect(() => { + if (isAuthPage) return; + + // 마지막 활동 시간 업데이트 함수 + const updateLastActive = () => { + setLastActive(Date.now()); + if (showWarning) setShowWarning(false); + }; + + // [Step 1] 사용자 활동 이벤트 감지 (마우스, 키보드, 스크롤, 터치) + const events = ["mousedown", "keydown", "scroll", "touchstart"]; + const handleActivity = () => updateLastActive(); + + events.forEach((event) => window.addEventListener(event, handleActivity)); + + // [Step 2] 주기적(1초)으로 세션 만료 여부 확인 + const intervalId = setInterval(async () => { + const currentLastActive = useSessionStore.getState().lastActive; + const now = Date.now(); + const timeSinceLastActive = now - currentLastActive; + + // 타임아웃 초과 시 로그아웃 + if (timeSinceLastActive >= SESSION_TIMEOUT_MS) { + await handleLogout(); + } + // 경고 로직 (현재 비활성) + // else if (timeSinceLastActive >= TIMEOUT_MS - WARNING_MS) { + // setShowWarning(true); + // } + }, 1000); + + // [Step 3] 탭 활성화/컴퓨터 깨어남 감지 (절전 모드 대응) + const handleVisibilityChange = async () => { + if (!document.hidden) { + const currentLastActive = useSessionStore.getState().lastActive; + const now = Date.now(); + + // 절전 모드 복귀 시 즉시 만료 체크 + if (now - currentLastActive >= SESSION_TIMEOUT_MS) { + await handleLogout(); + } + } + }; + document.addEventListener("visibilitychange", handleVisibilityChange); + + return () => { + events.forEach((event) => + window.removeEventListener(event, handleActivity), + ); + clearInterval(intervalId); + document.removeEventListener("visibilitychange", handleVisibilityChange); + }; + }, [pathname, isAuthPage, showWarning, handleLogout, setLastActive]); + + return ( + + + {/* ========== 헤더: 제목 및 설명 ========== */} + + 로그아웃 예정 + + 장시간 활동이 없어 1분 뒤 로그아웃됩니다. 계속 하시려면 아무 키나 + 누르거나 클릭해주세요. + + + + {/* ========== 하단: 액션 버튼 ========== */} + + setShowWarning(false)}> + 로그인 연장 + + + + + ); +} diff --git a/features/auth/components/session-timer.tsx b/features/auth/components/session-timer.tsx new file mode 100644 index 0000000..12078a7 --- /dev/null +++ b/features/auth/components/session-timer.tsx @@ -0,0 +1,70 @@ +/** + * @file features/auth/components/session-timer.tsx + * @description 헤더에 표시되는 세션 만료 카운트다운 컴포넌트 + * @remarks + * - [레이어] Components/UI + * - [사용자 행동] 남은 시간 확인 -> 만료 임박 시 붉은색 경고 + * - [데이터 흐름] Zustand Store -> Calculation -> UI + * - [연관 파일] stores/session-store.ts, features/layout/header.tsx + */ + +"use client"; + +import { useEffect, useState } from "react"; +import { useSessionStore } from "@/stores/session-store"; +import { SESSION_TIMEOUT_MS } from "@/features/auth/constants"; + +/** + * 세션 만료 타이머 컴포넌트 + * 남은 시간을 mm:ss 형태로 표시 (10분 미만 시 경고 스타일) + * @returns 시간 표시 배지 (모바일 숨김) + * @remarks 1초마다 리렌더링 발생 + * @see header.tsx - 로그인 상태일 때 헤더에 표시 + */ +export function SessionTimer() { + const lastActive = useSessionStore((state) => state.lastActive); + + // [State] 남은 시간 (밀리초) + const [timeLeft, setTimeLeft] = useState(SESSION_TIMEOUT_MS); + + useEffect(() => { + const calculateTimeLeft = () => { + const now = Date.now(); + const passed = now - lastActive; + + // [Step 1] 남은 시간 계산 (음수 방지) + const remaining = Math.max(0, SESSION_TIMEOUT_MS - passed); + setTimeLeft(remaining); + }; + + calculateTimeLeft(); // 초기 실행 + + // [Step 2] 1초마다 남은 시간 갱신 + const interval = setInterval(calculateTimeLeft, 1000); + + return () => clearInterval(interval); + }, [lastActive]); + + // [Step 3] 시간 포맷팅 (mm:ss) + const minutes = Math.floor(timeLeft / 60000); + const seconds = Math.floor((timeLeft % 60000) / 1000); + + // [Step 4] 10분 미만일 때 긴급 스타일 적용 + const isUrgent = timeLeft < 10 * 60 * 1000; + + return ( + + ); +} diff --git a/features/auth/constants.ts b/features/auth/constants.ts index 3ba0c98..abe356e 100644 --- a/features/auth/constants.ts +++ b/features/auth/constants.ts @@ -1,10 +1,11 @@ /** - * [인증 관련 상수 정의] - * - * 인증 모듈 전체에서 공통으로 사용하는 상수들을 정의합니다. - * - 에러 메시지 - * - 라우트 경로 - * - 검증 규칙 + * @file features/auth/constants.ts + * @description 인증 모듈 전반에서 사용되는 상수, 에러 메시지, 설정값 정의 + * @remarks + * - [레이어] Core/Constants + * - [사용자 행동] 로그인/회원가입/비밀번호 찾기 등 인증 전반 + * - [데이터 흐름] UI/Service -> Constants -> UI (메시지 표시) + * - [주의사항] 환경 변수(SESSION_TIMEOUT_MINUTES)에 의존하는 상수 포함 */ // ======================================== @@ -220,6 +221,21 @@ export const PASSWORD_RULES = { REQUIRE_SPECIAL_CHAR: true, } as const; +// ======================================== +// 세션 관련 상수 +// ======================================== + +/** + * 세션 타임아웃 시간 (밀리초) + * 환경 변수에서 분 단위를 가져와 밀리초로 변환합니다. + * 기본값: 30분 + */ +export const SESSION_TIMEOUT_MS = + (Number(process.env.NEXT_PUBLIC_SESSION_TIMEOUT_MINUTES) || 30) * 60 * 1000; + +// 경고 표시 시간 (타임아웃 1분 전) +export const SESSION_WARNING_MS = 60 * 1000; + // ======================================== // 타입 정의 // ======================================== diff --git a/features/layout/components/header.tsx b/features/layout/components/header.tsx index 2c8cb99..a2de463 100644 --- a/features/layout/components/header.tsx +++ b/features/layout/components/header.tsx @@ -1,45 +1,92 @@ +/** + * @file features/layout/components/header.tsx + * @description 애플리케이션 최상단 헤더 컴포넌트 (네비게이션, 테마, 유저 메뉴) + * @remarks + * - [레이어] Components/UI/Layout + * - [사용자 행동] 홈 이동, 테마 변경, 로그인/회원가입 이동, 대시보드 이동 + * - [데이터 흐름] User Prop -> UI Conditional Rendering + * - [연관 파일] layout.tsx, session-timer.tsx, user-menu.tsx + */ + import Link from "next/link"; import { User } from "@supabase/supabase-js"; import { AUTH_ROUTES } from "@/features/auth/constants"; import { UserMenu } from "@/features/layout/components/user-menu"; +import { ThemeToggle } from "@/components/theme-toggle"; import { Button } from "@/components/ui/button"; +import { SessionTimer } from "@/features/auth/components/session-timer"; + interface HeaderProps { + /** 현재 로그인한 사용자 정보 (없으면 null) */ user: User | null; + /** 대시보드 링크 표시 여부 */ showDashboardLink?: boolean; } +/** + * 글로벌 헤더 컴포넌트 + * @param user Supabase User 객체 + * @param showDashboardLink 대시보드 바로가기 버튼 노출 여부 + * @returns Header JSX + * @see layout.tsx - RootLayout에서 데이터 주입하여 호출 + */ export function Header({ user, showDashboardLink = false }: HeaderProps) { return ( -
-
- -
- +
+
+ {/* ========== 좌측: 로고 영역 ========== */} + +
+
+
+ AutoTrade -
-
- {user ? ( - <> - {showDashboardLink && ( - + )} + + {/* 사용자 드롭다운 메뉴 */} + + + ) : ( + // [Case 2] 비로그인 상태 +
+ - )} - - - ) : ( - <> - - - - )} + +
+ )} +
); diff --git a/features/layout/components/user-menu.tsx b/features/layout/components/user-menu.tsx index 3cb3f97..5121d88 100644 --- a/features/layout/components/user-menu.tsx +++ b/features/layout/components/user-menu.tsx @@ -1,3 +1,12 @@ +/** + * @file features/layout/components/user-menu.tsx + * @description 사용자 프로필 드롭다운 메뉴 컴포넌트 + * @remarks + * - [레이어] Components/UI + * - [사용자 행동] Avatar 클릭 -> 드롭다운 오픈 -> 프로필/설정 이동 또는 로그아웃 + * - [연관 파일] header.tsx, features/auth/actions.ts (로그아웃) + */ + "use client"; import { signout } from "@/features/auth/actions"; @@ -15,16 +24,22 @@ import { LogOut, Settings, User as UserIcon } from "lucide-react"; import { useRouter } from "next/navigation"; interface UserMenuProps { + /** Supabase User 객체 */ user: User | null; } +/** + * 사용자 메뉴/프로필 컴포넌트 (로그인 시 헤더 노출) + * @param user 로그인한 사용자 정보 + * @returns Avatar 버튼 및 드롭다운 메뉴 + */ export function UserMenu({ user }: UserMenuProps) { const router = useRouter(); if (!user) return null; return ( - +