Compare commits

...

9 Commits

Author SHA1 Message Date
ae013acd2d fix: DownloadAdmin.test.jsx 미사용 waitFor import 제거 (ESLint)
Some checks failed
Client CI/CD / test (push) Failing after 12m21s
Client CI/CD / deploy (push) Has been cancelled
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 17:33:07 +09:00
dcb2d1847d ci: Gitea 환경으로 전환 (git.tolelom.xyz 레지스트리)
- Docker registry: ghcr.io → git.tolelom.xyz
- 로그인: GITEA_TOKEN 사용

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 17:25:27 +09:00
daeaaca902 ci: npm test 추가 + Docker GHCR 빌드/푸시 + SSH 배포 추가
- test job: lint + vitest + build
- docker job: main 머지 시 nginx 이미지 빌드/푸시
- deploy job: SSH로 docker compose pull web && up

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 17:21:55 +09:00
b2fe4519f8 fix: Vitest 4.x + jsdom 28 localStorage.clear 호환성 수정
Vitest 4.x가 jsdom에 --localstorage-file을 빈 경로로 전달할 때
localStorage가 .clear()가 없는 stub 객체가 되는 문제 수정.
setup.js에서 Storage 전체 구현체로 폴백.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 17:11:56 +09:00
2cea340163 feat: ErrorBoundary 개선 + admin CSS 모듈화
- ErrorBoundary에 에러 유형/메시지 표시 + 다시 시도/새로고침 버튼 추가
- admin 컴포넌트 CSS Modules 전환 (클래스명 충돌 방지)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 16:59:11 +09:00
eaa3319c5d feat: 에러 처리 개선 + 커스텀 확인 모달 + 관리자 테스트
- 에러 코드 기반 한국어 매핑 (8개 코드, parseError 개선)
- window.confirm → 커스텀 ConfirmDialog (다크 테마, Promise 기반)
- launch URL 파라미터 ticket → token 통일
- 관리자 테스트 27개 추가 (공지사항 12 + 다운로드 6 + 유저 9)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 16:44:04 +09:00
24cbc54a96 ci: GitHub Actions 워크플로우 추가
Node.js lint + build 자동화 (push/PR on main)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 10:56:56 +09:00
42567ab6e4 feat: 폼 유효성 피드백 + 모바일 반응형
폼 검증:
- RegisterPage: 아이디 실시간 검증, 비밀번호 강도, 확인 일치
- LoginPage: aria-describedby 접근성 개선

반응형:
- 768px 이하 레이아웃 최적화, 터치 타겟 44px

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 10:52:17 +09:00
555749b953 feat: 보안 + UX 개선
보안:
- SSAFY OAuth URL https 스킴 검증
- CSRF 방어 X-Requested-With 헤더 추가
- 업로드 에러 상태코드별 메시지 분기 (413, 409, 5xx)

UX:
- Admin 페이지 Toast 알림 통합
- API 에러 메시지 한글화 (localizeError)
- og:title, og:description 메타 태그 추가

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 10:37:49 +09:00
27 changed files with 1235 additions and 179 deletions

76
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,76 @@
name: CI/CD
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
# ── 1. 린트 + 테스트 + 빌드 ────────────────────────────────────────────────
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Install dependencies
run: npm ci --legacy-peer-deps
- name: Lint
run: npm run lint
- name: Test
run: npm test
- name: Build
run: npm run build
env:
VITE_API_BASE_URL: https://a301.api.tolelom.xyz
# ── 2. Docker 빌드 & Gitea 레지스트리 푸시 (main 머지 시만) ───────────────
docker:
needs: test
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: git.tolelom.xyz
username: ${{ github.actor }}
password: ${{ secrets.GITEA_TOKEN }}
- uses: docker/build-push-action@v5
with:
context: .
push: true
tags: git.tolelom.xyz/${{ github.repository_owner }}/a301-web:latest
platforms: linux/arm64
build-args: |
VITE_API_BASE_URL=https://a301.api.tolelom.xyz
cache-from: type=gha
cache-to: type=gha,mode=max
# ── 3. 서버 배포 ──────────────────────────────────────────────────────────
deploy:
needs: docker
runs-on: ubuntu-latest
steps:
- uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
export PATH=$PATH:/usr/local/bin:/opt/homebrew/bin:$HOME/.docker/bin
cd ~/server
docker compose pull web
docker compose up -d web

View File

@@ -3,6 +3,9 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="One of the plans — 멀티플레이어 보스 레이드 게임 플랫폼">
<meta property="og:title" content="One of the plans">
<meta property="og:description" content="One of the plans — 멀티플레이어 보스 레이드 게임 플랫폼">
<title>One of the plans</title> <title>One of the plans</title>
</head> </head>
<body> <body>

View File

@@ -2,6 +2,7 @@ import { BrowserRouter, Routes, Route, Navigate, useNavigate } from 'react-route
import { useEffect, useRef } from 'react'; import { useEffect, useRef } from 'react';
import { AuthProvider } from './context/AuthContext'; import { AuthProvider } from './context/AuthContext';
import { ToastProvider } from './components/toast/ToastProvider'; import { ToastProvider } from './components/toast/ToastProvider';
import { ConfirmProvider } from './components/confirm/ConfirmProvider';
import { useAuth } from './context/useAuth'; import { useAuth } from './context/useAuth';
import ErrorBoundary from './components/ErrorBoundary'; import ErrorBoundary from './components/ErrorBoundary';
import LoginPage from './pages/LoginPage'; import LoginPage from './pages/LoginPage';
@@ -67,7 +68,9 @@ export default function App() {
<BrowserRouter> <BrowserRouter>
<AuthProvider> <AuthProvider>
<ToastProvider> <ToastProvider>
<AppRoutes /> <ConfirmProvider>
<AppRoutes />
</ConfirmProvider>
</ToastProvider> </ToastProvider>
</AuthProvider> </AuthProvider>
</BrowserRouter> </BrowserRouter>

View File

@@ -1,5 +1,14 @@
const BASE = import.meta.env.VITE_API_BASE_URL || ''; const BASE = import.meta.env.VITE_API_BASE_URL || '';
/** 네트워크 에러 메시지를 한국어로 변환 */
function localizeError(message) {
if (typeof message !== 'string') return message;
if (message.includes('Failed to fetch')) return '서버에 연결할 수 없습니다';
if (message.includes('NetworkError')) return '네트워크에 연결할 수 없습니다';
if (message.includes('AbortError') || message === 'The user aborted a request.') return '요청 시간이 초과되었습니다';
return message;
}
// 동시 401 발생 시 refresh를 한 번만 실행하기 위한 Promise 공유 // 동시 401 발생 시 refresh를 한 번만 실행하기 위한 Promise 공유
let refreshingPromise = null; let refreshingPromise = null;
@@ -26,19 +35,34 @@ export async function tryRefresh() {
} }
async function doFetch(path, options, token) { async function doFetch(path, options, token) {
const headers = { 'Content-Type': 'application/json', ...options.headers }; const headers = { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', ...options.headers };
if (token) headers['Authorization'] = `Bearer ${token}`; if (token) headers['Authorization'] = `Bearer ${token}`;
return fetch(BASE + path, { ...options, headers, credentials: 'include' }); return fetch(BASE + path, { ...options, headers, credentials: 'include' });
} }
/** 에러 코드별 기본 한국어 메시지 */
const ERROR_MESSAGES = {
bad_request: '잘못된 요청입니다',
unauthorized: '로그인이 필요합니다',
forbidden: '권한이 없습니다',
not_found: '요청한 리소스를 찾을 수 없습니다',
conflict: '이미 존재하는 항목입니다',
tx_failed: '트랜잭션 처리에 실패했습니다',
rate_limited: '요청이 너무 많습니다. 잠시 후 다시 시도해주세요',
internal_error: '서버 오류가 발생했습니다',
};
async function parseError(res) { async function parseError(res) {
let message = res.statusText; let message = res.statusText;
let code;
try { try {
const body = await res.json(); const body = await res.json();
if (body.error) message = body.error; code = body.error;
message = body.message || ERROR_MESSAGES[code] || message;
} catch { /* 응답 바디 파싱 실패 시 statusText 사용 */ } } catch { /* 응답 바디 파싱 실패 시 statusText 사용 */ }
const err = new Error(message); const err = new Error(message);
err.status = res.status; err.status = res.status;
err.code = code;
return err; return err;
} }
@@ -60,6 +84,7 @@ export async function apiFetch(path, options = {}, _retryCount = 0) {
await delay(1000 * (_retryCount + 1)); await delay(1000 * (_retryCount + 1));
return apiFetch(path, options, _retryCount + 1); return apiFetch(path, options, _retryCount + 1);
} }
e.message = localizeError(e.message);
throw e; throw e;
} }
@@ -115,6 +140,7 @@ export function apiUpload(path, file, onProgress) {
xhr.withCredentials = true; xhr.withCredentials = true;
if (token) xhr.setRequestHeader('Authorization', `Bearer ${token}`); if (token) xhr.setRequestHeader('Authorization', `Bearer ${token}`);
xhr.setRequestHeader('Content-Type', 'application/octet-stream'); xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.upload.onprogress = (event) => { xhr.upload.onprogress = (event) => {
if (event.lengthComputable && onProgress) { if (event.lengthComputable && onProgress) {
@@ -123,7 +149,7 @@ export function apiUpload(path, file, onProgress) {
}; };
xhr.onload = () => resolve(xhr); xhr.onload = () => resolve(xhr);
xhr.onerror = () => reject(new Error('네트워크 오류가 발생했습니다.')); xhr.onerror = () => reject(new Error('서버에 연결할 수 없습니다'));
xhr.send(file); xhr.send(file);
}); });
} }

View File

@@ -36,7 +36,7 @@ export default function DownloadSection() {
// JWT를 URL에 직접 노출하지 않고, 일회용 티켓을 발급받아 전달 // JWT를 URL에 직접 노출하지 않고, 일회용 티켓을 발급받아 전달
try { try {
const ticket = await createLaunchTicket(); const ticket = await createLaunchTicket();
window.location.href = 'a301://launch?ticket=' + encodeURIComponent(ticket); window.location.href = 'a301://launch?token=' + encodeURIComponent(ticket);
} catch { } catch {
// 티켓 발급 실패 시 로그인 유도 // 티켓 발급 실패 시 로그인 유도
navigate('/login'); navigate('/login');

View File

@@ -0,0 +1,99 @@
.error-boundary {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
padding: 2rem;
background-color: #2E2C2F;
}
.error-boundary-card {
text-align: center;
max-width: 440px;
padding: 40px 32px;
background: rgba(255, 255, 255, 0.03);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 16px;
}
.error-boundary-icon {
width: 56px;
height: 56px;
margin: 0 auto 20px;
border-radius: 50%;
background: rgba(229, 115, 115, 0.12);
color: rgba(229, 115, 115, 0.9);
font-size: 1.5rem;
font-weight: 700;
line-height: 56px;
}
.error-boundary-title {
font-size: 1.25rem;
font-weight: 700;
color: rgba(255, 255, 255, 0.9);
margin: 0 0 8px 0;
}
.error-boundary-desc {
font-size: 0.9rem;
color: rgba(255, 255, 255, 0.45);
margin: 0 0 20px 0;
}
.error-boundary-detail {
padding: 12px 16px;
background: rgba(255, 255, 255, 0.03);
border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: 8px;
margin-bottom: 24px;
text-align: left;
}
.error-boundary-type {
font-size: 0.75rem;
font-weight: 600;
color: rgba(229, 115, 115, 0.8);
text-transform: uppercase;
letter-spacing: 0.05em;
}
.error-boundary-message {
font-size: 0.85rem;
color: rgba(255, 255, 255, 0.6);
margin: 6px 0 0 0;
word-break: break-word;
font-family: monospace;
}
.error-boundary-actions {
display: flex;
gap: 8px;
justify-content: center;
}
.error-boundary-btn {
padding: 10px 24px;
border-radius: 6px;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
border: none;
transition: opacity 0.2s;
}
.error-boundary-btn:hover {
opacity: 0.85;
}
.error-boundary-btn-primary {
background: #BACDB0;
color: #2E2C2F;
font-weight: 600;
}
.error-boundary-btn-secondary {
background: transparent;
color: rgba(255, 255, 255, 0.5);
border: 1px solid rgba(255, 255, 255, 0.15);
}

View File

@@ -1,31 +1,54 @@
import { Component } from 'react'; import { Component } from 'react';
import './ErrorBoundary.css';
export default class ErrorBoundary extends Component { export default class ErrorBoundary extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { hasError: false }; this.state = { hasError: false, error: null };
} }
static getDerivedStateFromError() { static getDerivedStateFromError(error) {
return { hasError: true }; return { hasError: true, error };
} }
componentDidCatch(error, errorInfo) { componentDidCatch(error, errorInfo) {
console.error('Uncaught error:', error, errorInfo); console.error('Uncaught error:', error, errorInfo);
} }
handleRetry = () => {
this.setState({ hasError: false, error: null });
};
render() { render() {
if (this.state.hasError) { if (this.state.hasError) {
const { error } = this.state;
const errorType = error?.name || 'Error';
const errorMessage = error?.message || '알 수 없는 오류가 발생했습니다.';
return ( return (
<div style={{ padding: '2rem', textAlign: 'center', color: '#ccc' }}> <div className="error-boundary">
<h2>문제가 발생했습니다</h2> <div className="error-boundary-card">
<p>페이지를 새로고침하거나 잠시 다시 시도해주세요.</p> <div className="error-boundary-icon">!</div>
<button onClick={() => window.location.reload()} style={{ marginTop: '1rem', padding: '0.5rem 1rem', cursor: 'pointer' }}> <h2 className="error-boundary-title">문제가 발생했습니다</h2>
새로고침 <p className="error-boundary-desc">
</button> 예기치 않은 오류로 페이지를 표시할 없습니다.
</p>
<div className="error-boundary-detail">
<span className="error-boundary-type">{errorType}</span>
<p className="error-boundary-message">{errorMessage}</p>
</div>
<div className="error-boundary-actions">
<button className="error-boundary-btn error-boundary-btn-primary" onClick={this.handleRetry}>
다시 시도
</button>
<button className="error-boundary-btn error-boundary-btn-secondary" onClick={() => window.location.reload()}>
새로고침
</button>
</div>
</div>
</div> </div>
); );
} }
return this.props.children; return this.props.children;
} }
} }

View File

@@ -1,10 +1,10 @@
.admin-section { .section {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 24px; gap: 24px;
} }
.admin-section-title { .sectionTitle {
font-size: 1.1rem; font-size: 1.1rem;
font-weight: 700; font-weight: 700;
color: rgba(255, 255, 255, 0.9); color: rgba(255, 255, 255, 0.9);
@@ -14,7 +14,7 @@
} }
/* Form */ /* Form */
.admin-form { .form {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 12px; gap: 12px;
@@ -24,18 +24,18 @@
border-radius: 10px; border-radius: 10px;
} }
.admin-field { .field {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 6px; gap: 6px;
} }
.admin-label { .label {
font-size: 0.8rem; font-size: 0.8rem;
color: rgba(255, 255, 255, 0.5); color: rgba(255, 255, 255, 0.5);
} }
.admin-input { .input {
padding: 10px 14px; padding: 10px 14px;
background: rgba(255, 255, 255, 0.05); background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(186, 205, 176, 0.15); border: 1px solid rgba(186, 205, 176, 0.15);
@@ -46,11 +46,11 @@
transition: border-color 0.2s; transition: border-color 0.2s;
} }
.admin-input:focus { .input:focus {
border-color: rgba(186, 205, 176, 0.5); border-color: rgba(186, 205, 176, 0.5);
} }
.admin-textarea { .textarea {
padding: 10px 14px; padding: 10px 14px;
background: rgba(255, 255, 255, 0.05); background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(186, 205, 176, 0.15); border: 1px solid rgba(186, 205, 176, 0.15);
@@ -63,24 +63,24 @@
font-family: inherit; font-family: inherit;
} }
.admin-textarea:focus { .textarea:focus {
border-color: rgba(186, 205, 176, 0.5); border-color: rgba(186, 205, 176, 0.5);
} }
.admin-error { .error {
font-size: 0.85rem; font-size: 0.85rem;
color: rgba(229, 115, 115, 0.9); color: rgba(229, 115, 115, 0.9);
margin: 0; margin: 0;
} }
.admin-form-actions { .formActions {
display: flex; display: flex;
gap: 8px; gap: 8px;
margin-top: 4px; margin-top: 4px;
} }
/* Buttons */ /* Buttons */
.btn-admin-primary { .btnPrimary {
padding: 10px 24px; padding: 10px 24px;
background: #BACDB0; background: #BACDB0;
color: #2E2C2F; color: #2E2C2F;
@@ -92,10 +92,10 @@
transition: opacity 0.2s; transition: opacity 0.2s;
} }
.btn-admin-primary:hover { opacity: 0.9; } .btnPrimary:hover { opacity: 0.9; }
.btn-admin-primary:disabled { opacity: 0.5; cursor: not-allowed; } .btnPrimary:disabled { opacity: 0.5; cursor: not-allowed; }
.btn-admin-secondary { .btnSecondary {
padding: 10px 20px; padding: 10px 20px;
background: transparent; background: transparent;
color: rgba(255, 255, 255, 0.5); color: rgba(255, 255, 255, 0.5);
@@ -106,12 +106,12 @@
transition: background 0.2s; transition: background 0.2s;
} }
.btn-admin-secondary:hover { .btnSecondary:hover {
background: rgba(255, 255, 255, 0.05); background: rgba(255, 255, 255, 0.05);
} }
/* List */ /* List */
.admin-list { .list {
list-style: none; list-style: none;
margin: 0; margin: 0;
padding: 0; padding: 0;
@@ -120,7 +120,7 @@
gap: 4px; gap: 4px;
} }
.admin-list-item { .listItem {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
@@ -130,14 +130,14 @@
border-radius: 8px; border-radius: 8px;
} }
.admin-list-info { .listInfo {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 12px; gap: 12px;
min-width: 0; min-width: 0;
} }
.admin-list-title { .listTitle {
font-size: 0.9rem; font-size: 0.9rem;
color: rgba(255, 255, 255, 0.85); color: rgba(255, 255, 255, 0.85);
white-space: nowrap; white-space: nowrap;
@@ -145,19 +145,19 @@
text-overflow: ellipsis; text-overflow: ellipsis;
} }
.admin-list-date { .listDate {
font-size: 0.8rem; font-size: 0.8rem;
color: rgba(255, 255, 255, 0.3); color: rgba(255, 255, 255, 0.3);
flex-shrink: 0; flex-shrink: 0;
} }
.admin-list-actions { .listActions {
display: flex; display: flex;
gap: 8px; gap: 8px;
flex-shrink: 0; flex-shrink: 0;
} }
.btn-admin-edit { .btnEdit {
padding: 6px 14px; padding: 6px 14px;
background: transparent; background: transparent;
color: rgba(186, 205, 176, 0.8); color: rgba(186, 205, 176, 0.8);
@@ -168,11 +168,11 @@
transition: background 0.2s; transition: background 0.2s;
} }
.btn-admin-edit:hover { .btnEdit:hover {
background: rgba(186, 205, 176, 0.08); background: rgba(186, 205, 176, 0.08);
} }
.btn-admin-delete { .btnDelete {
padding: 6px 14px; padding: 6px 14px;
background: transparent; background: transparent;
color: rgba(229, 115, 115, 0.8); color: rgba(229, 115, 115, 0.8);
@@ -183,25 +183,25 @@
transition: background 0.2s; transition: background 0.2s;
} }
.btn-admin-delete:hover { .btnDelete:hover {
background: rgba(229, 115, 115, 0.08); background: rgba(229, 115, 115, 0.08);
} }
/* Deploy block */ /* Deploy block */
.admin-deploy-block { .deployBlock {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 8px; gap: 8px;
} }
.admin-deploy-header { .deployHeader {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 12px; gap: 12px;
flex-wrap: wrap; flex-wrap: wrap;
} }
.admin-deploy-label { .deployLabel {
font-size: 0.8rem; font-size: 0.8rem;
font-weight: 600; font-weight: 600;
color: rgba(255, 255, 255, 0.5); color: rgba(255, 255, 255, 0.5);
@@ -210,32 +210,32 @@
} }
/* File input */ /* File input */
.admin-input-file { .inputFile {
padding: 8px 0; padding: 8px 0;
color: rgba(255, 255, 255, 0.7); color: rgba(255, 255, 255, 0.7);
font-size: 0.875rem; font-size: 0.875rem;
cursor: pointer; cursor: pointer;
} }
.admin-input-file:disabled { .inputFile:disabled {
opacity: 0.4; opacity: 0.4;
cursor: not-allowed; cursor: not-allowed;
} }
/* Field hint */ /* Field hint */
.admin-field-hint { .fieldHint {
font-size: 0.75rem; font-size: 0.75rem;
color: rgba(255, 255, 255, 0.3); color: rgba(255, 255, 255, 0.3);
} }
/* Upload progress */ /* Upload progress */
.admin-upload-progress { .uploadProgress {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 10px; gap: 10px;
} }
.admin-upload-bar { .uploadBar {
flex: 1; flex: 1;
height: 6px; height: 6px;
background: #BACDB0; background: #BACDB0;
@@ -243,7 +243,7 @@
transition: width 0.2s; transition: width 0.2s;
} }
.admin-upload-pct { .uploadPct {
font-size: 0.8rem; font-size: 0.8rem;
color: rgba(255, 255, 255, 0.5); color: rgba(255, 255, 255, 0.5);
min-width: 36px; min-width: 36px;
@@ -251,7 +251,7 @@
} }
/* Current build info */ /* Current build info */
.admin-current-build { .currentBuild {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 8px; gap: 8px;
@@ -261,13 +261,13 @@
border-radius: 8px; border-radius: 8px;
} }
.admin-meta-row { .metaRow {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: 6px; gap: 6px;
} }
.admin-meta-item { .metaItem {
font-size: 0.78rem; font-size: 0.78rem;
color: rgba(186, 205, 176, 0.8); color: rgba(186, 205, 176, 0.8);
background: rgba(186, 205, 176, 0.08); background: rgba(186, 205, 176, 0.08);
@@ -276,32 +276,102 @@
border: 1px solid rgba(186, 205, 176, 0.15); border: 1px solid rgba(186, 205, 176, 0.15);
} }
.admin-meta-hash { .metaHash {
composes: metaItem;
font-family: monospace; font-family: monospace;
cursor: help; cursor: help;
} }
/* Role badge */ /* Role badge */
.admin-list-empty { .listEmpty {
font-size: 0.9rem; font-size: 0.9rem;
color: rgba(255, 255, 255, 0.35); color: rgba(255, 255, 255, 0.35);
padding: 12px 16px; padding: 12px 16px;
margin: 0; margin: 0;
} }
.admin-role-badge { .roleBadge {
font-size: 0.7rem; font-size: 0.7rem;
padding: 2px 8px; padding: 2px 8px;
border-radius: 4px; border-radius: 4px;
font-weight: 600; font-weight: 600;
} }
.admin-role-badge.admin { .roleBadgeAdmin {
composes: roleBadge;
background: rgba(186, 205, 176, 0.15); background: rgba(186, 205, 176, 0.15);
color: #BACDB0; color: #BACDB0;
} }
.admin-role-badge.user { .roleBadgeUser {
composes: roleBadge;
background: rgba(255, 255, 255, 0.08); background: rgba(255, 255, 255, 0.08);
color: rgba(255, 255, 255, 0.45); color: rgba(255, 255, 255, 0.45);
} }
.errorBlock {
display: flex;
flex-direction: column;
gap: 8px;
}
.loading {
font-size: 0.9rem;
color: rgba(255, 255, 255, 0.35);
padding: 12px 16px;
margin: 0;
}
/* Mobile responsive */
@media (max-width: 768px) {
.form {
padding: 16px 12px;
}
.input,
.textarea {
width: 100%;
box-sizing: border-box;
}
.listItem {
flex-direction: column;
align-items: flex-start;
gap: 8px;
padding: 10px 12px;
}
.listInfo {
width: 100%;
}
.listActions {
width: 100%;
justify-content: flex-end;
}
.formActions {
flex-direction: column;
}
.formActions button {
width: 100%;
min-height: 44px;
}
.btnPrimary,
.btnSecondary,
.btnEdit,
.btnDelete {
min-height: 44px;
}
.metaRow {
flex-direction: column;
}
.deployHeader {
flex-direction: column;
align-items: flex-start;
}
}

View File

@@ -1,11 +1,12 @@
// TODO: Add tests for CRUD operations (create, update, delete announcements)
import { useState, useEffect, useCallback } from 'react'; import { useState, useEffect, useCallback } from 'react';
import { getAnnouncements, createAnnouncement, updateAnnouncement, deleteAnnouncement } from '../../api/announcements'; import { getAnnouncements, createAnnouncement, updateAnnouncement, deleteAnnouncement } from '../../api/announcements';
import { useToast } from '../toast/useToast'; import { useToast } from '../toast/useToast';
import './AdminCommon.css'; import { useConfirm } from '../confirm/useConfirm';
import s from './AdminCommon.module.css';
export default function AnnouncementAdmin() { export default function AnnouncementAdmin() {
const toast = useToast(); const toast = useToast();
const confirm = useConfirm();
const [list, setList] = useState([]); const [list, setList] = useState([]);
const [form, setForm] = useState({ title: '', content: '' }); const [form, setForm] = useState({ title: '', content: '' });
const [editingId, setEditingId] = useState(null); const [editingId, setEditingId] = useState(null);
@@ -58,8 +59,7 @@ export default function AnnouncementAdmin() {
}; };
const handleDelete = async (id) => { const handleDelete = async (id) => {
// TODO: Replace window.confirm() with a custom confirmation modal for consistent UI if (!(await confirm('삭제하시겠습니까?'))) return;
if (!confirm('삭제하시겠습니까?')) return;
try { try {
await deleteAnnouncement(id); await deleteAnnouncement(id);
toast.success('공지사항이 삭제되었습니다.'); toast.success('공지사항이 삭제되었습니다.');
@@ -77,30 +77,30 @@ export default function AnnouncementAdmin() {
if (fetchLoading) { if (fetchLoading) {
return ( return (
<div className="admin-section"> <div className={s.section}>
<h2 className="admin-section-title">공지사항 관리</h2> <h2 className={s.sectionTitle}>공지사항 관리</h2>
<p className="admin-loading">불러오는 ...</p> <p className={s.loading}>불러오는 ...</p>
</div> </div>
); );
} }
if (fetchError) { if (fetchError) {
return ( return (
<div className="admin-section"> <div className={s.section}>
<h2 className="admin-section-title">공지사항 관리</h2> <h2 className={s.sectionTitle}>공지사항 관리</h2>
<p className="admin-error">{fetchError}</p> <p className={s.error}>{fetchError}</p>
<button className="btn-admin-secondary" onClick={load}>다시 시도</button> <button className={s.btnSecondary} onClick={load}>다시 시도</button>
</div> </div>
); );
} }
return ( return (
<div className="admin-section"> <div className={s.section}>
<h2 className="admin-section-title">공지사항 관리</h2> <h2 className={s.sectionTitle}>공지사항 관리</h2>
<form className="admin-form" onSubmit={handleSubmit}> <form className={s.form} onSubmit={handleSubmit}>
<input <input
className="admin-input" className={s.input}
placeholder="제목" placeholder="제목"
value={form.title} value={form.title}
onChange={(e) => setForm({ ...form, title: e.target.value })} onChange={(e) => setForm({ ...form, title: e.target.value })}
@@ -108,7 +108,7 @@ export default function AnnouncementAdmin() {
aria-label="공지사항 제목" aria-label="공지사항 제목"
/> />
<textarea <textarea
className="admin-textarea" className={s.textarea}
placeholder="내용" placeholder="내용"
rows={4} rows={4}
value={form.content} value={form.content}
@@ -116,29 +116,29 @@ export default function AnnouncementAdmin() {
maxLength={10000} maxLength={10000}
aria-label="공지사항 내용" aria-label="공지사항 내용"
/> />
{error && <p className="admin-error">{error}</p>} {error && <p className={s.error}>{error}</p>}
<div className="admin-form-actions"> <div className={s.formActions}>
<button className="btn-admin-primary" type="submit" disabled={loading}> <button className={s.btnPrimary} type="submit" disabled={loading}>
{editingId ? '수정 완료' : '공지 등록'} {editingId ? '수정 완료' : '공지 등록'}
</button> </button>
{editingId && ( {editingId && (
<button className="btn-admin-secondary" type="button" onClick={handleCancel}> <button className={s.btnSecondary} type="button" onClick={handleCancel}>
취소 취소
</button> </button>
)} )}
</div> </div>
</form> </form>
<ul className="admin-list"> <ul className={s.list}>
{list.map((item) => ( {list.map((item) => (
<li key={item.id} className="admin-list-item"> <li key={item.id} className={s.listItem}>
<div className="admin-list-info"> <div className={s.listInfo}>
<span className="admin-list-title">{item.title}</span> <span className={s.listTitle}>{item.title}</span>
<span className="admin-list-date">{item.createdAt?.slice(0, 10)}</span> <span className={s.listDate}>{item.createdAt?.slice(0, 10)}</span>
</div> </div>
<div className="admin-list-actions"> <div className={s.listActions}>
<button className="btn-admin-edit" onClick={() => handleEdit(item)}>수정</button> <button className={s.btnEdit} onClick={() => handleEdit(item)}>수정</button>
<button className="btn-admin-delete" onClick={() => handleDelete(item.id)}>삭제</button> <button className={s.btnDelete} onClick={() => handleDelete(item.id)}>삭제</button>
</div> </div>
</li> </li>
))} ))}

View File

@@ -0,0 +1,187 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import AnnouncementAdmin from './AnnouncementAdmin';
// Mock APIs
const mockGetAnnouncements = vi.fn();
const mockCreateAnnouncement = vi.fn();
const mockUpdateAnnouncement = vi.fn();
const mockDeleteAnnouncement = vi.fn();
vi.mock('../../api/announcements', () => ({
getAnnouncements: (...args) => mockGetAnnouncements(...args),
createAnnouncement: (...args) => mockCreateAnnouncement(...args),
updateAnnouncement: (...args) => mockUpdateAnnouncement(...args),
deleteAnnouncement: (...args) => mockDeleteAnnouncement(...args),
}));
// Mock toast
const mockToast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() };
vi.mock('../toast/useToast', () => ({
useToast: () => mockToast,
}));
// Mock confirm — resolves true by default
let mockConfirmResult = true;
vi.mock('../confirm/useConfirm', () => ({
useConfirm: () => () => Promise.resolve(mockConfirmResult),
}));
const SAMPLE_LIST = [
{ id: 1, title: '점검 안내', content: '서버 점검합니다.', createdAt: '2026-03-10T00:00:00Z' },
{ id: 2, title: '업데이트', content: '새 버전 출시.', createdAt: '2026-03-12T00:00:00Z' },
];
describe('AnnouncementAdmin', () => {
beforeEach(() => {
vi.clearAllMocks();
mockConfirmResult = true;
mockGetAnnouncements.mockResolvedValue(SAMPLE_LIST);
});
it('renders announcements after loading', async () => {
render(<AnnouncementAdmin />);
expect(screen.getByText('불러오는 중...')).toBeInTheDocument();
expect(await screen.findByText('점검 안내')).toBeInTheDocument();
expect(screen.getByText('업데이트')).toBeInTheDocument();
});
it('shows error when fetch fails', async () => {
mockGetAnnouncements.mockRejectedValueOnce(new Error('fail'));
render(<AnnouncementAdmin />);
expect(await screen.findByText('공지사항을 불러오지 못했습니다.')).toBeInTheDocument();
expect(screen.getByText('다시 시도')).toBeInTheDocument();
});
it('retries loading when "다시 시도" is clicked', async () => {
mockGetAnnouncements.mockRejectedValueOnce(new Error('fail'));
render(<AnnouncementAdmin />);
await screen.findByText('다시 시도');
mockGetAnnouncements.mockResolvedValueOnce(SAMPLE_LIST);
fireEvent.click(screen.getByText('다시 시도'));
expect(await screen.findByText('점검 안내')).toBeInTheDocument();
});
describe('create', () => {
it('creates a new announcement', async () => {
mockCreateAnnouncement.mockResolvedValueOnce({});
render(<AnnouncementAdmin />);
await screen.findByText('점검 안내');
fireEvent.change(screen.getByPlaceholderText('제목'), { target: { value: '새 공지' } });
fireEvent.change(screen.getByPlaceholderText('내용'), { target: { value: '새 내용입니다.' } });
fireEvent.click(screen.getByRole('button', { name: '공지 등록' }));
await waitFor(() => {
expect(mockCreateAnnouncement).toHaveBeenCalledWith('새 공지', '새 내용입니다.');
});
expect(mockToast.success).toHaveBeenCalledWith('공지사항이 등록되었습니다.');
});
it('shows validation error when fields are empty', async () => {
render(<AnnouncementAdmin />);
await screen.findByText('점검 안내');
fireEvent.click(screen.getByRole('button', { name: '공지 등록' }));
expect(await screen.findByText('제목과 내용을 모두 입력해주세요.')).toBeInTheDocument();
expect(mockCreateAnnouncement).not.toHaveBeenCalled();
});
it('shows toast on create failure', async () => {
mockCreateAnnouncement.mockRejectedValueOnce(new Error('서버 오류'));
render(<AnnouncementAdmin />);
await screen.findByText('점검 안내');
fireEvent.change(screen.getByPlaceholderText('제목'), { target: { value: '제목' } });
fireEvent.change(screen.getByPlaceholderText('내용'), { target: { value: '내용' } });
fireEvent.click(screen.getByRole('button', { name: '공지 등록' }));
await waitFor(() => {
expect(mockToast.error).toHaveBeenCalledWith('서버 오류');
});
});
});
describe('update', () => {
it('populates form on edit and submits update', async () => {
mockUpdateAnnouncement.mockResolvedValueOnce({});
render(<AnnouncementAdmin />);
await screen.findByText('점검 안내');
// Click edit on first item
const editButtons = screen.getAllByText('수정');
fireEvent.click(editButtons[0]);
// Form should be populated
expect(screen.getByPlaceholderText('제목')).toHaveValue('점검 안내');
expect(screen.getByPlaceholderText('내용')).toHaveValue('서버 점검합니다.');
expect(screen.getByRole('button', { name: '수정 완료' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '취소' })).toBeInTheDocument();
// Modify and submit
fireEvent.change(screen.getByPlaceholderText('제목'), { target: { value: '수정된 제목' } });
fireEvent.click(screen.getByRole('button', { name: '수정 완료' }));
await waitFor(() => {
expect(mockUpdateAnnouncement).toHaveBeenCalledWith(1, '수정된 제목', '서버 점검합니다.');
});
expect(mockToast.success).toHaveBeenCalledWith('공지사항이 수정되었습니다.');
});
it('cancels editing and clears form', async () => {
render(<AnnouncementAdmin />);
await screen.findByText('점검 안내');
const editButtons = screen.getAllByText('수정');
fireEvent.click(editButtons[0]);
expect(screen.getByPlaceholderText('제목')).toHaveValue('점검 안내');
fireEvent.click(screen.getByRole('button', { name: '취소' }));
expect(screen.getByPlaceholderText('제목')).toHaveValue('');
expect(screen.getByPlaceholderText('내용')).toHaveValue('');
expect(screen.getByRole('button', { name: '공지 등록' })).toBeInTheDocument();
});
});
describe('delete', () => {
it('deletes an announcement when confirmed', async () => {
mockDeleteAnnouncement.mockResolvedValueOnce({});
render(<AnnouncementAdmin />);
await screen.findByText('점검 안내');
const deleteButtons = screen.getAllByText('삭제');
fireEvent.click(deleteButtons[0]);
await waitFor(() => {
expect(mockDeleteAnnouncement).toHaveBeenCalledWith(1);
});
expect(mockToast.success).toHaveBeenCalledWith('공지사항이 삭제되었습니다.');
});
it('does not delete when confirm is cancelled', async () => {
mockConfirmResult = false;
render(<AnnouncementAdmin />);
await screen.findByText('점검 안내');
const deleteButtons = screen.getAllByText('삭제');
fireEvent.click(deleteButtons[0]);
await waitFor(() => {
expect(mockDeleteAnnouncement).not.toHaveBeenCalled();
});
});
it('shows toast on delete failure', async () => {
mockDeleteAnnouncement.mockRejectedValueOnce(new Error('삭제 실패'));
render(<AnnouncementAdmin />);
await screen.findByText('점검 안내');
const deleteButtons = screen.getAllByText('삭제');
fireEvent.click(deleteButtons[0]);
await waitFor(() => {
expect(mockToast.error).toHaveBeenCalledWith('삭제 실패');
});
});
});
});

View File

@@ -1,10 +1,11 @@
// TODO: Add tests for CRUD operations (load download info, upload launcher, upload game)
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { getDownloadInfo } from '../../api/download'; import { getDownloadInfo } from '../../api/download';
import { useToast } from '../toast/useToast';
import UploadForm from './UploadForm'; import UploadForm from './UploadForm';
import './AdminCommon.css'; import s from './AdminCommon.module.css';
export default function DownloadAdmin() { export default function DownloadAdmin() {
const toast = useToast();
const [info, setInfo] = useState(null); const [info, setInfo] = useState(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState(''); const [loadError, setLoadError] = useState('');
@@ -20,6 +21,7 @@ export default function DownloadAdmin() {
.catch((err) => { .catch((err) => {
console.error('다운로드 정보 로드 실패:', err); console.error('다운로드 정보 로드 실패:', err);
setLoadError('배포 정보를 불러올 수 없습니다.'); setLoadError('배포 정보를 불러올 수 없습니다.');
toast.error('배포 정보를 불러올 수 없습니다.');
}) })
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}; };
@@ -29,34 +31,34 @@ export default function DownloadAdmin() {
if (loading) { if (loading) {
return ( return (
<div className="admin-section"> <div className={s.section}>
<h2 className="admin-section-title">게임 배포 관리</h2> <h2 className={s.sectionTitle}>게임 배포 관리</h2>
<p className="admin-loading">불러오는 ...</p> <p className={s.loading}>불러오는 ...</p>
</div> </div>
); );
} }
if (loadError) { if (loadError) {
return ( return (
<div className="admin-section"> <div className={s.section}>
<h2 className="admin-section-title">게임 배포 관리</h2> <h2 className={s.sectionTitle}>게임 배포 관리</h2>
<p className="admin-error">{loadError}</p> <p className={s.error}>{loadError}</p>
<button className="btn-admin-secondary" onClick={load}>다시 시도</button> <button className={s.btnSecondary} onClick={load}>다시 시도</button>
</div> </div>
); );
} }
return ( return (
<div className="admin-section"> <div className={s.section}>
<h2 className="admin-section-title">게임 배포 관리</h2> <h2 className={s.sectionTitle}>게임 배포 관리</h2>
{/* 런처 섹션 */} {/* 런처 섹션 */}
<div className="admin-deploy-block"> <div className={s.deployBlock}>
<div className="admin-deploy-header"> <div className={s.deployHeader}>
<span className="admin-deploy-label">런처</span> <span className={s.deployLabel}>런처</span>
{info?.launcherUrl && ( {info?.launcherUrl && (
<div className="admin-meta-row"> <div className={s.metaRow}>
{info.launcherSize && <span className="admin-meta-item">{info.launcherSize}</span>} {info.launcherSize && <span className={s.metaItem}>{info.launcherSize}</span>}
</div> </div>
)} )}
</div> </div>
@@ -70,16 +72,16 @@ export default function DownloadAdmin() {
</div> </div>
{/* 게임 섹션 */} {/* 게임 섹션 */}
<div className="admin-deploy-block"> <div className={s.deployBlock}>
<div className="admin-deploy-header"> <div className={s.deployHeader}>
<span className="admin-deploy-label">게임</span> <span className={s.deployLabel}>게임</span>
{info?.url && ( {info?.url && (
<div className="admin-meta-row"> <div className={s.metaRow}>
{info.version && <span className="admin-meta-item">{info.version}</span>} {info.version && <span className={s.metaItem}>{info.version}</span>}
{info.fileName && <span className="admin-meta-item">{info.fileName}</span>} {info.fileName && <span className={s.metaItem}>{info.fileName}</span>}
{info.fileSize && <span className="admin-meta-item">{info.fileSize}</span>} {info.fileSize && <span className={s.metaItem}>{info.fileSize}</span>}
{info.fileHash && ( {info.fileHash && (
<span className="admin-meta-item admin-meta-hash" title={info.fileHash}> <span className={s.metaHash} title={info.fileHash}>
SHA256: {info.fileHash.slice(0, 12)}... SHA256: {info.fileHash.slice(0, 12)}...
</span> </span>
)} )}

View File

@@ -0,0 +1,85 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import DownloadAdmin from './DownloadAdmin';
// Mock APIs
const mockGetDownloadInfo = vi.fn();
vi.mock('../../api/download', () => ({
getDownloadInfo: (...args) => mockGetDownloadInfo(...args),
}));
// Mock apiUpload
const mockApiUpload = vi.fn();
vi.mock('../../api/client', () => ({
apiUpload: (...args) => mockApiUpload(...args),
}));
// Mock toast
const mockToast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() };
vi.mock('../toast/useToast', () => ({
useToast: () => mockToast,
}));
const SAMPLE_INFO = {
url: 'https://example.com/game.zip',
launcherUrl: 'https://example.com/launcher.exe',
version: 'v1.2.0',
fileName: 'game.zip',
fileSize: '512 MB',
fileHash: 'abc123def456abc123def456abc123def456abc123def456abc123def456abcd',
launcherSize: '8 MB',
};
describe('DownloadAdmin', () => {
beforeEach(() => {
vi.clearAllMocks();
mockGetDownloadInfo.mockResolvedValue(SAMPLE_INFO);
});
it('shows loading state then renders download info', async () => {
render(<DownloadAdmin />);
expect(screen.getByText('불러오는 중...')).toBeInTheDocument();
expect(await screen.findByText('v1.2.0')).toBeInTheDocument();
expect(screen.getByText('512 MB')).toBeInTheDocument();
expect(screen.getByText('game.zip')).toBeInTheDocument();
});
it('shows error when fetch fails', async () => {
mockGetDownloadInfo.mockRejectedValueOnce(new Error('fail'));
render(<DownloadAdmin />);
expect(await screen.findByText('배포 정보를 불러올 수 없습니다.')).toBeInTheDocument();
expect(screen.getByText('다시 시도')).toBeInTheDocument();
});
it('retries loading on "다시 시도" click', async () => {
mockGetDownloadInfo.mockRejectedValueOnce(new Error('fail'));
render(<DownloadAdmin />);
await screen.findByText('다시 시도');
mockGetDownloadInfo.mockResolvedValueOnce(SAMPLE_INFO);
fireEvent.click(screen.getByText('다시 시도'));
expect(await screen.findByText('v1.2.0')).toBeInTheDocument();
});
it('renders launcher and game upload sections', async () => {
render(<DownloadAdmin />);
await screen.findByText('v1.2.0');
expect(screen.getByText('launcher.exe')).toBeInTheDocument();
expect(screen.getByText(/게임 파일/)).toBeInTheDocument();
// Two upload buttons (both disabled without file selection)
const uploadButtons = screen.getAllByRole('button', { name: '업로드' });
expect(uploadButtons).toHaveLength(2);
uploadButtons.forEach((btn) => expect(btn).toBeDisabled());
});
it('displays launcher size', async () => {
render(<DownloadAdmin />);
await screen.findByText('8 MB');
});
it('displays SHA256 hash prefix', async () => {
render(<DownloadAdmin />);
expect(await screen.findByText(/SHA256: abc123def456/)).toBeInTheDocument();
});
});

View File

@@ -1,7 +1,10 @@
import { useState, useRef } from 'react'; import { useState, useRef } from 'react';
import { apiUpload } from '../../api/client'; import { apiUpload } from '../../api/client';
import { useToast } from '../toast/useToast';
import s from './AdminCommon.module.css';
export default function UploadForm({ title, hint, accept, endpoint, onSuccess }) { export default function UploadForm({ title, hint, accept, endpoint, onSuccess }) {
const toast = useToast();
const [file, setFile] = useState(null); const [file, setFile] = useState(null);
const [uploading, setUploading] = useState(false); const [uploading, setUploading] = useState(false);
const [progress, setProgress] = useState(0); const [progress, setProgress] = useState(0);
@@ -27,15 +30,32 @@ export default function UploadForm({ title, hint, accept, endpoint, onSuccess })
const { status, body } = await apiUpload(path, file, (p) => setProgress(p)); const { status, body } = await apiUpload(path, file, (p) => setProgress(p));
if (status >= 200 && status < 300) { if (status >= 200 && status < 300) {
onSuccess(body); onSuccess(body);
toast.success('업로드가 완료되었습니다.');
setFile(null); setFile(null);
if (fileInputRef.current) fileInputRef.current.value = ''; if (fileInputRef.current) fileInputRef.current.value = '';
setProgress(0); setProgress(0);
} else if (status === 413) {
const msg = '파일 크기가 너무 큽니다. 더 작은 파일을 선택해주세요.';
setError(msg);
toast.error(msg);
} else if (status === 409) {
const msg = '동일한 파일이 이미 존재합니다.';
setError(msg);
toast.error(msg);
} else if (status >= 500) {
const msg = '서버 오류가 발생했습니다. 잠시 후 다시 시도해주세요.';
setError(msg);
toast.error(msg);
} else { } else {
setError(body.error || '업로드에 실패했습니다.'); const msg = body.error || '업로드에 실패했습니다.';
setError(msg);
toast.error(msg);
setProgress(0); setProgress(0);
} }
} catch { } catch {
setError('네트워크 오류가 발생했습니다.'); const msg = '네트워크 오류가 발생했습니다.';
setError(msg);
toast.error(msg);
setProgress(0); setProgress(0);
} finally { } finally {
setUploading(false); setUploading(false);
@@ -43,31 +63,31 @@ export default function UploadForm({ title, hint, accept, endpoint, onSuccess })
}; };
return ( return (
<form className="admin-form" onSubmit={handleUpload}> <form className={s.form} onSubmit={handleUpload}>
<div className="admin-field"> <div className={s.field}>
<label className="admin-label">{title}</label> <label className={s.label}>{title}</label>
<input <input
ref={fileInputRef} ref={fileInputRef}
type="file" type="file"
accept={accept} accept={accept}
className="admin-input-file" className={s.inputFile}
onChange={handleFileChange} onChange={handleFileChange}
disabled={uploading} disabled={uploading}
/> />
<span className="admin-field-hint">{hint}</span> <span className={s.fieldHint}>{hint}</span>
</div> </div>
{uploading && ( {uploading && (
<div className="admin-upload-progress"> <div className={s.uploadProgress}>
<div className="admin-upload-bar" style={{ width: `${progress}%` }} /> <div className={s.uploadBar} style={{ width: `${progress}%` }} />
<span className="admin-upload-pct">{progress}%</span> <span className={s.uploadPct}>{progress}%</span>
</div> </div>
)} )}
{error && <p className="admin-error">{error}</p>} {error && <p className={s.error}>{error}</p>}
<div className="admin-form-actions"> <div className={s.formActions}>
<button className="btn-admin-primary" type="submit" disabled={uploading || !file}> <button className={s.btnPrimary} type="submit" disabled={uploading || !file}>
{uploading ? `업로드 중... (${progress}%)` : '업로드'} {uploading ? `업로드 중... (${progress}%)` : '업로드'}
</button> </button>
</div> </div>

View File

@@ -1,9 +1,9 @@
// TODO: Add tests for CRUD operations (list users, update role, delete user)
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { getUsers, updateUserRole, deleteUser } from '../../api/users'; import { getUsers, updateUserRole, deleteUser } from '../../api/users';
import { useAuth } from '../../context/useAuth'; import { useAuth } from '../../context/useAuth';
import { useToast } from '../toast/useToast'; import { useToast } from '../toast/useToast';
import './AdminCommon.css'; import { useConfirm } from '../confirm/useConfirm';
import s from './AdminCommon.module.css';
export default function UserAdmin() { export default function UserAdmin() {
const [users, setUsers] = useState([]); const [users, setUsers] = useState([]);
@@ -11,6 +11,7 @@ export default function UserAdmin() {
const [fetchError, setFetchError] = useState(false); const [fetchError, setFetchError] = useState(false);
const { user: me } = useAuth(); const { user: me } = useAuth();
const toast = useToast(); const toast = useToast();
const confirm = useConfirm();
const load = () => { const load = () => {
setLoading(true); setLoading(true);
@@ -28,8 +29,7 @@ export default function UserAdmin() {
const handleRoleToggle = async (u) => { const handleRoleToggle = async (u) => {
const newRole = u.role === 'admin' ? 'user' : 'admin'; const newRole = u.role === 'admin' ? 'user' : 'admin';
// TODO: Replace window.confirm() with a custom confirmation modal for consistent UI if (!(await confirm(`${u.username}의 권한을 ${newRole}로 변경하시겠습니까?`))) return;
if (!confirm(`${u.username}의 권한을 ${newRole}로 변경하시겠습니까?`)) return;
try { try {
await updateUserRole(u.id, newRole); await updateUserRole(u.id, newRole);
toast.success(`${u.username}의 권한이 ${newRole}로 변경되었습니다.`); toast.success(`${u.username}의 권한이 ${newRole}로 변경되었습니다.`);
@@ -40,8 +40,7 @@ export default function UserAdmin() {
}; };
const handleDelete = async (u) => { const handleDelete = async (u) => {
// TODO: Replace window.confirm() with a custom confirmation modal for consistent UI if (!(await confirm(`${u.username} 계정을 삭제하시겠습니까?`))) return;
if (!confirm(`${u.username} 계정을 삭제하시겠습니까?`)) return;
try { try {
await deleteUser(u.id); await deleteUser(u.id);
toast.success(`${u.username} 계정이 삭제되었습니다.`); toast.success(`${u.username} 계정이 삭제되었습니다.`);
@@ -52,29 +51,29 @@ export default function UserAdmin() {
}; };
return ( return (
<div className="admin-section"> <div className={s.section}>
<h2 className="admin-section-title">유저 관리</h2> <h2 className={s.sectionTitle}>유저 관리</h2>
{fetchError && ( {fetchError && (
<div className="admin-error-block"> <div className={s.errorBlock}>
<p className="admin-error">유저 목록을 불러올 없습니다.</p> <p className={s.error}>유저 목록을 불러올 없습니다.</p>
<button className="btn-admin-secondary" onClick={load}>다시 시도</button> <button className={s.btnSecondary} onClick={load}>다시 시도</button>
</div> </div>
)} )}
{loading && <p className="admin-list-empty">불러오는 ...</p>} {loading && <p className={s.listEmpty}>불러오는 ...</p>}
{!loading && users.length === 0 && <p className="admin-list-empty">등록된 유저가 없습니다.</p>} {!loading && users.length === 0 && <p className={s.listEmpty}>등록된 유저가 없습니다.</p>}
<ul className="admin-list"> <ul className={s.list}>
{users.map((u) => ( {users.map((u) => (
<li key={u.id} className="admin-list-item"> <li key={u.id} className={s.listItem}>
<div className="admin-list-info"> <div className={s.listInfo}>
<span className="admin-list-title">{u.username}</span> <span className={s.listTitle}>{u.username}</span>
<span className={`admin-role-badge ${u.role}`}>{u.role}</span> <span className={u.role === 'admin' ? s.roleBadgeAdmin : s.roleBadgeUser}>{u.role}</span>
</div> </div>
{u.username !== me?.username && ( {u.username !== me?.username && (
<div className="admin-list-actions"> <div className={s.listActions}>
<button className="btn-admin-edit" onClick={() => handleRoleToggle(u)}> <button className={s.btnEdit} onClick={() => handleRoleToggle(u)}>
{u.role === 'admin' ? '일반으로' : '관리자로'} {u.role === 'admin' ? '일반으로' : '관리자로'}
</button> </button>
<button className="btn-admin-delete" onClick={() => handleDelete(u)}>삭제</button> <button className={s.btnDelete} onClick={() => handleDelete(u)}>삭제</button>
</div> </div>
)} )}
</li> </li>

View File

@@ -0,0 +1,161 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import UserAdmin from './UserAdmin';
// Mock APIs
const mockGetUsers = vi.fn();
const mockUpdateUserRole = vi.fn();
const mockDeleteUser = vi.fn();
vi.mock('../../api/users', () => ({
getUsers: (...args) => mockGetUsers(...args),
updateUserRole: (...args) => mockUpdateUserRole(...args),
deleteUser: (...args) => mockDeleteUser(...args),
}));
// Mock useAuth — current user is "admin1"
vi.mock('../../context/useAuth', () => ({
useAuth: () => ({ user: { username: 'admin1', role: 'admin' } }),
}));
// Mock toast
const mockToast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() };
vi.mock('../toast/useToast', () => ({
useToast: () => mockToast,
}));
// Mock confirm
let mockConfirmResult = true;
vi.mock('../confirm/useConfirm', () => ({
useConfirm: () => () => Promise.resolve(mockConfirmResult),
}));
const SAMPLE_USERS = [
{ id: 1, username: 'admin1', role: 'admin' },
{ id: 2, username: 'player1', role: 'user' },
{ id: 3, username: 'player2', role: 'user' },
];
describe('UserAdmin', () => {
beforeEach(() => {
vi.clearAllMocks();
mockConfirmResult = true;
mockGetUsers.mockResolvedValue(SAMPLE_USERS);
});
it('renders user list after loading', async () => {
render(<UserAdmin />);
expect(screen.getByText('불러오는 중...')).toBeInTheDocument();
expect(await screen.findByText('admin1')).toBeInTheDocument();
expect(screen.getByText('player1')).toBeInTheDocument();
expect(screen.getByText('player2')).toBeInTheDocument();
});
it('shows error when fetch fails', async () => {
mockGetUsers.mockRejectedValueOnce(new Error('fail'));
render(<UserAdmin />);
expect(await screen.findByText('유저 목록을 불러올 수 없습니다.')).toBeInTheDocument();
});
it('does not show action buttons for the current user', async () => {
render(<UserAdmin />);
await screen.findByText('admin1');
// admin1 row should not have edit/delete buttons
const listItems = screen.getAllByRole('listitem');
const admin1Item = listItems.find((li) => li.textContent.includes('admin1'));
expect(admin1Item.querySelector('button')).toBeNull();
});
it('shows role badge for each user', async () => {
render(<UserAdmin />);
await screen.findByText('admin1');
const badges = screen.getAllByText(/^(admin|user)$/);
expect(badges.length).toBeGreaterThanOrEqual(3);
});
describe('role toggle', () => {
it('promotes a user to admin', async () => {
mockUpdateUserRole.mockResolvedValueOnce({});
render(<UserAdmin />);
await screen.findByText('player1');
// player1 should have "관리자로" button
const promoteButtons = screen.getAllByText('관리자로');
fireEvent.click(promoteButtons[0]);
await waitFor(() => {
expect(mockUpdateUserRole).toHaveBeenCalledWith(2, 'admin');
});
expect(mockToast.success).toHaveBeenCalledWith('player1의 권한이 admin로 변경되었습니다.');
});
it('does not toggle role when confirm is cancelled', async () => {
mockConfirmResult = false;
render(<UserAdmin />);
await screen.findByText('player1');
const promoteButtons = screen.getAllByText('관리자로');
fireEvent.click(promoteButtons[0]);
await waitFor(() => {
expect(mockUpdateUserRole).not.toHaveBeenCalled();
});
});
it('shows toast on role toggle failure', async () => {
mockUpdateUserRole.mockRejectedValueOnce(new Error('권한 변경 실패'));
render(<UserAdmin />);
await screen.findByText('player1');
const promoteButtons = screen.getAllByText('관리자로');
fireEvent.click(promoteButtons[0]);
await waitFor(() => {
expect(mockToast.error).toHaveBeenCalledWith('권한 변경 실패');
});
});
});
describe('delete', () => {
it('deletes a user when confirmed', async () => {
mockDeleteUser.mockResolvedValueOnce({});
render(<UserAdmin />);
await screen.findByText('player1');
const deleteButtons = screen.getAllByText('삭제');
fireEvent.click(deleteButtons[0]);
await waitFor(() => {
expect(mockDeleteUser).toHaveBeenCalledWith(2);
});
expect(mockToast.success).toHaveBeenCalledWith('player1 계정이 삭제되었습니다.');
});
it('does not delete when confirm is cancelled', async () => {
mockConfirmResult = false;
render(<UserAdmin />);
await screen.findByText('player1');
const deleteButtons = screen.getAllByText('삭제');
fireEvent.click(deleteButtons[0]);
await waitFor(() => {
expect(mockDeleteUser).not.toHaveBeenCalled();
});
});
it('shows toast on delete failure', async () => {
mockDeleteUser.mockRejectedValueOnce(new Error('삭제 실패'));
render(<UserAdmin />);
await screen.findByText('player1');
const deleteButtons = screen.getAllByText('삭제');
fireEvent.click(deleteButtons[0]);
await waitFor(() => {
expect(mockToast.error).toHaveBeenCalledWith('삭제 실패');
});
});
});
});

View File

@@ -0,0 +1,76 @@
.confirm-overlay {
position: fixed;
inset: 0;
z-index: 10001;
background: rgba(0, 0, 0, 0.6);
display: flex;
align-items: center;
justify-content: center;
animation: confirm-fade-in 0.15s ease-out;
}
.confirm-dialog {
background: #3a3a3a;
border: 1px solid rgba(186, 205, 176, 0.15);
border-radius: 12px;
padding: 24px;
min-width: 320px;
max-width: 420px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
animation: confirm-scale-in 0.15s ease-out;
}
.confirm-message {
font-size: 0.95rem;
color: rgba(255, 255, 255, 0.87);
line-height: 1.5;
margin: 0 0 20px 0;
}
.confirm-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
}
.confirm-btn {
padding: 8px 20px;
border-radius: 6px;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
border: none;
transition: opacity 0.2s;
}
.confirm-btn:hover {
opacity: 0.85;
}
.confirm-btn-cancel {
background: transparent;
color: rgba(255, 255, 255, 0.5);
border: 1px solid rgba(255, 255, 255, 0.15);
}
.confirm-btn-ok {
background: #BACDB0;
color: #2E2C2F;
font-weight: 600;
}
@keyframes confirm-fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes confirm-scale-in {
from {
opacity: 0;
transform: scale(0.95);
}
to {
opacity: 1;
transform: scale(1);
}
}

View File

@@ -0,0 +1,46 @@
import { useState, useCallback, useMemo, useRef } from 'react';
import { ConfirmContext } from './confirmContextValue';
import './Confirm.css';
export function ConfirmProvider({ children }) {
const [dialog, setDialog] = useState(null);
const resolveRef = useRef(null);
const confirm = useCallback((message) => {
return new Promise((resolve) => {
resolveRef.current = resolve;
setDialog({ message });
});
}, []);
const handleConfirm = useCallback(() => {
resolveRef.current?.(true);
resolveRef.current = null;
setDialog(null);
}, []);
const handleCancel = useCallback(() => {
resolveRef.current?.(false);
resolveRef.current = null;
setDialog(null);
}, []);
const value = useMemo(() => confirm, [confirm]);
return (
<ConfirmContext.Provider value={value}>
{children}
{dialog && (
<div className="confirm-overlay" onClick={handleCancel}>
<div className="confirm-dialog" role="alertdialog" aria-modal="true" aria-label={dialog.message} onClick={(e) => e.stopPropagation()}>
<p className="confirm-message">{dialog.message}</p>
<div className="confirm-actions">
<button className="confirm-btn confirm-btn-cancel" onClick={handleCancel}>취소</button>
<button className="confirm-btn confirm-btn-ok" onClick={handleConfirm} autoFocus>확인</button>
</div>
</div>
</div>
)}
</ConfirmContext.Provider>
);
}

View File

@@ -0,0 +1,3 @@
import { createContext } from 'react';
export const ConfirmContext = createContext(null);

View File

@@ -0,0 +1,2 @@
export { ConfirmProvider } from './ConfirmProvider';
export { useConfirm } from './useConfirm';

View File

@@ -0,0 +1,8 @@
import { useContext } from 'react';
import { ConfirmContext } from './confirmContextValue';
export function useConfirm() {
const ctx = useContext(ConfirmContext);
if (!ctx) throw new Error('useConfirm must be used within ConfirmProvider');
return ctx;
}

View File

@@ -95,3 +95,43 @@
margin: 0 auto; margin: 0 auto;
padding: 32px 24px 80px; padding: 32px 24px 80px;
} }
/* Mobile responsive */
@media (max-width: 768px) {
.admin-header {
flex-direction: column;
gap: 12px;
padding: 12px 16px;
}
.admin-header-left {
width: 100%;
justify-content: center;
}
.admin-header-right {
width: 100%;
justify-content: center;
}
.admin-tabs {
padding: 12px 16px 0;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
scrollbar-width: none;
}
.admin-tabs::-webkit-scrollbar {
display: none;
}
.admin-tab {
white-space: nowrap;
flex-shrink: 0;
min-height: 44px;
}
.admin-main {
padding: 20px 12px 60px;
}
}

View File

@@ -165,12 +165,65 @@
color: rgba(255, 255, 255, 0.7); color: rgba(255, 255, 255, 0.7);
} }
.password-strength { /* Validation feedback */
font-size: 0.8rem; .input-hint {
color: rgba(186, 205, 176, 0.7); font-size: 0.75rem;
margin: -12px 0 0; color: #888;
margin-top: 2px;
} }
.password-strength.strength-weak { .input-hint-error {
color: #e57373; color: #e57373;
} }
.input-hint-success {
color: #bacdb0;
}
.input-group input.input-valid {
border-color: #bacdb0 !important;
}
.input-group input.input-invalid {
border-color: #e57373 !important;
}
.password-strength {
font-size: 0.75rem;
margin-top: 2px;
}
.strength-weak {
color: #e57373;
}
.strength-medium {
color: #ffd54f;
}
.strength-strong {
color: #bacdb0;
}
/* Mobile responsive */
@media (max-width: 768px) {
.login-panel {
max-width: 100%;
padding: 32px 20px;
margin: 0 12px;
border-radius: 8px;
}
.game-title {
font-size: 2.2rem;
}
.login-header {
margin-bottom: 28px;
}
.btn-login,
.btn-ssafy {
min-height: 44px;
}
}

View File

@@ -124,3 +124,43 @@
margin: 0 auto; margin: 0 auto;
padding: 40px 24px 80px; padding: 40px 24px 80px;
} }
/* Mobile responsive */
@media (max-width: 768px) {
.home-header {
flex-direction: column;
gap: 12px;
padding: 12px 16px;
text-align: center;
}
.home-user {
width: 100%;
justify-content: center;
}
.hero-banner {
height: 180px;
}
.hero-title {
font-size: 1.8rem;
}
.hero-desc {
font-size: 0.85rem;
}
.home-main {
padding: 24px 16px 60px;
}
.btn-logout,
.btn-admin-link,
.btn-header-login {
min-height: 44px;
display: inline-flex;
align-items: center;
justify-content: center;
}
}

View File

@@ -51,6 +51,7 @@ export default function LoginPage() {
placeholder="아이디를 입력하세요" placeholder="아이디를 입력하세요"
autoComplete="username" autoComplete="username"
maxLength={50} maxLength={50}
aria-describedby={error ? 'login-error' : undefined}
/> />
</div> </div>
@@ -64,11 +65,12 @@ export default function LoginPage() {
placeholder="비밀번호를 입력하세요" placeholder="비밀번호를 입력하세요"
autoComplete="current-password" autoComplete="current-password"
maxLength={72} maxLength={72}
aria-describedby={error ? 'login-error' : undefined}
/> />
</div> </div>
{justRegistered && <p className="login-success">회원가입이 완료되었습니다. 로그인해주세요.</p>} {justRegistered && <p className="login-success">회원가입이 완료되었습니다. 로그인해주세요.</p>}
{error && <p className="login-error" role="alert">{error}</p>} {error && <p id="login-error" className="login-error" role="alert">{error}</p>}
<button type="submit" className="btn-login" disabled={loading}> <button type="submit" className="btn-login" disabled={loading}>
{loading ? '로그인 중...' : '로그인'} {loading ? '로그인 중...' : '로그인'}
@@ -85,6 +87,9 @@ export default function LoginPage() {
onClick={async () => { onClick={async () => {
try { try {
const data = await getSSAFYLoginURL(); const data = await getSSAFYLoginURL();
if (!data.url || !data.url.startsWith('https://')) {
throw new Error('유효하지 않은 로그인 URL입니다.');
}
window.location.href = data.url; window.location.href = data.url;
} catch { } catch {
setError('SSAFY 로그인 URL을 가져올 수 없습니다.'); setError('SSAFY 로그인 URL을 가져올 수 없습니다.');

View File

@@ -3,29 +3,31 @@ import { useNavigate, Link } from 'react-router-dom';
import { register } from '../api/auth'; import { register } from '../api/auth';
import './AuthPage.css'; import './AuthPage.css';
const USERNAME_REGEX = /^[a-z0-9_-]{3,50}$/;
export default function RegisterPage() { export default function RegisterPage() {
const [username, setUsername] = useState(''); const [username, setUsername] = useState('');
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const [confirm, setConfirm] = useState(''); const [confirm, setConfirm] = useState('');
const [error, setError] = useState(''); const [error, setError] = useState('');
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [usernameTouched, setUsernameTouched] = useState(false);
const navigate = useNavigate(); const navigate = useNavigate();
const isUsernameValid = USERNAME_REGEX.test(username);
const showUsernameError = usernameTouched && username.length > 0 && !isUsernameValid;
const showUsernameValid = usernameTouched && username.length > 0 && isUsernameValid;
const getPasswordStrength = (pw) => { const getPasswordStrength = (pw) => {
if (pw.length === 0) return ''; if (pw.length === 0) return { label: '', level: '' };
if (pw.length < 6) return '비밀번호는 6자 이상이어야 합니다.'; if (pw.length < 6) return { label: '약함', level: 'weak' };
let strength = 0; if (pw.length < 10) return { label: '중간', level: 'medium' };
if (/[a-z]/.test(pw)) strength++; return { label: '강함', level: 'strong' };
if (/[A-Z]/.test(pw)) strength++;
if (/[0-9]/.test(pw)) strength++;
if (/[^a-zA-Z0-9]/.test(pw)) strength++;
if (strength <= 1) return '약함';
if (strength <= 2) return '보통';
return '강함';
}; };
const passwordStrength = getPasswordStrength(password); const passwordStrength = getPasswordStrength(password);
const isPasswordWeak = password.length > 0 && password.length < 6; const confirmMismatch = confirm.length > 0 && password !== confirm;
const confirmMatch = confirm.length > 0 && password === confirm;
const handleSubmit = async (e) => { const handleSubmit = async (e) => {
e.preventDefault(); e.preventDefault();
@@ -80,10 +82,17 @@ export default function RegisterPage() {
type="text" type="text"
value={username} value={username}
onChange={(e) => setUsername(e.target.value)} onChange={(e) => setUsername(e.target.value)}
onBlur={() => setUsernameTouched(true)}
placeholder="아이디를 입력하세요" placeholder="아이디를 입력하세요"
autoComplete="username" autoComplete="username"
maxLength={50} maxLength={50}
className={showUsernameValid ? 'input-valid' : showUsernameError ? 'input-invalid' : ''}
aria-describedby="username-hint"
/> />
<span id="username-hint" className={`input-hint ${showUsernameError ? 'input-hint-error' : ''}`}>
{showUsernameError ? '3~50자 영문 소문자, 숫자, _, -만 가능합니다' : '3~50자 영문 소문자, 숫자, _, -만 가능'}
{showUsernameValid && ' \u2713'}
</span>
</div> </div>
<div className="input-group"> <div className="input-group">
@@ -96,15 +105,15 @@ export default function RegisterPage() {
placeholder="6자 이상 입력하세요" placeholder="6자 이상 입력하세요"
autoComplete="new-password" autoComplete="new-password"
maxLength={72} maxLength={72}
aria-describedby="password-strength"
/> />
{passwordStrength.label && (
<span id="password-strength" className={`password-strength strength-${passwordStrength.level}`}>
강도: {passwordStrength.label}
</span>
)}
</div> </div>
{passwordStrength && (
<p className={`password-strength ${isPasswordWeak ? 'strength-weak' : ''}`}>
강도: {passwordStrength}
</p>
)}
<div className="input-group"> <div className="input-group">
<label htmlFor="confirm">비밀번호 확인</label> <label htmlFor="confirm">비밀번호 확인</label>
<input <input
@@ -115,7 +124,15 @@ export default function RegisterPage() {
placeholder="비밀번호를 다시 입력하세요" placeholder="비밀번호를 다시 입력하세요"
autoComplete="new-password" autoComplete="new-password"
maxLength={72} maxLength={72}
className={confirmMatch ? 'input-valid' : confirmMismatch ? 'input-invalid' : ''}
aria-describedby="confirm-hint"
/> />
{confirmMismatch && (
<span id="confirm-hint" className="input-hint input-hint-error">비밀번호가 일치하지 않습니다</span>
)}
{confirmMatch && (
<span id="confirm-hint" className="input-hint input-hint-success">비밀번호가 일치합니다 \u2713</span>
)}
</div> </div>
{error && <p className="login-error" role="alert">{error}</p>} {error && <p className="login-error" role="alert">{error}</p>}

View File

@@ -68,27 +68,21 @@ describe('RegisterPage', () => {
}); });
describe('password strength', () => { describe('password strength', () => {
it('shows weak indicator for short passwords', () => { it('shows "약함" for passwords shorter than 6 characters', () => {
renderRegisterPage(); renderRegisterPage();
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abc' } }); fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abc' } });
expect(screen.getByText(/비밀번호는 6자 이상이어야 합니다/)).toBeInTheDocument();
});
it('shows "약함" for lowercase-only password of 6+ chars', () => {
renderRegisterPage();
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abcdef' } });
expect(screen.getByText(/약함/)).toBeInTheDocument(); expect(screen.getByText(/약함/)).toBeInTheDocument();
}); });
it('shows "보통" for mixed-case password', () => { it('shows "중간" for passwords of 6-9 characters', () => {
renderRegisterPage(); renderRegisterPage();
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abcDEF' } }); fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abcdef' } });
expect(screen.getByText(/보통/)).toBeInTheDocument(); expect(screen.getByText(/중간/)).toBeInTheDocument();
}); });
it('shows "강함" for password with multiple character types', () => { it('shows "강함" for passwords of 10+ characters', () => {
renderRegisterPage(); renderRegisterPage();
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abcD1!' } }); fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abcdefghij' } });
expect(screen.getByText(/강함/)).toBeInTheDocument(); expect(screen.getByText(/강함/)).toBeInTheDocument();
}); });
}); });

View File

@@ -1 +1,19 @@
import '@testing-library/jest-dom'; import '@testing-library/jest-dom';
// Vitest 4.x + jsdom 28: '--localstorage-file' without a valid path
// causes localStorage to be a stub without .clear(). Provide a full implementation.
if (typeof localStorage === 'undefined' || typeof localStorage.clear !== 'function') {
const store = new Map();
Object.defineProperty(globalThis, 'localStorage', {
value: {
getItem: (key) => store.get(String(key)) ?? null,
setItem: (key, value) => { store.set(String(key), String(value)); },
removeItem: (key) => { store.delete(String(key)); },
clear: () => { store.clear(); },
get length() { return store.size; },
key: (index) => ([...store.keys()][index] ?? null),
},
writable: true,
configurable: true,
});
}