-
Notifications
You must be signed in to change notification settings - Fork 0
[feature] 로그인/회원가입 모달 및 Header 이벤트 로직 구현 #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
0b04263
feat: header의 로그인 버튼 클릭 이벤트 핸들러 추가
cl-o-lc 444f043
feat: 로그인/회원가입 모달 컴포넌트 구현
cl-o-lc c06e3ff
feat: 로그인 버튼 클릭 시 모달 열기 이벤트 추가
cl-o-lc 58685d5
chore: 프론트엔드 API base URL 설정을 위한 .env.local 추가
cl-o-lc c0335ea
style: layout에 전역 배경색(bg-gray-50) 적용해 스크롤 시 하단 검정색 영역 문제 해결
cl-o-lc 1cd3680
feat: 로그인/로그아웃 상태 관리 및 UI 동작 개선
cl-o-lc 45a7091
refactor: ConfirmModal에 role/aria 및 버튼 type 추가, ESC/포커스 처리
cl-o-lc 7ae67f4
fix: 회원가입 실패 시 모달이 닫히지 않도록 처리
cl-o-lc bb0b647
refactor: 옵션 prop 안전 호출 적용 및 파일명 수정
cl-o-lc bb5ee05
refactor: isAuthed 상태에 따른 필수 핸들러를 타입으로 강제
cl-o-lc 49c2c56
refactor: 환경변수 기반 API URL 안전 조합 및 기본 경로 처리
cl-o-lc c1dfb2e
refactor: fetch 실패 응답 시 에러 처리 및 no-store 캐시 적용
cl-o-lc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,19 +3,60 @@ | |
| import Header from '@/components/ui/Header'; | ||
| import SearchForm from '@/components/ServerSearchForm'; | ||
| import { useRouter } from 'next/navigation'; | ||
| import KoreanStandardTime from '@/components/KoreanStandaradTime'; | ||
| import React, { useEffect, useState } from 'react'; | ||
| import KoreanStandardTime from '@/components/KoreanStandardTime'; | ||
| import LoginModal from '@/components/auth/LoginModal'; | ||
| import SignupModal from '@/components/auth/SignupModal'; | ||
| import ConfirmModal from '@/components/ui/ConfirmModal'; | ||
|
|
||
| export default function Home() { | ||
| const router = useRouter(); | ||
| const [signupOpen, setSignupOpen] = useState(false); | ||
| const [loginOpen, setLoginOpen] = useState(false); | ||
| const [isAuthed, setIsAuthed] = useState(false); | ||
| const [userName, setUserName] = useState<string | undefined>(undefined); | ||
| const [confirmOpen, setConfirmOpen] = useState(false); | ||
|
|
||
| const handleSubmit = (url: string) => { | ||
| router.push(`/result?url=${encodeURIComponent(url)}`); | ||
| }; | ||
|
|
||
| // 새로고침 시에도 로그인 유지 | ||
| useEffect(() => { | ||
| const at = localStorage.getItem('accessToken'); | ||
| const name = localStorage.getItem('userName') || undefined; | ||
| if (at) { | ||
| setIsAuthed(true); | ||
| setUserName(name); | ||
| } | ||
| }, []); | ||
|
|
||
| const handleLogout = () => { | ||
| localStorage.removeItem('accessToken'); | ||
| localStorage.removeItem('refreshToken'); | ||
| localStorage.removeItem('userName'); | ||
| setIsAuthed(false); | ||
| setUserName(undefined); | ||
| setConfirmOpen(false); | ||
|
|
||
| alert('로그아웃 되었습니다.'); | ||
| router.push('/'); // 홈으로 리다이렉트 | ||
| }; | ||
|
|
||
| const headerProps: React.ComponentProps<typeof Header> = isAuthed | ||
| ? { | ||
| isAuthed: true as const, | ||
| userName: userName!, | ||
| onLogoutClick: () => setConfirmOpen(true), | ||
| } | ||
| : { | ||
| onLoginClick: () => setLoginOpen(true), | ||
| }; | ||
|
|
||
| return ( | ||
| <div className="min-h-screen bg-gray-50 text-gray-900"> | ||
| {/* Header */} | ||
| <Header /> | ||
| <Header {...headerProps} /> | ||
|
|
||
| {/* Hero */} | ||
| <section className="text-center py-16"> | ||
|
|
@@ -42,6 +83,89 @@ export default function Home() { | |
| <section className="max-w-3xl mx-auto mb-20 p-10"> | ||
| <KoreanStandardTime showToggle={false} /> | ||
| </section> | ||
|
|
||
| {/* 로그인 모달 */} | ||
| <LoginModal | ||
| open={loginOpen} | ||
| onClose={() => setLoginOpen(false)} | ||
| onSignupClick={() => { | ||
| setLoginOpen(false); | ||
| setSignupOpen(true); | ||
| }} | ||
| onSubmit={async ({ email, password }) => { | ||
| try { | ||
| const res = await fetch( | ||
| `${process.env.NEXT_PUBLIC_API_BASE}/api/auth/login`, | ||
| { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| body: JSON.stringify({ email, password }), | ||
| }, | ||
| ); | ||
|
|
||
| const data = await res.json(); | ||
|
|
||
| if (!res.ok) throw new Error(data.error || '로그인 실패'); | ||
|
|
||
| localStorage.setItem('accessToken', data.data.accessToken); | ||
| localStorage.setItem('refreshToken', data.data.refreshToken); | ||
|
Comment on lines
+110
to
+111
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Refresh Token을 localStorage 에 저장하면 XSS에 취약합니다
🤖 Prompt for AI Agents |
||
| if (data?.data?.user?.username) { | ||
| localStorage.setItem('userName', data.data.user.username); | ||
| setUserName(data.data.user.username); | ||
| } | ||
| setIsAuthed(true); | ||
| return true; | ||
| } catch (err) { | ||
| alert(err instanceof Error ? err.message : '로그인 중 오류 발생'); | ||
| return false; // 실패 시 false 반환 | ||
| } | ||
| }} | ||
| /> | ||
|
|
||
| {/* 회원가입 모달 */} | ||
| <SignupModal | ||
| open={signupOpen} | ||
| onClose={() => setSignupOpen(false)} | ||
| onLoginClick={() => { | ||
| setSignupOpen(false); | ||
| setLoginOpen(true); | ||
| }} | ||
| onSubmit={async ({ username, email, password }) => { | ||
| try { | ||
| const res = await fetch( | ||
| `${process.env.NEXT_PUBLIC_API_BASE}/api/auth/register`, | ||
| { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| body: JSON.stringify({ username, email, password }), | ||
| }, | ||
| ); | ||
| const data = await res.json(); | ||
|
|
||
| if (!res.ok) { | ||
| throw new Error(data.error || '회원가입 실패'); | ||
| } | ||
|
|
||
| console.log('회원가입 성공', data.data.user); | ||
| alert('회원가입이 완료되었습니다. 로그인 해주세요.'); | ||
| setSignupOpen(false); | ||
| setLoginOpen(true); // 바로 로그인 유도 | ||
| } catch (err) { | ||
| alert(err instanceof Error ? err.message : '회원가입 중 오류 발생'); | ||
| } | ||
| }} | ||
| /> | ||
|
|
||
| {/* 로그아웃 확인 모달 */} | ||
| <ConfirmModal | ||
| open={confirmOpen} | ||
| title="로그아웃 확인" | ||
| message="정말 로그아웃하시겠습니까?" | ||
| confirmText="로그아웃" | ||
| cancelText="취소" | ||
| onConfirm={handleLogout} | ||
| onClose={() => setConfirmOpen(false)} | ||
| /> | ||
| </div> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| 'use client'; | ||
|
|
||
| import { useEffect, useState } from 'react'; | ||
|
|
||
| type Props = { | ||
| open: boolean; | ||
| onClose: () => void; | ||
| onSubmit?: (payload: { | ||
| email: string; | ||
| password: string; | ||
| }) => Promise<boolean> | boolean; | ||
| onSignupClick?: () => void; // 회원가입 열기 | ||
| }; | ||
|
|
||
| export default function LoginModal({ | ||
| open, | ||
| onClose, | ||
| onSubmit, | ||
| onSignupClick, | ||
| }: Props) { | ||
| const [showPw, setShowPw] = useState(false); | ||
| const [loading, setLoading] = useState(false); | ||
|
|
||
| useEffect(() => { | ||
| if (!open) return; | ||
| const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose(); | ||
| document.addEventListener('keydown', onKey); | ||
| return () => document.removeEventListener('keydown', onKey); | ||
| }, [open, onClose]); | ||
|
|
||
| if (!open) return null; | ||
|
|
||
| async function handleSubmit(e: React.FormEvent<HTMLFormElement>) { | ||
| e.preventDefault(); | ||
| const fd = new FormData(e.currentTarget); | ||
| const email = String(fd.get('email') || ''); | ||
| const password = String(fd.get('password') || ''); | ||
| setLoading(true); | ||
| try { | ||
| const ok = await onSubmit?.({ email, password }); | ||
| if (ok) onClose(); // 로그인 성공 시 모달 닫기 | ||
| } finally { | ||
| setLoading(false); | ||
| } | ||
| } | ||
|
|
||
| return ( | ||
| <div | ||
| role="dialog" | ||
| aria-modal="true" | ||
| className="fixed inset-0 z-[60] flex items-center justify-center" | ||
| > | ||
| {/* backdrop (배경 클릭으로 닫기) */} | ||
| <button | ||
| aria-label="닫기" | ||
| onClick={onClose} | ||
| className="absolute inset-0 bg-black/40" | ||
| /> | ||
|
|
||
| {/* panel */} | ||
| <div className="relative w-full max-w-md rounded-2xl bg-white p-12 shadow-lg border border-gray-200"> | ||
| {/* 닫기 버튼 */} | ||
| <button | ||
| onClick={onClose} | ||
| aria-label="모달 닫기" | ||
| className="absolute right-3 top-3 rounded p-1 text-gray-500 hover:bg-gray-100" | ||
| > | ||
| ✕ | ||
| </button> | ||
|
|
||
| {/* 로고 섹션 (logo-section) */} | ||
| <div className="text-center mb-8"> | ||
| <div className="inline-flex items-center gap-2 mb-4"> | ||
| <div className="h-8 w-8 rounded-lg text-white flex items-center justify-center bg-gradient-to-br from-indigo-400 to-purple-500"> | ||
| ⏰ | ||
| </div> | ||
| <div className="text-xl font-bold text-black">Check Time</div> | ||
| </div> | ||
| <p className="text-sm text-gray-500">계정에 로그인하세요</p> | ||
| </div> | ||
|
|
||
| {/* 로그인 폼 (login-form) */} | ||
| <form onSubmit={handleSubmit} className="space-y-5"> | ||
| <div> | ||
| <label | ||
| htmlFor="email" | ||
| className="mb-1 block text-sm font-medium text-gray-700" | ||
| > | ||
| 이메일 | ||
| </label> | ||
| <input | ||
| id="email" | ||
| name="email" | ||
| type="email" | ||
| required | ||
| placeholder="your@email.com" | ||
| className="w-full rounded-lg border border-gray-300 bg-gray-50 px-4 py-3 text-sm outline-none transition focus:border-indigo-500 focus:bg-white focus:ring-4 focus:ring-indigo-200/50" | ||
| /> | ||
| </div> | ||
|
|
||
| <div> | ||
| <label | ||
| htmlFor="password" | ||
| className="mb-1 block text-sm font-medium text-gray-700" | ||
| > | ||
| 비밀번호 | ||
| </label> | ||
| <div className="relative"> | ||
| <input | ||
| id="password" | ||
| name="password" | ||
| type={showPw ? 'text' : 'password'} | ||
| required | ||
| placeholder="비밀번호를 입력하세요" | ||
| className="w-full rounded-lg border border-gray-300 bg-gray-50 px-4 py-3 pr-10 text-sm outline-none transition focus:border-indigo-500 focus:bg-white focus:ring-4 focus:ring-indigo-200/50" | ||
| /> | ||
| <button | ||
| type="button" | ||
| onClick={() => setShowPw((v) => !v)} | ||
| className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600" | ||
| aria-label="비밀번호 표시 전환" | ||
| > | ||
| {showPw ? '🙈' : '👁️'} | ||
| </button> | ||
| </div> | ||
| <div className="mt-2 text-right"> | ||
| <button | ||
| type="button" | ||
| className="text-sm text-indigo-600 hover:underline" | ||
| > | ||
| 비밀번호를 잊으셨나요? | ||
| </button> | ||
| </div> | ||
| </div> | ||
|
|
||
| <button | ||
| type="submit" | ||
| disabled={loading} | ||
| className="w-full rounded-lg bg-black px-4 py-3 text-sm font-medium text-white transition hover:bg-black/80 disabled:bg-gray-300" | ||
| > | ||
| {loading ? ( | ||
| <span className="inline-flex items-center gap-2"> | ||
| <span className="inline-block h-4 w-4 animate-spin rounded-full border-2 border-transparent border-t-current" /> | ||
| 로그인 중… | ||
| </span> | ||
| ) : ( | ||
| '로그인' | ||
| )} | ||
| </button> | ||
| </form> | ||
|
|
||
| {/* 구분선 (divider) */} | ||
| <div className="my-6 flex items-center text-sm text-gray-400"> | ||
| <span className="h-px flex-1 bg-gray-200" /> | ||
| </div> | ||
|
|
||
| {/* 하단 링크 (bottom-link) */} | ||
| <p className="text-center text-sm text-gray-500"> | ||
| 아직 계정이 없으신가요?{' '} | ||
| <button | ||
| type="button" | ||
| onClick={() => { | ||
| onClose(); | ||
| onSignupClick?.(); | ||
| }} | ||
| className="font-medium text-indigo-600 hover:underline" | ||
| > | ||
| 회원가입 | ||
| </button> | ||
| </p> | ||
| </div> | ||
| </div> | ||
| ); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
토큰 만료‧무결성 검증 로직이 없습니다
로컬 스토리지에 토큰이 존재한다는 이유만으로
isAuthed를true로 설정하면만료·위조 토큰을 가진 사용자가 인증된 상태로 오인될 수 있습니다.
JWT 만료 확인 혹은
/auth/validate같은 엔드포인트 호출을 통해 최초 마운트 시 토큰 유효성을 검증해 주세요.🏁 Script executed:
Length of output: 5395
토큰 유효성 검증 로직 추가 필요
로컬 스토리지에 토큰이 존재한다고 곧바로
isAuthed를true로 설정하면, 만료되었거나 위조된 토큰도 인증된 상태로 오인될 수 있습니다.• 검증 대상:
src/app/page.tsxuseEffect 내부 (24–32라인)• 제안 사항:
exp) 확인/api/auth/validate같은 백엔드 엔드포인트에 토큰 검증 요청예시 코드 스니펫:
useEffect(() => { const at = localStorage.getItem('accessToken'); const name = localStorage.getItem('userName') || undefined; if (at) { - setIsAuthed(true); - setUserName(name); + // 1) 만료·무결성 검증 + fetch(`${process.env.NEXT_PUBLIC_API_BASE}/api/auth/validate`, { + headers: { Authorization: `Bearer ${at}` }, + }) + .then(res => { + if (res.ok) { + setIsAuthed(true); + setUserName(name); + } else { + localStorage.removeItem('accessToken'); + setIsAuthed(false); + } + }); } }, []);📝 Committable suggestion
🤖 Prompt for AI Agents