FEAT(app): add password protection

- Add authentication feature
- Enable password login
This commit is contained in:
2025-11-24 23:18:11 +09:00
parent c04a3fb267
commit 471cde3986
7 changed files with 290 additions and 2 deletions

View File

@@ -0,0 +1,84 @@
import { NextRequest, NextResponse } from 'next/server'
import { corsHeaders, handleCorsPreFlight } from '@/shared/lib/cors'
const PASSWORD = '5364'
const SESSION_COOKIE_NAME = 'todo-auth-session'
// OPTIONS - CORS preflight 처리
export async function OPTIONS() {
return handleCorsPreFlight()
}
// POST - 비밀번호 인증
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { password } = body
if (!password) {
const response = NextResponse.json(
{ success: false, error: '비밀번호를 입력해주세요' },
{ status: 400 }
)
Object.entries(corsHeaders()).forEach(([key, value]) => {
response.headers.set(key, value)
})
return response
}
if (password === PASSWORD) {
// 인증 성공 - 세션 쿠키 설정
const response = NextResponse.json(
{ success: true, message: '인증 성공' },
{ status: 200 }
)
// HttpOnly 쿠키로 세션 저장 (보안 강화)
response.cookies.set(SESSION_COOKIE_NAME, 'authenticated', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 60 * 60 * 24, // 24시간
path: '/',
})
Object.entries(corsHeaders()).forEach(([key, value]) => {
response.headers.set(key, value)
})
return response
} else {
const response = NextResponse.json(
{ success: false, error: '비밀번호가 일치하지 않습니다' },
{ status: 401 }
)
Object.entries(corsHeaders()).forEach(([key, value]) => {
response.headers.set(key, value)
})
return response
}
} catch (error) {
console.error('Password auth error:', error)
const response = NextResponse.json(
{ success: false, error: '서버 오류가 발생했습니다' },
{ status: 500 }
)
Object.entries(corsHeaders()).forEach(([key, value]) => {
response.headers.set(key, value)
})
return response
}
}
// GET - 인증 상태 확인
export async function GET(request: NextRequest) {
const session = request.cookies.get(SESSION_COOKIE_NAME)?.value
const response = NextResponse.json(
{ success: true, authenticated: session === 'authenticated' },
{ status: 200 }
)
Object.entries(corsHeaders()).forEach(([key, value]) => {
response.headers.set(key, value)
})
return response
}

View File

@@ -1,6 +1,11 @@
import { TodoApp } from '@/src/widgets/todo-app'
import PasswordModal from '@/src/features/password-auth/ui/PasswordModal'
export default function Home() {
return <TodoApp />
return (
<PasswordModal>
<TodoApp />
</PasswordModal>
)
}

View File

@@ -0,0 +1,51 @@
import { NextRequest, NextResponse } from 'next/server'
import { isAuthenticated, createUnauthorizedResponse } from '@/shared/lib/auth'
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
// 공개 경로 (인증 불필요)
const publicPaths = [
'/api/auth/password', // 비밀번호 인증 API
'/api/health', // 헬스체크
]
// 공개 경로는 통과
if (publicPaths.some(path => pathname.startsWith(path))) {
return NextResponse.next()
}
// API 라우트 보호
if (pathname.startsWith('/api/')) {
if (!isAuthenticated(request)) {
return createUnauthorizedResponse()
}
return NextResponse.next()
}
// 페이지 라우트 보호
if (pathname === '/' || pathname.startsWith('/app')) {
if (!isAuthenticated(request)) {
// 인증되지 않은 경우, 클라이언트에서 처리하도록 그대로 진행
// (PasswordModal이 표시됨)
return NextResponse.next()
}
return NextResponse.next()
}
return NextResponse.next()
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder
*/
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
}

View File

@@ -0,0 +1,2 @@
export { default as PasswordModal } from './ui/PasswordModal'

View File

@@ -0,0 +1,119 @@
'use client'
import { useState, ReactNode, useEffect } from 'react'
import { Input, Button } from '../../../shared/ui'
interface PasswordModalProps {
children: ReactNode
}
export default function PasswordModal({ children }: PasswordModalProps) {
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [isAuthenticated, setIsAuthenticated] = useState(false)
const [isChecking, setIsChecking] = useState(true)
// 컴포넌트 마운트 시 인증 상태 확인
useEffect(() => {
checkAuthStatus()
}, [])
const checkAuthStatus = async () => {
try {
const response = await fetch('/api/auth/password', {
method: 'GET',
credentials: 'include',
})
const data = await response.json()
if (data.success && data.authenticated) {
setIsAuthenticated(true)
}
} catch (error) {
console.error('인증 상태 확인 실패:', error)
} finally {
setIsChecking(false)
}
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
try {
const response = await fetch('/api/auth/password', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({ password }),
})
const data = await response.json()
if (data.success) {
setIsAuthenticated(true)
setPassword('')
} else {
setError(data.error || '비밀번호가 일치하지 않습니다.')
setPassword('')
}
} catch (error) {
console.error('인증 요청 실패:', error)
setError('서버 오류가 발생했습니다. 다시 시도해주세요.')
setPassword('')
}
}
// 인증 상태 확인 중일 때 로딩 표시
if (isChecking) {
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
<div className="bg-white rounded-lg shadow-xl p-8">
<p className="text-gray-600"> ...</p>
</div>
</div>
)
}
if (isAuthenticated) {
return <>{children}</>
}
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
<div className="bg-white rounded-lg shadow-xl p-8 w-full max-w-md mx-4">
<h2 className="text-2xl font-bold text-gray-800 mb-4 text-center">
</h2>
<p className="text-gray-600 mb-6 text-center">
Todo .
</p>
<form onSubmit={handleSubmit} className="space-y-4">
<Input
type="password"
placeholder="비밀번호를 입력하세요"
value={password}
onChange={(e) => {
setPassword(e.target.value)
setError('')
}}
className="w-full h-12 border-gray-300 focus:border-green-500 focus:ring-green-500/20"
autoFocus
/>
{error && (
<p className="text-red-500 text-sm text-center">{error}</p>
)}
<Button
type="submit"
className="w-full bg-green-600 hover:bg-green-700 text-white h-12 rounded-md font-medium"
>
</Button>
</form>
</div>
</div>
)
}

View File

@@ -0,0 +1,27 @@
import { NextRequest } from 'next/server'
export const SESSION_COOKIE_NAME = 'todo-auth-session'
/**
* 요청이 인증되었는지 확인
*/
export function isAuthenticated(request: NextRequest): boolean {
const session = request.cookies.get(SESSION_COOKIE_NAME)?.value
return session === 'authenticated'
}
/**
* 인증되지 않은 요청에 대한 응답 생성
*/
export function createUnauthorizedResponse() {
return new Response(
JSON.stringify({ success: false, error: '인증이 필요합니다' }),
{
status: 401,
headers: {
'Content-Type': 'application/json',
},
}
)
}