Compare commits
59 Commits
2f56dfb519
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 7cd8f0a837 | |||
| 0b999f0526 | |||
| 4e0716c1cb | |||
| 9a8102fb19 | |||
| 90b75413f1 | |||
| 40ea1644b1 | |||
| c0d827e8ec | |||
| ad0db24891 | |||
| 73ab907e09 | |||
| b9bdbcaabc | |||
| 7e7b3e85a7 | |||
| 1691638fe9 | |||
| 60be6e1d39 | |||
| 3dc1aad8ac | |||
| 8b6ba38a82 | |||
| f6c95c9745 | |||
| a5af22478a | |||
| 35dbdbba3b | |||
| 32d87d8151 | |||
| 4232c80f2f | |||
| 4e3a01428a | |||
| ae013acd2d | |||
| dcb2d1847d | |||
| daeaaca902 | |||
| b2fe4519f8 | |||
| 2cea340163 | |||
| eaa3319c5d | |||
| 24cbc54a96 | |||
| 42567ab6e4 | |||
| 555749b953 | |||
| 1a3be5f76b | |||
| 790e6e4c7f | |||
| 285e3ae4bd | |||
| 1335a4e929 | |||
| 789dad1e34 | |||
| e671a1cba6 | |||
| 96f5381d1c | |||
| 254617530c | |||
| f93d81b6d9 | |||
| aaf92baa9f | |||
| 97453b1d81 | |||
| c2e3be491d | |||
| 90e9922bde | |||
| 6fb7e2cbc5 | |||
| f85e261366 | |||
| f4196f5918 | |||
| 2cb4b9419f | |||
| 7e4e5a1801 | |||
| eb579ded5c | |||
| e496de7e56 | |||
| 4ec4f9a0a3 | |||
| 80c06e814e | |||
| 2163d0f311 | |||
| 4047014cea | |||
| 6998ffd6a3 | |||
| e025fdfe87 | |||
| 2ac2823ecc | |||
| 1359c38222 | |||
| 9fa665c9c0 |
7
.claude/settings.local.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(cd E:/projects/a301_launcher && \"C:/Users/98kim/sdk/go1.25.1/bin/go.exe\" build -ldflags=\"-H windowsgui -s -w\" -o launcher.exe . 2>&1)"
|
||||
]
|
||||
}
|
||||
}
|
||||
17
.dockerignore
Normal file
@@ -0,0 +1,17 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.git/
|
||||
.gitignore
|
||||
|
||||
# 환경 변수 (빌드 시 --build-arg로 주입)
|
||||
.env
|
||||
.env.*
|
||||
|
||||
# 에디터 / OS
|
||||
.vscode/
|
||||
.idea/
|
||||
*.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# 로그
|
||||
npm-debug.log*
|
||||
1
.env.development
Normal file
@@ -0,0 +1 @@
|
||||
VITE_API_BASE_URL=
|
||||
@@ -6,23 +6,56 @@ on:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 코드 체크아웃
|
||||
run: |
|
||||
git config --global --add safe.directory /workspace/A301/a301_client
|
||||
git init
|
||||
git remote add origin $GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git
|
||||
git fetch --depth=1 origin $GITHUB_SHA
|
||||
git checkout $GITHUB_SHA
|
||||
|
||||
- name: Node.js 설정
|
||||
run: |
|
||||
if ! command -v node &>/dev/null || [ "$(node -v | cut -d. -f1 | tr -d v)" -lt 22 ]; then
|
||||
curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
|
||||
apt-get install -y nodejs
|
||||
fi
|
||||
node -v && npm -v
|
||||
|
||||
- name: 의존성 설치
|
||||
run: npm ci
|
||||
|
||||
- name: 린트 검사
|
||||
run: npm run lint
|
||||
|
||||
- name: 테스트 실행
|
||||
run: npm test
|
||||
|
||||
- name: 프로덕션 빌드 검증
|
||||
run: npm run build
|
||||
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
needs: test
|
||||
steps:
|
||||
- name: 서버에 배포
|
||||
uses: appleboy/ssh-action@v1
|
||||
with:
|
||||
host: ${{ secrets.SERVER_HOST }}
|
||||
username: ${{ secrets.SERVER_USER }}
|
||||
key: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
port: 22
|
||||
script: |
|
||||
export PATH=$PATH:/usr/local/bin:/opt/homebrew/bin:$HOME/.docker/bin
|
||||
cd /tmp
|
||||
rm -rf a301-client
|
||||
git clone https://tolelom:${{ secrets.GIT_TOKEN }}@git.tolelom.xyz/A301/a301_client.git a301-client
|
||||
cd a301-client
|
||||
docker build --no-cache --build-arg VITE_API_BASE_URL=${{ secrets.VITE_API_BASE_URL }} -t a301-client:latest .
|
||||
cd ~/server
|
||||
docker compose up -d --force-recreate a301-client
|
||||
rm -rf /tmp/a301-client
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/deploy_key
|
||||
chmod 600 ~/.ssh/deploy_key
|
||||
ssh -o StrictHostKeyChecking=no -i ~/.ssh/deploy_key \
|
||||
${{ secrets.SERVER_USER }}@${{ secrets.SERVER_HOST }} \
|
||||
'set -e &&
|
||||
export PATH=$PATH:/usr/local/bin:/opt/homebrew/bin:$HOME/.docker/bin &&
|
||||
cd /tmp &&
|
||||
rm -rf a301-client &&
|
||||
git clone --quiet https://tolelom:${{ secrets.GIT_TOKEN }}@git.tolelom.xyz/A301/a301_client.git a301-client &&
|
||||
cd a301-client &&
|
||||
docker build --build-arg VITE_API_BASE_URL=${{ secrets.VITE_API_BASE_URL }} -t a301-client:latest . &&
|
||||
cd ~/server &&
|
||||
docker compose up -d --force-recreate a301-client &&
|
||||
rm -rf /tmp/a301-client'
|
||||
rm -f ~/.ssh/deploy_key
|
||||
|
||||
1
.gitignore
vendored
@@ -23,3 +23,4 @@ dist-ssr
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
.superpowers/
|
||||
|
||||
49
CLAUDE.md
@@ -1,33 +1,50 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
npm run dev # Start dev server with HMR (hot module reloading)
|
||||
npm run build # Production build to dist/
|
||||
npm run preview # Preview production build locally
|
||||
npm run lint # Run ESLint on all files
|
||||
npm run dev # 개발 서버 (HMR)
|
||||
npm run build # 프로덕션 빌드 → dist/
|
||||
npm run preview # 빌드 결과 미리보기
|
||||
npm run lint # ESLint
|
||||
```
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **React 19** with plain JavaScript (no TypeScript)
|
||||
- **Vite 7** as build tool (uses `@vitejs/plugin-react` with Babel/Fast Refresh)
|
||||
- **ESLint** with react-hooks and react-refresh plugins
|
||||
- **React 19** — plain JavaScript (no TypeScript)
|
||||
- **Vite 7** — `@vitejs/plugin-react` (Babel / Fast Refresh)
|
||||
- **React Router v7**
|
||||
- **ESLint** — flat config, `no-unused-vars` ignores `^[A-Z_]`
|
||||
|
||||
## Project Purpose
|
||||
|
||||
Frontend for a **Unity 3D multiplayer game deployment**. Target users are testers who need to:
|
||||
- Access/log in to the game platform
|
||||
- Download the Unity game client
|
||||
- Launch and play the multiplayer game
|
||||
Unity 3D 멀티플레이어 게임 "One of the plans" 웹 플랫폼.
|
||||
유저 인증 → 게임 런처 다운로드 → `a301://` 프로토콜로 런처 실행.
|
||||
|
||||
## Project Structure
|
||||
|
||||
Currently a minimal Vite + React starter. `src/main.jsx` is the entry point that mounts `src/App.jsx` to `#root`. No routing, state management libraries, or API layer are set up yet — these will be added as the project develops.
|
||||
```
|
||||
src/
|
||||
├── api/ # 백엔드 호출 (client.js: fetch 래퍼 + JWT + 401 처리)
|
||||
├── context/ # AuthContext — 3파일 분리 (react-refresh 규칙)
|
||||
│ ├── authContextValue.js
|
||||
│ ├── AuthContext.jsx
|
||||
│ └── useAuth.js
|
||||
├── pages/ # HomePage, LoginPage, RegisterPage, AdminPage
|
||||
└── components/
|
||||
├── DownloadSection.jsx # a301:// URI 호출, 미설치 시 launcher.exe 다운로드
|
||||
├── AnnouncementBoard.jsx
|
||||
└── admin/ # AnnouncementAdmin, DownloadAdmin, UserAdmin
|
||||
```
|
||||
|
||||
## ESLint Config
|
||||
## Key Patterns
|
||||
|
||||
Uses the new flat config format (`eslint.config.js`). The `no-unused-vars` rule ignores variables matching `^[A-Z_]` (uppercase constants are exempt).
|
||||
- `src/api/client.js` — 모든 API 호출은 이 래퍼를 통해 처리. 401 응답 시 자동으로 localStorage 토큰 삭제 후 `/login` 리다이렉트.
|
||||
- AuthContext는 `react-refresh` 린트 규칙(컴포넌트와 hook 혼재 금지) 때문에 3개 파일로 분리.
|
||||
- 환경변수 `VITE_API_BASE_URL` — 빌드 시 주입. 개발 시 빈 문자열(상대경로 사용).
|
||||
- 게임 이름 표기: **"One of the plans"** (기술 식별자 `a301`, `A301.exe` 등은 변경하지 않음)
|
||||
|
||||
## API Base URL
|
||||
|
||||
프론트엔드 nginx는 `/api/` 프록시 없음.
|
||||
런처·백엔드 직접 통신은 `https://a301.api.tolelom.xyz` 사용.
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Stage 1: Build
|
||||
FROM node:lts-alpine AS builder
|
||||
FROM node:22-alpine AS builder
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm ci --legacy-peer-deps
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
ARG VITE_API_BASE_URL
|
||||
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
|
||||
@@ -13,4 +13,6 @@ FROM nginx:alpine
|
||||
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
EXPOSE 80
|
||||
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
|
||||
CMD wget --no-verbose --tries=1 --spider http://localhost/ || exit 1
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
|
||||
72
README.md
@@ -1,16 +1,70 @@
|
||||
# React + Vite
|
||||
# One of the plans — Frontend
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
React 기반 웹 프론트엔드. 유저 인증, 공지사항, 게임 런처 다운로드/실행 기능을 제공합니다.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
## 기술 스택
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
- **React 19** (plain JavaScript, no TypeScript)
|
||||
- **Vite 7** — 빌드 도구 / HMR
|
||||
- **React Router v7** — 클라이언트 사이드 라우팅
|
||||
- **ESLint** — flat config (`eslint.config.js`)
|
||||
|
||||
## React Compiler
|
||||
## 실행
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
```bash
|
||||
npm install
|
||||
npm run dev # 개발 서버 (HMR)
|
||||
npm run build # 프로덕션 빌드 → dist/
|
||||
npm run preview # 빌드 결과 로컬 미리보기
|
||||
npm run lint # ESLint 검사
|
||||
```
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
## 환경 변수
|
||||
|
||||
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
|
||||
| 변수 | 설명 | 기본값 |
|
||||
|------|------|--------|
|
||||
| `VITE_API_BASE_URL` | 백엔드 API 주소 | `""` (상대경로) |
|
||||
|
||||
프로덕션 빌드 시 `--build-arg VITE_API_BASE_URL=https://a301.api.tolelom.xyz` 로 주입.
|
||||
|
||||
## 프로젝트 구조
|
||||
|
||||
```
|
||||
src/
|
||||
├── api/ # 백엔드 API 호출 모듈
|
||||
│ ├── client.js # fetch 래퍼 (JWT 자동 첨부, 401 리다이렉트)
|
||||
│ ├── auth.js
|
||||
│ ├── announcements.js
|
||||
│ ├── download.js
|
||||
│ └── users.js
|
||||
├── context/ # 인증 컨텍스트 (3파일 분리 — react-refresh 규칙)
|
||||
│ ├── authContextValue.js # createContext
|
||||
│ ├── AuthContext.jsx # AuthProvider
|
||||
│ └── useAuth.js # useAuth hook
|
||||
├── pages/
|
||||
│ ├── HomePage.jsx # 메인 (배너 + 다운로드 + 공지)
|
||||
│ ├── LoginPage.jsx
|
||||
│ ├── RegisterPage.jsx
|
||||
│ └── AdminPage.jsx # 관리자 (공지/다운로드/유저 관리)
|
||||
└── components/
|
||||
├── DownloadSection.jsx # 게임 시작 버튼 (a301:// URI 호출)
|
||||
├── AnnouncementBoard.jsx
|
||||
└── admin/
|
||||
├── AnnouncementAdmin.jsx
|
||||
├── DownloadAdmin.jsx # launcher.exe / game.zip 업로드
|
||||
└── UserAdmin.jsx
|
||||
```
|
||||
|
||||
## 게임 실행 흐름
|
||||
|
||||
1. 유저가 "게임 시작" 클릭 → `a301://launch?token=<JWT>` 호출
|
||||
2. 런처 미설치 시 → `launcher.exe` 자동 다운로드
|
||||
3. 런처 설치 후 재클릭 → 런처가 게임 다운로드/실행 처리
|
||||
|
||||
## 배포
|
||||
|
||||
Docker + nginx로 서빙. `nginx.conf` 참고.
|
||||
|
||||
```bash
|
||||
docker build --build-arg VITE_API_BASE_URL=https://a301.api.tolelom.xyz -t a301-client .
|
||||
```
|
||||
|
||||
195
docs/superpowers/specs/2026-03-23-wallet-ui-design.md
Normal file
@@ -0,0 +1,195 @@
|
||||
# 지갑 UI 설계
|
||||
|
||||
> 작성일: 2026-03-23
|
||||
> 상태: 승인됨
|
||||
|
||||
---
|
||||
|
||||
## 개요
|
||||
|
||||
웹 클라이언트(`a301_client`)에 블록체인 지갑 UI를 추가한다. 단일 `/wallet` 페이지에 4개 탭(지갑, 자산, 인벤토리, 마켓)으로 구성하고, HomePage에 잔액 요약 카드를 배치한다.
|
||||
|
||||
---
|
||||
|
||||
## 페이지 구조
|
||||
|
||||
### 라우팅
|
||||
|
||||
| 경로 | 컴포넌트 | 인증 |
|
||||
|------|----------|------|
|
||||
| `/wallet` | WalletPage | 로그인 필수 |
|
||||
|
||||
`/wallet` 라우트 보호: 기존 `AdminRoute` 패턴을 참고하여 `PrivateRoute` 컴포넌트를 새로 만든다. 로그인하지 않은 유저는 `/login`으로 리다이렉트.
|
||||
|
||||
기존 라우트는 변경하지 않는다.
|
||||
|
||||
### HomePage 변경
|
||||
|
||||
1. **헤더**: "지갑" 링크 추가 → `/wallet`로 이동
|
||||
2. **지갑 요약 카드**: DownloadSection 위에 배치
|
||||
- TOL 잔액 (큰 글씨)
|
||||
- 보유 자산 수, 장착 아이템 수
|
||||
- 클릭 시 `/wallet`로 이동
|
||||
- 로그인하지 않은 상태에서는 숨김
|
||||
- 3개 API (`/balance`, `/assets`, `/inventory`) `Promise.all`로 병렬 호출
|
||||
- 일부 API 실패 시: 실패한 항목만 "--"로 표시, 카드 자체는 숨기지 않음
|
||||
|
||||
---
|
||||
|
||||
## 탭 1: 지갑
|
||||
|
||||
잔액, 지갑 주소, 키 내보내기.
|
||||
|
||||
### 잔액 카드
|
||||
- TOL 잔액을 크게 표시
|
||||
- API: `GET /api/chain/balance`
|
||||
|
||||
### 지갑 정보
|
||||
- 공개키: 축약 표시 (`a3b4...e1f2`) + 복사 버튼
|
||||
- 주소: 축약 표시 (`a3b4c5d6...e9f0a1b2`) + 복사 버튼
|
||||
- 클릭 시 클립보드에 전체 값 복사, 토스트로 "복사됨" 알림
|
||||
- API: `GET /api/chain/wallet`
|
||||
|
||||
### 키 내보내기
|
||||
- 비밀번호 입력 필드 + "내보내기" 버튼
|
||||
- 성공 시: 개인키 hex를 화면에 표시 (복사 버튼 포함)
|
||||
- 경고 텍스트: "개인키를 안전하게 보관하세요"
|
||||
- 탭 이탈 시(다른 탭 클릭): 개인키 표시 상태 초기화 (보안)
|
||||
- 에러 처리:
|
||||
- HTTP 401 → "비밀번호가 올바르지 않습니다"
|
||||
- 기타 에러 → 토스트로 서버 에러 메시지 표시
|
||||
- API: `POST /api/chain/wallet/export` (body: `{"password": "..."}`)
|
||||
|
||||
---
|
||||
|
||||
## 탭 2: 자산
|
||||
|
||||
보유 NFT 목록 + 상세 정보.
|
||||
|
||||
### 자산 목록
|
||||
- 아이템 이름, 템플릿 이름, 자산 ID 표시
|
||||
- 거래 가능 여부 표시 ("거래 가능" / "거래 불가")
|
||||
- API 호출 전략:
|
||||
1. `GET /api/chain/assets` → 자산 ID 배열 반환
|
||||
2. 각 ID에 대해 `GET /api/chain/asset/:id`를 `Promise.all`로 **병렬 호출**
|
||||
3. 개별 자산 로드 실패 시: 해당 자산만 "로드 실패" 표시, 나머지는 정상 표시
|
||||
- 로딩 중: 스피너 표시
|
||||
|
||||
### 자산 상세 (클릭 시 펼치기)
|
||||
- 속성(properties) 키-값 표시
|
||||
- 거래 가능 여부
|
||||
- 마켓 등록 상태 (등록됨 / 미등록)
|
||||
- **마켓 등록 버튼**: 미등록 + 거래 가능한 자산에만 표시
|
||||
- 클릭 시: 가격 입력 인라인 UI (펼쳐진 상세 영역 내 숫자 input + "등록" 버튼)
|
||||
- `POST /api/chain/market/list` (body: `{"asset_id": "...", "price": N}`)
|
||||
- Idempotency-Key 헤더 필요
|
||||
- 성공 시: 토스트 알림 + 해당 자산 상태 갱신 (마켓 등록됨으로 변경)
|
||||
|
||||
---
|
||||
|
||||
## 탭 3: 인벤토리
|
||||
|
||||
장착 슬롯 현황 (조회 전용).
|
||||
|
||||
### 슬롯 목록
|
||||
- 슬롯 이름 + 장착된 아이템 이름/ID 표시
|
||||
- 빈 슬롯은 "비어있음"으로 표시 (점선 테두리)
|
||||
- 장착/해제 버튼 없음 (게임 내에서만 조작)
|
||||
- API: `GET /api/chain/inventory`
|
||||
|
||||
---
|
||||
|
||||
## 탭 4: 마켓
|
||||
|
||||
NFT 마켓플레이스. 구매, 판매(자산 탭에서 연결), 취소.
|
||||
|
||||
### 리스팅 목록
|
||||
- 전체 / 내 리스팅 필터 토글
|
||||
- 각 리스팅: 아이템 이름, 판매자 (축약 주소), 가격
|
||||
- "내 리스팅" 필터: 클라이언트에서 `/api/chain/wallet`으로 가져온 내 지갑 주소와 리스팅의 seller 필드를 비교하여 필터링
|
||||
- API: `GET /api/chain/market` → 활성 리스팅 목록
|
||||
- 미사용: `GET /api/chain/market/:id` — 리스팅 상세 모달이 없으므로 의도적으로 사용하지 않음
|
||||
|
||||
### 구매
|
||||
- 타인의 리스팅에 "구매" 버튼
|
||||
- 확인 다이얼로그 (useConfirm 사용): "화염 활을 500 TOL에 구매하시겠습니까?"
|
||||
- `POST /api/chain/market/buy` (body: `{"listing_id": "..."}`)
|
||||
- Idempotency-Key 헤더 필요
|
||||
- 성공 시: 토스트 알림 + 리스팅 목록 새로고침 + 잔액 갱신
|
||||
- 실패 시: 서버 응답 에러 메시지를 토스트로 표시 (잔액 부족 등 포함)
|
||||
|
||||
### 내 리스팅 취소
|
||||
- 내 리스팅에 "취소" 버튼 (빨간 테두리)
|
||||
- 확인 다이얼로그: "리스팅을 취소하시겠습니까?"
|
||||
- `POST /api/chain/market/cancel` (body: `{"listing_id": "..."}`)
|
||||
- Idempotency-Key 헤더 필요
|
||||
- 성공 시: 토스트 알림 + 리스팅 목록 새로고침
|
||||
|
||||
---
|
||||
|
||||
## API 호출 패턴
|
||||
|
||||
### 기존 API 클라이언트 활용
|
||||
- 모든 API 호출은 `src/api/client.js`의 `apiFetch()` 경유
|
||||
- JWT 토큰 자동 첨부, 401 시 자동 refresh
|
||||
- 새 파일: `src/api/chain.js` — 체인 관련 API 래퍼 함수 모음
|
||||
|
||||
### Idempotency-Key
|
||||
- 마켓 구매/등록/취소 등 트랜잭션 API에는 `Idempotency-Key` 헤더 필요
|
||||
- `chain.js` 래퍼 내부에서 `crypto.randomUUID()`로 자동 생성하여 헤더에 추가
|
||||
- 호출 측(컴포넌트)에서는 Idempotency-Key를 신경 쓸 필요 없음
|
||||
|
||||
### 에러 처리
|
||||
- API 에러 시 토스트로 에러 메시지 표시
|
||||
- 네트워크 에러 시 기존 retry 로직 적용 (GET만)
|
||||
|
||||
### 로딩 상태
|
||||
- 각 탭 진입 시: 중앙 스피너 표시 (기존 로딩 패턴과 동일)
|
||||
- WalletSummary: 인라인 스피너 또는 "--" placeholder
|
||||
|
||||
---
|
||||
|
||||
## 컴포넌트 구조
|
||||
|
||||
```
|
||||
src/
|
||||
├── api/
|
||||
│ └── chain.js # 체인 API 래퍼 (신규)
|
||||
├── pages/
|
||||
│ ├── WalletPage.jsx # /wallet 페이지 (탭 컨테이너) (신규)
|
||||
│ └── WalletPage.css # 지갑 페이지 스타일 (신규)
|
||||
├── components/
|
||||
│ └── wallet/ # 지갑 관련 컴포넌트 (신규)
|
||||
│ ├── WalletTab.jsx # 탭 1: 잔액, 주소, 키 내보내기
|
||||
│ ├── AssetsTab.jsx # 탭 2: 자산 목록 + 상세
|
||||
│ ├── InventoryTab.jsx # 탭 3: 인벤토리 조회
|
||||
│ ├── MarketTab.jsx # 탭 4: 마켓
|
||||
│ └── WalletSummary.jsx # HomePage 요약 카드
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 스타일링
|
||||
|
||||
- 기존 프로젝트 패턴 그대로: plain CSS, dark 테마
|
||||
- 색상: 기존 `#BACDB0` (sage green) accent 사용
|
||||
- 탭 UI: 하단 보더로 활성 탭 표시
|
||||
- 복사 버튼: 클릭 시 `navigator.clipboard.writeText()` + 토스트
|
||||
- 반응형: `@media (max-width: 768px)` 대응
|
||||
|
||||
---
|
||||
|
||||
## 변경 파일 요약
|
||||
|
||||
| 파일 | 변경 |
|
||||
|------|------|
|
||||
| `src/api/chain.js` | 신규: 체인 API 래퍼 (Idempotency-Key 자동 생성) |
|
||||
| `src/pages/WalletPage.jsx` | 신규: 지갑 페이지 (탭 컨테이너) |
|
||||
| `src/pages/WalletPage.css` | 신규: 지갑 페이지 스타일 |
|
||||
| `src/components/wallet/WalletTab.jsx` | 신규: 잔액/주소/키 내보내기 |
|
||||
| `src/components/wallet/AssetsTab.jsx` | 신규: 자산 목록 + 상세 + 마켓 등록 |
|
||||
| `src/components/wallet/InventoryTab.jsx` | 신규: 인벤토리 조회 |
|
||||
| `src/components/wallet/MarketTab.jsx` | 신규: 마켓 (구매/취소) |
|
||||
| `src/components/wallet/WalletSummary.jsx` | 신규: 홈 요약 카드 |
|
||||
| `src/App.jsx` | 수정: `/wallet` 라우트 + PrivateRoute 추가 |
|
||||
| `src/pages/HomePage.jsx` | 수정: 헤더 링크 + WalletSummary 추가 |
|
||||
@@ -14,12 +14,11 @@ export default defineConfig([
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
ecmaFeatures: { jsx: true },
|
||||
sourceType: 'module',
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
|
||||
14
index.html
@@ -1,10 +1,18 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>a301_client</title>
|
||||
<meta name="description" content="One of the plans — 멀티플레이어 보스 레이드 게임 플랫폼">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:url" content="https://a301.tolelom.xyz">
|
||||
<meta property="og:title" content="One of the plans">
|
||||
<meta property="og:description" content="One of the plans — 멀티플레이어 보스 레이드 게임 플랫폼">
|
||||
<meta property="og:image" content="https://a301.tolelom.xyz/images/logo.webp">
|
||||
<link rel="preconnect" href="https://cdn.jsdelivr.net">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard/dist/web/static/pretendard.css">
|
||||
<link rel="icon" type="image/webp" href="/images/logo.webp">
|
||||
<title>One of the plans</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
19
nginx.conf
@@ -3,6 +3,25 @@ server {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
|
||||
# index.html은 캐싱 금지 (배포 후 즉시 반영)
|
||||
location = /index.html {
|
||||
try_files $uri =404;
|
||||
add_header Cache-Control "no-store, no-cache, must-revalidate";
|
||||
}
|
||||
|
||||
# Vite 빌드 에셋 장기 캐싱 (파일명에 해시 포함 — 내용 변경 시 URL도 바뀜)
|
||||
location /assets/ {
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
}
|
||||
|
||||
# 정적 이미지 단기 캐싱 (해시 없는 파일)
|
||||
location /images/ {
|
||||
add_header Cache-Control "public, max-age=86400";
|
||||
}
|
||||
|
||||
# SPA fallback (react-router 사용 시 필요)
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
|
||||
1585
package-lock.json
generated
13
package.json
@@ -7,7 +7,9 @@
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.2.0",
|
||||
@@ -16,13 +18,18 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.1",
|
||||
"eslint": "^10.0.2",
|
||||
"eslint": "^9.0.0",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.4.24",
|
||||
"globals": "^16.5.0",
|
||||
"vite": "^7.3.1"
|
||||
"jsdom": "^28.1.0",
|
||||
"vite": "^7.3.1",
|
||||
"vitest": "^4.1.0"
|
||||
}
|
||||
}
|
||||
|
||||
BIN
public/images/bg_loading.webp
Normal file
|
After Width: | Height: | Size: 82 KiB |
BIN
public/images/bg_login.webp
Normal file
|
After Width: | Height: | Size: 218 KiB |
BIN
public/images/bg_main.webp
Normal file
|
After Width: | Height: | Size: 234 KiB |
BIN
public/images/btn_normal.webp
Normal file
|
After Width: | Height: | Size: 43 KiB |
BIN
public/images/btn_pressed.webp
Normal file
|
After Width: | Height: | Size: 20 KiB |
BIN
public/images/card_frame.webp
Normal file
|
After Width: | Height: | Size: 38 KiB |
BIN
public/images/divider.webp
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
public/images/logo.webp
Normal file
|
After Width: | Height: | Size: 126 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB |
@@ -1 +0,0 @@
|
||||
/* Global app styles - kept minimal, page-level styles in pages/ */
|
||||
73
src/App.jsx
@@ -1,18 +1,75 @@
|
||||
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
|
||||
import { AuthProvider, useAuth } from './context/AuthContext';
|
||||
import { BrowserRouter, Routes, Route, Navigate, useNavigate } from 'react-router-dom';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { AuthProvider } from './context/AuthContext';
|
||||
import { ToastProvider } from './components/toast/ToastProvider';
|
||||
import { ConfirmProvider } from './components/confirm/ConfirmProvider';
|
||||
import { useAuth } from './context/useAuth';
|
||||
import ErrorBoundary from './components/ErrorBoundary';
|
||||
import LoginPage from './pages/LoginPage';
|
||||
import RegisterPage from './pages/RegisterPage';
|
||||
import HomePage from './pages/HomePage';
|
||||
import AdminPage from './pages/AdminPage';
|
||||
import WalletPage from './pages/WalletPage';
|
||||
import SSAFYCallbackPage from './pages/SSAFYCallbackPage';
|
||||
import NotFoundPage from './pages/NotFoundPage';
|
||||
|
||||
function AuthRedirect() {
|
||||
const { user } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const prevUserRef = useRef(user);
|
||||
|
||||
useEffect(() => {
|
||||
if (prevUserRef.current && !user) {
|
||||
navigate('/login', { replace: true });
|
||||
}
|
||||
prevUserRef.current = user;
|
||||
}, [user, navigate]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function PrivateRoute({ children }) {
|
||||
const { user } = useAuth();
|
||||
if (!user) return <Navigate to="/login" replace />;
|
||||
return children;
|
||||
}
|
||||
|
||||
function AdminRoute({ children }) {
|
||||
const { user } = useAuth();
|
||||
if (!user) return <Navigate to="/login" replace />;
|
||||
if (user.role !== 'admin') return <Navigate to="/" replace />;
|
||||
return children;
|
||||
}
|
||||
|
||||
function AppRoutes() {
|
||||
const { user } = useAuth();
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<AuthRedirect />
|
||||
<Routes>
|
||||
<Route
|
||||
path="/login"
|
||||
element={user ? <Navigate to="/" replace /> : <LoginPage />}
|
||||
/>
|
||||
<Route path="/login" element={user ? <Navigate to="/" replace /> : <LoginPage />} />
|
||||
<Route path="/register" element={user ? <Navigate to="/" replace /> : <RegisterPage />} />
|
||||
<Route path="/auth/ssafy/callback" element={<SSAFYCallbackPage />} />
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route
|
||||
path="/wallet"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<WalletPage />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin"
|
||||
element={
|
||||
<AdminRoute>
|
||||
<AdminPage />
|
||||
</AdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route path="*" element={<NotFoundPage />} />
|
||||
</Routes>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -20,7 +77,11 @@ export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<ToastProvider>
|
||||
<ConfirmProvider>
|
||||
<AppRoutes />
|
||||
</ConfirmProvider>
|
||||
</ToastProvider>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
);
|
||||
|
||||
@@ -3,3 +3,21 @@ import { apiFetch } from './client';
|
||||
export async function getAnnouncements() {
|
||||
return apiFetch('/api/announcements');
|
||||
}
|
||||
|
||||
export async function createAnnouncement(title, content) {
|
||||
return apiFetch('/api/announcements', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ title, content }),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateAnnouncement(id, title, content) {
|
||||
return apiFetch(`/api/announcements/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ title, content }),
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteAnnouncement(id) {
|
||||
return apiFetch(`/api/announcements/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
@@ -6,3 +6,38 @@ export async function login(username, password) {
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
}
|
||||
|
||||
export async function register(username, password) {
|
||||
return apiFetch('/api/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
}
|
||||
|
||||
export async function logout() {
|
||||
return apiFetch('/api/auth/logout', { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function getSSAFYLoginURL() {
|
||||
return apiFetch('/api/auth/ssafy/login');
|
||||
}
|
||||
|
||||
export async function ssafyCallback(code, state) {
|
||||
return apiFetch('/api/auth/ssafy/callback', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ code, state }),
|
||||
});
|
||||
}
|
||||
|
||||
// 토큰을 리프레시하고 새 access token을 반환 (동시 호출 방지 포함)
|
||||
export { tryRefresh as refreshToken } from './client';
|
||||
|
||||
/**
|
||||
* 게임 런처용 일회용 티켓 발급
|
||||
* JWT를 URL에 직접 노출하지 않기 위해 단기 티켓으로 대체
|
||||
* @returns {Promise<string>} 티켓 문자열
|
||||
*/
|
||||
export async function createLaunchTicket() {
|
||||
const data = await apiFetch('/api/auth/launch-ticket', { method: 'POST' });
|
||||
return data.ticket;
|
||||
}
|
||||
|
||||
93
src/api/chain.js
Normal file
@@ -0,0 +1,93 @@
|
||||
import { apiFetch } from './client';
|
||||
|
||||
// exportWalletKey는 비밀번호 오류 시 서버가 401을 반환하므로
|
||||
// apiFetch의 401 자동 refresh/로그아웃을 우회하기 위해 BASE를 직접 참조
|
||||
const BASE = import.meta.env.VITE_API_BASE_URL || '';
|
||||
|
||||
// --- 지갑 ---
|
||||
|
||||
export async function getBalance() {
|
||||
return apiFetch('/api/chain/balance');
|
||||
}
|
||||
|
||||
export async function getWallet() {
|
||||
return apiFetch('/api/chain/wallet');
|
||||
}
|
||||
|
||||
/**
|
||||
* 개인키 내보내기
|
||||
* apiFetch를 우회해 직접 fetch 사용 — 비밀번호 오류(401)를 로그아웃 없이 처리하기 위함
|
||||
* @param {string} password
|
||||
* @returns {Promise<{privateKey: string}>}
|
||||
* @throws {Error} 비밀번호 오류 시 status 401
|
||||
*/
|
||||
export async function exportWalletKey(password) {
|
||||
const token = localStorage.getItem('token');
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
const res = await fetch(BASE + '/api/chain/wallet/export', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = new Error(res.status === 401 ? '비밀번호가 올바르지 않습니다' : '키 내보내기에 실패했습니다');
|
||||
err.status = res.status;
|
||||
try { const body = await res.json(); err.message = body.message || err.message; } catch { /* ignore parse failure */ }
|
||||
throw err;
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
// --- 자산 ---
|
||||
|
||||
export async function getAssets() {
|
||||
return apiFetch('/api/chain/assets');
|
||||
}
|
||||
|
||||
export async function getAsset(id) {
|
||||
return apiFetch(`/api/chain/asset/${id}`);
|
||||
}
|
||||
|
||||
// --- 인벤토리 ---
|
||||
|
||||
export async function getInventory() {
|
||||
return apiFetch('/api/chain/inventory');
|
||||
}
|
||||
|
||||
// --- 마켓 ---
|
||||
|
||||
export async function getMarketListings() {
|
||||
return apiFetch('/api/chain/market');
|
||||
}
|
||||
|
||||
export async function getListing(id) {
|
||||
return apiFetch(`/api/chain/market/${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Idempotency-Key 헤더를 붙인 POST 요청
|
||||
* 중복 제출(네트워크 재시도 등)로 인한 이중 처리를 서버에서 방지
|
||||
* @param {string} path
|
||||
* @param {object} body
|
||||
*/
|
||||
function idempotentPost(path, body) {
|
||||
return apiFetch(path, {
|
||||
method: 'POST',
|
||||
headers: { 'Idempotency-Key': crypto.randomUUID() },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
export async function listOnMarket(assetId, price) {
|
||||
return idempotentPost('/api/chain/market/list', { assetId, price });
|
||||
}
|
||||
|
||||
export async function buyFromMarket(listingId) {
|
||||
return idempotentPost('/api/chain/market/buy', { listingId });
|
||||
}
|
||||
|
||||
export async function cancelListing(listingId) {
|
||||
return idempotentPost('/api/chain/market/cancel', { listingId });
|
||||
}
|
||||
@@ -1,15 +1,200 @@
|
||||
const BASE = import.meta.env.VITE_API_BASE_URL || '';
|
||||
|
||||
export async function apiFetch(path, options = {}) {
|
||||
const token = localStorage.getItem('token');
|
||||
const headers = { 'Content-Type': 'application/json', ...options.headers };
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
|
||||
const res = await fetch(BASE + path, { ...options, headers });
|
||||
if (!res.ok) {
|
||||
const err = new Error(res.statusText);
|
||||
err.status = res.status;
|
||||
throw err;
|
||||
/**
|
||||
* 네트워크 에러 메시지를 한국어로 변환
|
||||
* @param {string} message
|
||||
* @returns {string}
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
let refreshingPromise = null;
|
||||
|
||||
/**
|
||||
* 리프레시 토큰으로 액세스 토큰 갱신
|
||||
* 동시 401 발생 시 refresh를 한 번만 실행하기 위해 Promise를 공유
|
||||
* @returns {Promise<string>} 새 액세스 토큰
|
||||
* @throws {Error} refresh_failed — 리프레시 토큰 만료 또는 서버 오류
|
||||
*/
|
||||
export async function tryRefresh() {
|
||||
if (refreshingPromise) return refreshingPromise;
|
||||
|
||||
refreshingPromise = (async () => {
|
||||
const res = await fetch(BASE + '/api/auth/refresh', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('refresh_failed');
|
||||
|
||||
const data = await res.json();
|
||||
localStorage.setItem('token', data.token);
|
||||
return data.token;
|
||||
})().finally(() => {
|
||||
refreshingPromise = null;
|
||||
});
|
||||
|
||||
return refreshingPromise;
|
||||
}
|
||||
|
||||
async function doFetch(path, options, token) {
|
||||
const headers = { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', ...options.headers };
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
return fetch(BASE + path, { ...options, headers, credentials: 'include' });
|
||||
}
|
||||
|
||||
/** @type {Record<string, string>} 에러 코드별 기본 한국어 메시지 */
|
||||
const ERROR_MESSAGES = {
|
||||
bad_request: '잘못된 요청입니다',
|
||||
unauthorized: '로그인이 필요합니다',
|
||||
forbidden: '권한이 없습니다',
|
||||
not_found: '요청한 리소스를 찾을 수 없습니다',
|
||||
conflict: '이미 존재하는 항목입니다',
|
||||
tx_failed: '트랜잭션 처리에 실패했습니다',
|
||||
rate_limited: '요청이 너무 많습니다. 잠시 후 다시 시도해주세요',
|
||||
internal_error: '서버 오류가 발생했습니다',
|
||||
};
|
||||
|
||||
async function parseError(res) {
|
||||
let message = res.statusText;
|
||||
let code;
|
||||
try {
|
||||
const body = await res.json();
|
||||
code = body.error;
|
||||
message = body.message || ERROR_MESSAGES[code] || message;
|
||||
} catch { /* 응답 바디 파싱 실패 시 statusText 사용 */ }
|
||||
const err = new Error(message);
|
||||
err.status = res.status;
|
||||
err.code = code;
|
||||
return err;
|
||||
}
|
||||
|
||||
async function parseResponse(res) {
|
||||
if (res.status === 204) return null;
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* 인증 포함 API 요청 래퍼
|
||||
* - 401 응답 시 토큰 자동 갱신 후 재시도
|
||||
* - 네트워크 에러 / 5xx 응답 시 GET·HEAD 요청만 최대 2회 재시도 (exponential backoff)
|
||||
* @param {string} path - API 경로 (예: '/api/chain/balance')
|
||||
* @param {RequestInit} [options={}] - fetch 옵션
|
||||
* @returns {Promise<any>} 응답 JSON (204는 null)
|
||||
* @throws {Error} HTTP 에러 또는 네트워크 에러
|
||||
*/
|
||||
export async function apiFetch(path, options = {}, _retryCount = 0) {
|
||||
const token = localStorage.getItem('token');
|
||||
let res;
|
||||
|
||||
const method = (options.method || 'GET').toUpperCase();
|
||||
const isIdempotent = method === 'GET' || method === 'HEAD';
|
||||
|
||||
try {
|
||||
res = await doFetch(path, options, token);
|
||||
} catch (e) {
|
||||
// 네트워크 에러 (오프라인 등) — 멱등 요청만 재시도
|
||||
if (isIdempotent && _retryCount < 2) {
|
||||
await delay(1000 * (_retryCount + 1));
|
||||
return apiFetch(path, options, _retryCount + 1);
|
||||
}
|
||||
e.message = localizeError(e.message);
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (res.status === 401) {
|
||||
try {
|
||||
const newToken = await tryRefresh();
|
||||
// 새 토큰으로 원래 요청 재시도
|
||||
const retryRes = await doFetch(path, options, newToken);
|
||||
if (retryRes.status === 401) {
|
||||
window.dispatchEvent(new Event('auth:unauthorized'));
|
||||
throw await parseError(retryRes);
|
||||
}
|
||||
if (!retryRes.ok) throw await parseError(retryRes);
|
||||
return parseResponse(retryRes);
|
||||
} catch (e) {
|
||||
// refresh 자체 실패 → 로그아웃
|
||||
if (e.message === 'no_refresh_token' || e.message === 'refresh_failed') {
|
||||
window.dispatchEvent(new Event('auth:unauthorized'));
|
||||
const err = new Error('인증이 필요합니다');
|
||||
err.status = 401;
|
||||
throw err;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
// 5xx 서버 에러 — 멱등 요청만 최대 2회 재시도 (exponential backoff)
|
||||
if (res.status >= 500 && isIdempotent && _retryCount < 2) {
|
||||
await delay(1000 * (_retryCount + 1));
|
||||
return apiFetch(path, options, _retryCount + 1);
|
||||
}
|
||||
|
||||
if (!res.ok) throw await parseError(res);
|
||||
return parseResponse(res);
|
||||
}
|
||||
|
||||
function delay(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
/**
|
||||
* XHR 기반 파일 업로드 (progress 지원 + 401 자동 갱신)
|
||||
* @param {string} path - API 경로 (예: '/api/download/upload/game?filename=...')
|
||||
* @param {File} file - 업로드할 파일
|
||||
* @param {function} onProgress - progress 콜백 (percent: number)
|
||||
* @returns {Promise<{status: number, body: object}>}
|
||||
*/
|
||||
export function apiUpload(path, file, onProgress) {
|
||||
function send(token) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', BASE + path);
|
||||
xhr.withCredentials = true;
|
||||
if (token) xhr.setRequestHeader('Authorization', `Bearer ${token}`);
|
||||
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
|
||||
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
|
||||
|
||||
xhr.upload.onprogress = (event) => {
|
||||
if (event.lengthComputable && onProgress) {
|
||||
onProgress(Math.round((event.loaded / event.total) * 100));
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onload = () => resolve(xhr);
|
||||
xhr.onerror = () => reject(new Error('서버에 연결할 수 없습니다'));
|
||||
xhr.send(file);
|
||||
});
|
||||
}
|
||||
|
||||
return (async () => {
|
||||
const token = localStorage.getItem('token');
|
||||
const xhr = await send(token);
|
||||
|
||||
if (xhr.status === 401) {
|
||||
try {
|
||||
const newToken = await tryRefresh();
|
||||
const retryXhr = await send(newToken);
|
||||
if (retryXhr.status === 401) {
|
||||
window.dispatchEvent(new Event('auth:unauthorized'));
|
||||
throw new Error('인증이 필요합니다');
|
||||
}
|
||||
return { status: retryXhr.status, body: JSON.parse(retryXhr.responseText || '{}') };
|
||||
} catch (e) {
|
||||
if (e.message === 'no_refresh_token' || e.message === 'refresh_failed') {
|
||||
window.dispatchEvent(new Event('auth:unauthorized'));
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
return { status: xhr.status, body: JSON.parse(xhr.responseText || '{}') };
|
||||
})();
|
||||
}
|
||||
|
||||
156
src/api/client.test.js
Normal file
@@ -0,0 +1,156 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { apiFetch, tryRefresh } from './client';
|
||||
|
||||
// Stub import.meta.env
|
||||
// Vitest handles import.meta.env automatically via vite config
|
||||
|
||||
describe('apiFetch', () => {
|
||||
let fetchSpy;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
fetchSpy = vi.spyOn(globalThis, 'fetch');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('adds Authorization header when token exists in localStorage', async () => {
|
||||
localStorage.setItem('token', 'test-token-123');
|
||||
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ ok: true }), { status: 200 }),
|
||||
);
|
||||
|
||||
await apiFetch('/api/test');
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledOnce();
|
||||
const [, options] = fetchSpy.mock.calls[0];
|
||||
expect(options.headers['Authorization']).toBe('Bearer test-token-123');
|
||||
});
|
||||
|
||||
it('does not add Authorization header when no token exists', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ data: 1 }), { status: 200 }),
|
||||
);
|
||||
|
||||
await apiFetch('/api/test');
|
||||
|
||||
const [, options] = fetchSpy.mock.calls[0];
|
||||
expect(options.headers['Authorization']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('attempts token refresh on 401 response', async () => {
|
||||
localStorage.setItem('token', 'expired-token');
|
||||
|
||||
// First call: 401
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ error: 'unauthorized' }), { status: 401 }),
|
||||
);
|
||||
|
||||
// Refresh call: success (refresh token sent via HttpOnly cookie by browser)
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify({ token: 'new-token' }),
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
|
||||
// Retry with new token: success
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ data: 'ok' }), { status: 200 }),
|
||||
);
|
||||
|
||||
const result = await apiFetch('/api/protected');
|
||||
|
||||
expect(result).toEqual({ data: 'ok' });
|
||||
// After refresh, localStorage should have new access token
|
||||
expect(localStorage.getItem('token')).toBe('new-token');
|
||||
});
|
||||
|
||||
it('dispatches auth:unauthorized when refresh fails', async () => {
|
||||
localStorage.setItem('token', 'expired-token');
|
||||
// Refresh will fail (no HttpOnly cookie set in test env)
|
||||
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ error: 'unauthorized' }), { status: 401 }),
|
||||
);
|
||||
|
||||
// Refresh call: fail
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ error: 'refreshToken이 필요합니다' }), { status: 400 }),
|
||||
);
|
||||
|
||||
const dispatchSpy = vi.spyOn(window, 'dispatchEvent');
|
||||
|
||||
await expect(apiFetch('/api/protected')).rejects.toThrow();
|
||||
|
||||
expect(dispatchSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: 'auth:unauthorized' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('retries on 5xx errors up to 2 times', async () => {
|
||||
// Mock delay to be instant for faster tests
|
||||
const originalSetTimeout = globalThis.setTimeout;
|
||||
vi.spyOn(globalThis, 'setTimeout').mockImplementation((fn) => originalSetTimeout(fn, 0));
|
||||
|
||||
fetchSpy
|
||||
.mockResolvedValueOnce(
|
||||
new Response('', { status: 500, statusText: 'Internal Server Error' }),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response('', { status: 502, statusText: 'Bad Gateway' }),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ data: 'recovered' }), { status: 200 }),
|
||||
);
|
||||
|
||||
const result = await apiFetch('/api/flaky');
|
||||
expect(result).toEqual({ data: 'recovered' });
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('throws after exhausting 5xx retries', async () => {
|
||||
const originalSetTimeout = globalThis.setTimeout;
|
||||
vi.spyOn(globalThis, 'setTimeout').mockImplementation((fn) => originalSetTimeout(fn, 0));
|
||||
|
||||
fetchSpy
|
||||
.mockResolvedValue(
|
||||
new Response('', { status: 500, statusText: 'Internal Server Error' }),
|
||||
);
|
||||
|
||||
await expect(apiFetch('/api/broken')).rejects.toThrow();
|
||||
// 1 original + 2 retries = 3
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tryRefresh', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('throws when refresh request fails', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ error: 'refreshToken이 필요합니다' }), { status: 400 }),
|
||||
);
|
||||
|
||||
await expect(tryRefresh()).rejects.toThrow('refresh_failed');
|
||||
});
|
||||
|
||||
it('stores new access token on successful refresh', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify({ token: 'fresh-token' }),
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
|
||||
const token = await tryRefresh();
|
||||
expect(token).toBe('fresh-token');
|
||||
expect(localStorage.getItem('token')).toBe('fresh-token');
|
||||
});
|
||||
});
|
||||
17
src/api/users.js
Normal file
@@ -0,0 +1,17 @@
|
||||
import { apiFetch } from './client';
|
||||
|
||||
export function getUsers(offset = 0, limit = 20) {
|
||||
const params = new URLSearchParams({ offset, limit });
|
||||
return apiFetch(`/api/users?${params}`);
|
||||
}
|
||||
|
||||
export function updateUserRole(id, role) {
|
||||
return apiFetch(`/api/users/${id}/role`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ role }),
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteUser(id) {
|
||||
return apiFetch(`/api/users/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 4.0 KiB |
@@ -1,5 +1,6 @@
|
||||
.announcement-board {
|
||||
margin-top: 32px;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.announcement-heading {
|
||||
@@ -7,8 +8,9 @@
|
||||
font-weight: 700;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
margin: 0 0 16px;
|
||||
padding-bottom: 12px;
|
||||
border-bottom: 1px solid rgba(186, 205, 176, 0.15);
|
||||
padding-bottom: 0;
|
||||
border-bottom: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.announcement-list {
|
||||
@@ -58,4 +60,18 @@
|
||||
font-size: 0.9rem;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.announcement-error {
|
||||
font-size: 0.9rem;
|
||||
color: #e57373;
|
||||
padding: 12px 8px;
|
||||
}
|
||||
|
||||
.announcement-empty {
|
||||
font-size: 0.9rem;
|
||||
color: rgba(255, 255, 255, 0.35);
|
||||
padding: 12px 8px;
|
||||
}
|
||||
|
||||
@@ -5,20 +5,31 @@ import './AnnouncementBoard.css';
|
||||
export default function AnnouncementBoard() {
|
||||
const [list, setList] = useState([]);
|
||||
const [expanded, setExpanded] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
getAnnouncements().then(setList);
|
||||
getAnnouncements()
|
||||
.then(setList)
|
||||
.catch(() => setError(true))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<section className="announcement-board">
|
||||
<h2 className="announcement-heading">공지사항</h2>
|
||||
{loading && <p className="announcement-empty">불러오는 중...</p>}
|
||||
{error && <p className="announcement-error">공지사항을 불러오지 못했습니다.</p>}
|
||||
{!loading && !error && list.length === 0 && (
|
||||
<p className="announcement-empty">등록된 공지사항이 없습니다.</p>
|
||||
)}
|
||||
<ul className="announcement-list">
|
||||
{list.map((item) => (
|
||||
<li key={item.id} className="announcement-item">
|
||||
<button
|
||||
className="announcement-row"
|
||||
onClick={() => setExpanded(expanded === item.id ? null : item.id)}
|
||||
aria-expanded={expanded === item.id}
|
||||
>
|
||||
<span className="announcement-title">{item.title}</span>
|
||||
<span className="announcement-date">{item.createdAt?.slice(0, 10)}</span>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
.download-section {
|
||||
background: rgba(186, 205, 176, 0.06);
|
||||
border: 1px solid rgba(186, 205, 176, 0.12);
|
||||
position: relative;
|
||||
background:
|
||||
linear-gradient(to bottom, rgba(0,0,0,0.7), rgba(0,0,0,0.6)),
|
||||
url('/images/bg_main.webp') center/cover no-repeat;
|
||||
border-radius: 12px;
|
||||
padding: 48px 40px;
|
||||
padding: 60px 40px;
|
||||
text-align: center;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.download-title {
|
||||
@@ -19,22 +22,63 @@
|
||||
margin: 0 0 28px;
|
||||
}
|
||||
|
||||
.btn-download {
|
||||
.btn-play {
|
||||
display: inline-block;
|
||||
padding: 16px 48px;
|
||||
padding: 18px 64px;
|
||||
background: #BACDB0;
|
||||
color: #2E2C2F;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 1.1rem;
|
||||
font-size: 1.2rem;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s, transform 0.15s;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.btn-download:hover {
|
||||
.btn-play:hover {
|
||||
opacity: 0.9;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btn-play:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.btn-launcher-download {
|
||||
display: inline-block;
|
||||
margin-left: 12px;
|
||||
padding: 18px 32px;
|
||||
background: transparent;
|
||||
color: #BACDB0;
|
||||
border: 1px solid rgba(186, 205, 176, 0.4);
|
||||
border-radius: 8px;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, transform 0.15s;
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
|
||||
.btn-launcher-download:hover {
|
||||
background: rgba(186, 205, 176, 0.1);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.launch-hint {
|
||||
font-size: 0.78rem;
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
margin: 16px 0 0;
|
||||
}
|
||||
|
||||
.launch-hint-active {
|
||||
color: #BACDB0;
|
||||
}
|
||||
|
||||
.download-preparing {
|
||||
font-size: 0.9rem;
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@@ -1,37 +1,116 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { useAuth } from '../context/useAuth';
|
||||
import { getDownloadInfo } from '../api/download';
|
||||
import { createLaunchTicket } from '../api/auth';
|
||||
import './DownloadSection.css';
|
||||
|
||||
export default function DownloadSection() {
|
||||
const [info, setInfo] = useState(null);
|
||||
const [ready, setReady] = useState(false);
|
||||
const [loadError, setLoadError] = useState(false);
|
||||
const [launched, setLaunched] = useState(false);
|
||||
const [launching, setLaunching] = useState(false);
|
||||
const { user } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
getDownloadInfo().then(setInfo);
|
||||
}, []);
|
||||
const loadInfo = () => {
|
||||
setReady(false);
|
||||
setLoadError(false);
|
||||
getDownloadInfo()
|
||||
.then((data) => { setInfo(data); setReady(true); })
|
||||
.catch(() => { setLoadError(true); setReady(true); });
|
||||
};
|
||||
|
||||
const handleDownload = (e) => {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- initial data fetch on mount
|
||||
useEffect(() => { loadInfo(); }, []);
|
||||
|
||||
const handlePlay = async () => {
|
||||
if (!user) {
|
||||
e.preventDefault();
|
||||
navigate('/login');
|
||||
return;
|
||||
}
|
||||
|
||||
setLaunching(true);
|
||||
|
||||
// JWT를 URL에 직접 노출하지 않고, 일회용 티켓을 발급받아 전달
|
||||
try {
|
||||
const ticket = await createLaunchTicket();
|
||||
window.location.href = 'a301://launch?token=' + encodeURIComponent(ticket);
|
||||
} catch {
|
||||
// 티켓 발급 실패 시 로그인 유도
|
||||
navigate('/login');
|
||||
return;
|
||||
}
|
||||
|
||||
// 런처가 실행되지 않았을 수 있으므로 안내 표시
|
||||
setLaunched(true);
|
||||
setLaunching(false);
|
||||
};
|
||||
|
||||
const handleDownloadLauncher = () => {
|
||||
if (info?.launcherUrl) {
|
||||
const a = document.createElement('a');
|
||||
a.href = info.launcherUrl;
|
||||
a.download = 'launcher.exe';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
}
|
||||
};
|
||||
|
||||
if (!info) return null;
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<section className="download-section">
|
||||
<div className="download-content">
|
||||
<h2 className="download-title">게임 런처 다운로드</h2>
|
||||
<p className="download-meta">
|
||||
{info.fileName} · {info.fileSize} · {info.version}
|
||||
</p>
|
||||
<a href={info.url} download onClick={handleDownload} className="btn-download">
|
||||
{user ? '다운로드' : '로그인 후 다운로드'}
|
||||
</a>
|
||||
<h2 className="download-title">One of the plans</h2>
|
||||
<p className="download-meta">불러오는 중...</p>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="download-section">
|
||||
<div className="download-content">
|
||||
<h2 className="download-title">One of the plans</h2>
|
||||
{info ? (
|
||||
<>
|
||||
<p className="download-meta">
|
||||
{info.version} · {info.fileSize}
|
||||
</p>
|
||||
<button onClick={handlePlay} className="btn-play" disabled={launching}>
|
||||
{launching ? '준비 중...' : '게임 시작'}
|
||||
</button>
|
||||
{info.launcherUrl && (
|
||||
<button onClick={handleDownloadLauncher} className="btn-launcher-download">
|
||||
런처 다운로드
|
||||
</button>
|
||||
)}
|
||||
{launched ? (
|
||||
<p className="launch-hint launch-hint-active">
|
||||
게임이 실행되지 않나요? 런처를 다운로드한 뒤 한 번 실행해주세요.
|
||||
</p>
|
||||
) : (
|
||||
<p className="launch-hint">
|
||||
처음이거나 게임이 실행되지 않으면 런처를 다운로드해주세요.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="download-preparing">
|
||||
{loadError
|
||||
? '서버에 연결할 수 없습니다.'
|
||||
: '런처 준비 중입니다. 잠시 후 다시 확인해주세요.'}
|
||||
</p>
|
||||
{loadError && (
|
||||
<button onClick={loadInfo} className="btn-launcher-download">
|
||||
다시 시도
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
|
||||
99
src/components/ErrorBoundary.css
Normal 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);
|
||||
}
|
||||
54
src/components/ErrorBoundary.jsx
Normal file
@@ -0,0 +1,54 @@
|
||||
import { Component } from 'react';
|
||||
import './ErrorBoundary.css';
|
||||
|
||||
export default class ErrorBoundary extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = { hasError: false, error: null };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error) {
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
componentDidCatch(error, errorInfo) {
|
||||
console.error('Uncaught error:', error, errorInfo);
|
||||
}
|
||||
|
||||
handleRetry = () => {
|
||||
this.setState({ hasError: false, error: null });
|
||||
};
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
const { error } = this.state;
|
||||
const errorType = error?.name || 'Error';
|
||||
const errorMessage = error?.message || '알 수 없는 오류가 발생했습니다.';
|
||||
|
||||
return (
|
||||
<div className="error-boundary">
|
||||
<div className="error-boundary-card">
|
||||
<div className="error-boundary-icon">!</div>
|
||||
<h2 className="error-boundary-title">문제가 발생했습니다</h2>
|
||||
<p className="error-boundary-desc">
|
||||
예기치 않은 오류로 페이지를 표시할 수 없습니다.
|
||||
</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>
|
||||
);
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
377
src/components/admin/AdminCommon.module.css
Normal file
@@ -0,0 +1,377 @@
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 700;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
margin: 0;
|
||||
padding-bottom: 12px;
|
||||
border-bottom: 1px solid rgba(186, 205, 176, 0.12);
|
||||
}
|
||||
|
||||
/* Form */
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 20px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid rgba(186, 205, 176, 0.1);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.label {
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.input {
|
||||
padding: 10px 14px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(186, 205, 176, 0.15);
|
||||
border-radius: 6px;
|
||||
color: #fff;
|
||||
font-size: 0.9rem;
|
||||
outline: none;
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
.input:focus {
|
||||
border-color: rgba(186, 205, 176, 0.5);
|
||||
}
|
||||
|
||||
.textarea {
|
||||
padding: 10px 14px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(186, 205, 176, 0.15);
|
||||
border-radius: 6px;
|
||||
color: #fff;
|
||||
font-size: 0.9rem;
|
||||
outline: none;
|
||||
resize: vertical;
|
||||
transition: border-color 0.2s;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.textarea:focus {
|
||||
border-color: rgba(186, 205, 176, 0.5);
|
||||
}
|
||||
|
||||
.error {
|
||||
font-size: 0.85rem;
|
||||
color: rgba(229, 115, 115, 0.9);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.formActions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.btnPrimary {
|
||||
padding: 10px 24px;
|
||||
background: #BACDB0;
|
||||
color: #2E2C2F;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.btnPrimary:hover { opacity: 0.9; }
|
||||
.btnPrimary:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
.btnSecondary {
|
||||
padding: 10px 20px;
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
border-radius: 6px;
|
||||
font-size: 0.9rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.btnSecondary:hover {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
/* List */
|
||||
.list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.listItem {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 12px 16px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.listInfo {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.listTitle {
|
||||
font-size: 0.9rem;
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.listDate {
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.listActions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.btnEdit {
|
||||
padding: 6px 14px;
|
||||
background: transparent;
|
||||
color: rgba(186, 205, 176, 0.8);
|
||||
border: 1px solid rgba(186, 205, 176, 0.25);
|
||||
border-radius: 5px;
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.btnEdit:hover {
|
||||
background: rgba(186, 205, 176, 0.08);
|
||||
}
|
||||
|
||||
.btnDelete {
|
||||
padding: 6px 14px;
|
||||
background: transparent;
|
||||
color: rgba(229, 115, 115, 0.8);
|
||||
border: 1px solid rgba(229, 115, 115, 0.25);
|
||||
border-radius: 5px;
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.btnDelete:hover {
|
||||
background: rgba(229, 115, 115, 0.08);
|
||||
}
|
||||
|
||||
/* Deploy block */
|
||||
.deployBlock {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.deployHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.deployLabel {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
/* File input */
|
||||
.inputFile {
|
||||
padding: 8px 0;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.inputFile:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* Field hint */
|
||||
.fieldHint {
|
||||
font-size: 0.75rem;
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
/* Upload progress */
|
||||
.uploadProgress {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.uploadBar {
|
||||
flex: 1;
|
||||
height: 6px;
|
||||
background: #BACDB0;
|
||||
border-radius: 3px;
|
||||
transition: width 0.2s;
|
||||
}
|
||||
|
||||
.uploadPct {
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
min-width: 36px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
/* Current build info */
|
||||
.currentBuild {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 14px 16px;
|
||||
background: rgba(186, 205, 176, 0.05);
|
||||
border: 1px solid rgba(186, 205, 176, 0.12);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.metaRow {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.metaItem {
|
||||
font-size: 0.78rem;
|
||||
color: rgba(186, 205, 176, 0.8);
|
||||
background: rgba(186, 205, 176, 0.08);
|
||||
padding: 3px 10px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid rgba(186, 205, 176, 0.15);
|
||||
}
|
||||
|
||||
.metaHash {
|
||||
composes: metaItem;
|
||||
font-family: monospace;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
/* Role badge */
|
||||
.listEmpty {
|
||||
font-size: 0.9rem;
|
||||
color: rgba(255, 255, 255, 0.35);
|
||||
padding: 12px 16px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.roleBadge {
|
||||
font-size: 0.7rem;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.roleBadgeAdmin {
|
||||
composes: roleBadge;
|
||||
background: rgba(186, 205, 176, 0.15);
|
||||
color: #BACDB0;
|
||||
}
|
||||
|
||||
.roleBadgeUser {
|
||||
composes: roleBadge;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
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;
|
||||
}
|
||||
}
|
||||
148
src/components/admin/AnnouncementAdmin.jsx
Normal file
@@ -0,0 +1,148 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { getAnnouncements, createAnnouncement, updateAnnouncement, deleteAnnouncement } from '../../api/announcements';
|
||||
import { useToast } from '../toast/useToast';
|
||||
import { useConfirm } from '../confirm/useConfirm';
|
||||
import s from './AdminCommon.module.css';
|
||||
|
||||
export default function AnnouncementAdmin() {
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const [list, setList] = useState([]);
|
||||
const [form, setForm] = useState({ title: '', content: '' });
|
||||
const [editingId, setEditingId] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [fetchLoading, setFetchLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [fetchError, setFetchError] = useState('');
|
||||
|
||||
const load = useCallback(() => {
|
||||
setFetchError('');
|
||||
getAnnouncements()
|
||||
.then(setList)
|
||||
.catch((err) => {
|
||||
console.error('공지사항 로드 실패:', err);
|
||||
setFetchError('공지사항을 불러오지 못했습니다.');
|
||||
})
|
||||
.finally(() => setFetchLoading(false));
|
||||
}, []);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
if (!form.title || !form.content) {
|
||||
setError('제목과 내용을 모두 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
if (editingId) {
|
||||
await updateAnnouncement(editingId, form.title, form.content);
|
||||
} else {
|
||||
await createAnnouncement(form.title, form.content);
|
||||
}
|
||||
toast.success(editingId ? '공지사항이 수정되었습니다.' : '공지사항이 등록되었습니다.');
|
||||
setForm({ title: '', content: '' });
|
||||
setEditingId(null);
|
||||
load();
|
||||
} catch (err) {
|
||||
toast.error(err.message || '처리에 실패했습니다.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (item) => {
|
||||
setEditingId(item.id);
|
||||
setForm({ title: item.title, content: item.content });
|
||||
setError('');
|
||||
};
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (!(await confirm('삭제하시겠습니까?'))) return;
|
||||
try {
|
||||
await deleteAnnouncement(id);
|
||||
toast.success('공지사항이 삭제되었습니다.');
|
||||
load();
|
||||
} catch (err) {
|
||||
toast.error(err.message || '삭제에 실패했습니다.');
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setEditingId(null);
|
||||
setForm({ title: '', content: '' });
|
||||
setError('');
|
||||
};
|
||||
|
||||
if (fetchLoading) {
|
||||
return (
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>공지사항 관리</h2>
|
||||
<p className={s.loading}>불러오는 중...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (fetchError) {
|
||||
return (
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>공지사항 관리</h2>
|
||||
<p className={s.error}>{fetchError}</p>
|
||||
<button className={s.btnSecondary} onClick={load}>다시 시도</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>공지사항 관리</h2>
|
||||
|
||||
<form className={s.form} onSubmit={handleSubmit}>
|
||||
<input
|
||||
className={s.input}
|
||||
placeholder="제목"
|
||||
value={form.title}
|
||||
onChange={(e) => setForm({ ...form, title: e.target.value })}
|
||||
maxLength={200}
|
||||
aria-label="공지사항 제목"
|
||||
/>
|
||||
<textarea
|
||||
className={s.textarea}
|
||||
placeholder="내용"
|
||||
rows={4}
|
||||
value={form.content}
|
||||
onChange={(e) => setForm({ ...form, content: e.target.value })}
|
||||
maxLength={10000}
|
||||
aria-label="공지사항 내용"
|
||||
/>
|
||||
{error && <p className={s.error}>{error}</p>}
|
||||
<div className={s.formActions}>
|
||||
<button className={s.btnPrimary} type="submit" disabled={loading}>
|
||||
{editingId ? '수정 완료' : '공지 등록'}
|
||||
</button>
|
||||
{editingId && (
|
||||
<button className={s.btnSecondary} type="button" onClick={handleCancel}>
|
||||
취소
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<ul className={s.list}>
|
||||
{list.map((item) => (
|
||||
<li key={item.id} className={s.listItem}>
|
||||
<div className={s.listInfo}>
|
||||
<span className={s.listTitle}>{item.title}</span>
|
||||
<span className={s.listDate}>{item.createdAt?.slice(0, 10)}</span>
|
||||
</div>
|
||||
<div className={s.listActions}>
|
||||
<button className={s.btnEdit} onClick={() => handleEdit(item)}>수정</button>
|
||||
<button className={s.btnDelete} onClick={() => handleDelete(item.id)}>삭제</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
187
src/components/admin/AnnouncementAdmin.test.jsx
Normal 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('삭제 실패');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
92
src/components/admin/DownloadAdmin.jsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { getDownloadInfo } from '../../api/download';
|
||||
import UploadForm from './UploadForm';
|
||||
import s from './AdminCommon.module.css';
|
||||
|
||||
export default function DownloadAdmin() {
|
||||
const [info, setInfo] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
setLoadError('');
|
||||
getDownloadInfo()
|
||||
.then((data) => setInfo(data))
|
||||
.catch(() => setLoadError('배포 정보를 불러올 수 없습니다.'))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>게임 배포 관리</h2>
|
||||
<p className={s.loading}>불러오는 중...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (loadError) {
|
||||
return (
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>게임 배포 관리</h2>
|
||||
<p className={s.error}>{loadError}</p>
|
||||
<button className={s.btnSecondary} onClick={load}>다시 시도</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>게임 배포 관리</h2>
|
||||
|
||||
{/* 런처 섹션 */}
|
||||
<div className={s.deployBlock}>
|
||||
<div className={s.deployHeader}>
|
||||
<span className={s.deployLabel}>런처</span>
|
||||
{info?.launcherUrl && (
|
||||
<div className={s.metaRow}>
|
||||
{info.launcherSize && <span className={s.metaItem}>{info.launcherSize}</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<UploadForm
|
||||
title="launcher.exe"
|
||||
hint="빌드된 launcher.exe 파일을 업로드하세요."
|
||||
accept=".exe"
|
||||
endpoint="/api/download/upload/launcher"
|
||||
onSuccess={setInfo}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 게임 섹션 */}
|
||||
<div className={s.deployBlock}>
|
||||
<div className={s.deployHeader}>
|
||||
<span className={s.deployLabel}>게임</span>
|
||||
{info?.url && (
|
||||
<div className={s.metaRow}>
|
||||
{info.version && <span className={s.metaItem}>{info.version}</span>}
|
||||
{info.fileName && <span className={s.metaItem}>{info.fileName}</span>}
|
||||
{info.fileSize && <span className={s.metaItem}>{info.fileSize}</span>}
|
||||
{info.fileHash && (
|
||||
<span className={s.metaHash} title={info.fileHash}>
|
||||
SHA256: {info.fileHash.slice(0, 12)}...
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<UploadForm
|
||||
title="게임 파일 (zip)"
|
||||
hint="A301.exe가 포함된 zip 파일을 업로드하세요. 버전·크기·해시가 자동으로 추출됩니다."
|
||||
accept=".zip"
|
||||
endpoint="/api/download/upload/game"
|
||||
onSuccess={setInfo}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
85
src/components/admin/DownloadAdmin.test.jsx
Normal 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();
|
||||
});
|
||||
});
|
||||
85
src/components/admin/UploadForm.jsx
Normal file
@@ -0,0 +1,85 @@
|
||||
import { useState, useRef } from 'react';
|
||||
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 }) {
|
||||
const toast = useToast();
|
||||
const [file, setFile] = useState(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [error, setError] = useState('');
|
||||
const fileInputRef = useRef(null);
|
||||
|
||||
const handleFileChange = (e) => {
|
||||
setFile(e.target.files[0] || null);
|
||||
setError('');
|
||||
setProgress(0);
|
||||
};
|
||||
|
||||
const handleUpload = async (e) => {
|
||||
e.preventDefault();
|
||||
if (!file) return;
|
||||
|
||||
const path = `${endpoint}?filename=${encodeURIComponent(file.name)}`;
|
||||
setUploading(true);
|
||||
setError('');
|
||||
|
||||
const fail = (msg) => { setError(msg); toast.error(msg); setProgress(0); };
|
||||
|
||||
try {
|
||||
const { status, body } = await apiUpload(path, file, (p) => setProgress(p));
|
||||
if (status >= 200 && status < 300) {
|
||||
onSuccess(body);
|
||||
toast.success('업로드가 완료되었습니다.');
|
||||
setFile(null);
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
setProgress(0);
|
||||
} else if (status === 413) {
|
||||
fail('파일 크기가 너무 큽니다. 더 작은 파일을 선택해주세요.');
|
||||
} else if (status === 409) {
|
||||
fail('동일한 파일이 이미 존재합니다.');
|
||||
} else if (status >= 500) {
|
||||
fail('서버 오류가 발생했습니다. 잠시 후 다시 시도해주세요.');
|
||||
} else {
|
||||
fail(body.error || '업로드에 실패했습니다.');
|
||||
}
|
||||
} catch {
|
||||
fail('네트워크 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form className={s.form} onSubmit={handleUpload}>
|
||||
<div className={s.field}>
|
||||
<label className={s.label}>{title}</label>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept={accept}
|
||||
className={s.inputFile}
|
||||
onChange={handleFileChange}
|
||||
disabled={uploading}
|
||||
/>
|
||||
<span className={s.fieldHint}>{hint}</span>
|
||||
</div>
|
||||
|
||||
{uploading && (
|
||||
<div className={s.uploadProgress}>
|
||||
<div className={s.uploadBar} style={{ width: `${progress}%` }} />
|
||||
<span className={s.uploadPct}>{progress}%</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <p className={s.error}>{error}</p>}
|
||||
|
||||
<div className={s.formActions}>
|
||||
<button className={s.btnPrimary} type="submit" disabled={uploading || !file}>
|
||||
{uploading ? `업로드 중... (${progress}%)` : '업로드'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
113
src/components/admin/UserAdmin.jsx
Normal file
@@ -0,0 +1,113 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { getUsers, updateUserRole, deleteUser } from '../../api/users';
|
||||
import { useAuth } from '../../context/useAuth';
|
||||
import { useToast } from '../toast/useToast';
|
||||
import { useConfirm } from '../confirm/useConfirm';
|
||||
import s from './AdminCommon.module.css';
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
export default function UserAdmin() {
|
||||
const [users, setUsers] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [fetchError, setFetchError] = useState(false);
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
const { user: me } = useAuth();
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
|
||||
const load = useCallback((off = 0) => {
|
||||
setLoading(true);
|
||||
setFetchError(false);
|
||||
getUsers(off, PAGE_SIZE)
|
||||
.then((data) => {
|
||||
setUsers(data);
|
||||
setHasMore(data.length === PAGE_SIZE);
|
||||
})
|
||||
.catch(() => setFetchError(true))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
useEffect(() => { load(0); }, [load]);
|
||||
|
||||
const handleRoleToggle = async (u) => {
|
||||
const newRole = u.role === 'admin' ? 'user' : 'admin';
|
||||
if (!(await confirm(`${u.username}의 권한을 ${newRole}로 변경하시겠습니까?`))) return;
|
||||
try {
|
||||
await updateUserRole(u.id, newRole);
|
||||
toast.success(`${u.username}의 권한이 ${newRole}로 변경되었습니다.`);
|
||||
load();
|
||||
} catch (err) {
|
||||
toast.error(err.message || '권한 변경에 실패했습니다.');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (u) => {
|
||||
if (!(await confirm(`${u.username} 계정을 삭제하시겠습니까?`))) return;
|
||||
try {
|
||||
await deleteUser(u.id);
|
||||
toast.success(`${u.username} 계정이 삭제되었습니다.`);
|
||||
load();
|
||||
} catch (err) {
|
||||
toast.error(err.message || '삭제에 실패했습니다.');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={s.section}>
|
||||
<h2 className={s.sectionTitle}>유저 관리</h2>
|
||||
{fetchError && (
|
||||
<div className={s.errorBlock}>
|
||||
<p className={s.error}>유저 목록을 불러올 수 없습니다.</p>
|
||||
<button className={s.btnSecondary} onClick={load}>다시 시도</button>
|
||||
</div>
|
||||
)}
|
||||
{loading && <p className={s.listEmpty}>불러오는 중...</p>}
|
||||
{!loading && users.length === 0 && <p className={s.listEmpty}>등록된 유저가 없습니다.</p>}
|
||||
<ul className={s.list}>
|
||||
{users.map((u) => (
|
||||
<li key={u.id} className={s.listItem}>
|
||||
<div className={s.listInfo}>
|
||||
<span className={s.listTitle}>{u.username}</span>
|
||||
<span className={u.role === 'admin' ? s.roleBadgeAdmin : s.roleBadgeUser}>{u.role}</span>
|
||||
</div>
|
||||
{u.username !== me?.username && (
|
||||
<div className={s.listActions}>
|
||||
<button className={s.btnEdit} onClick={() => handleRoleToggle(u)}>
|
||||
{u.role === 'admin' ? '일반으로' : '관리자로'}
|
||||
</button>
|
||||
<button className={s.btnDelete} onClick={() => handleDelete(u)}>삭제</button>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className={s.listActions} style={{ justifyContent: 'center', marginTop: '1rem' }}>
|
||||
<button
|
||||
className={s.btnSecondary}
|
||||
disabled={offset === 0}
|
||||
onClick={() => {
|
||||
const prev = Math.max(0, offset - PAGE_SIZE);
|
||||
setOffset(prev);
|
||||
load(prev);
|
||||
}}
|
||||
>
|
||||
이전
|
||||
</button>
|
||||
<button
|
||||
className={s.btnSecondary}
|
||||
disabled={!hasMore}
|
||||
onClick={() => {
|
||||
const next = offset + PAGE_SIZE;
|
||||
setOffset(next);
|
||||
load(next);
|
||||
}}
|
||||
>
|
||||
다음
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
161
src/components/admin/UserAdmin.test.jsx
Normal 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('삭제 실패');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
76
src/components/confirm/Confirm.css
Normal 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);
|
||||
}
|
||||
}
|
||||
44
src/components/confirm/ConfirmProvider.jsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import { useState, useCallback, 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);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ConfirmContext.Provider value={confirm}>
|
||||
{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>
|
||||
);
|
||||
}
|
||||
3
src/components/confirm/confirmContextValue.js
Normal file
@@ -0,0 +1,3 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export const ConfirmContext = createContext(null);
|
||||
2
src/components/confirm/index.js
Normal file
@@ -0,0 +1,2 @@
|
||||
export { ConfirmProvider } from './ConfirmProvider';
|
||||
export { useConfirm } from './useConfirm';
|
||||
8
src/components/confirm/useConfirm.js
Normal 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;
|
||||
}
|
||||
49
src/components/toast/Toast.css
Normal file
@@ -0,0 +1,49 @@
|
||||
.toast-container {
|
||||
position: fixed;
|
||||
top: 16px;
|
||||
right: 16px;
|
||||
z-index: 10000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.toast-item {
|
||||
padding: 12px 20px;
|
||||
border-radius: 8px;
|
||||
color: #fff;
|
||||
font-size: 14px;
|
||||
max-width: 360px;
|
||||
cursor: pointer;
|
||||
pointer-events: auto;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
||||
animation: toast-in 0.25s ease-out;
|
||||
}
|
||||
|
||||
.toast-item.info {
|
||||
background-color: #3a3a3a;
|
||||
}
|
||||
|
||||
.toast-item.success {
|
||||
background-color: #2d6a4f;
|
||||
}
|
||||
|
||||
.toast-item.error {
|
||||
background-color: #9b2226;
|
||||
}
|
||||
|
||||
.toast-item.warn {
|
||||
background-color: #7f5539;
|
||||
}
|
||||
|
||||
@keyframes toast-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(100%);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
42
src/components/toast/ToastProvider.jsx
Normal file
@@ -0,0 +1,42 @@
|
||||
import { useState, useCallback, useMemo, useRef } from 'react';
|
||||
import { ToastContext } from './toastContextValue';
|
||||
import './Toast.css';
|
||||
|
||||
export function ToastProvider({ children }) {
|
||||
const [toasts, setToasts] = useState([]);
|
||||
const timersRef = useRef({});
|
||||
const toastIdRef = useRef(0);
|
||||
|
||||
const removeToast = useCallback((id) => {
|
||||
clearTimeout(timersRef.current[id]);
|
||||
delete timersRef.current[id];
|
||||
setToasts((prev) => prev.filter((t) => t.id !== id));
|
||||
}, []);
|
||||
|
||||
const addToast = useCallback((message, type = 'info', duration = 3000) => {
|
||||
const id = ++toastIdRef.current;
|
||||
setToasts((prev) => [...prev, { id, message, type }]);
|
||||
timersRef.current[id] = setTimeout(() => removeToast(id), duration);
|
||||
return id;
|
||||
}, [removeToast]);
|
||||
|
||||
const toast = useMemo(() => ({
|
||||
info: (message) => addToast(message, 'info'),
|
||||
success: (message) => addToast(message, 'success'),
|
||||
error: (message) => addToast(message, 'error'),
|
||||
warn: (message) => addToast(message, 'warn'),
|
||||
}), [addToast]);
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={toast}>
|
||||
{children}
|
||||
<div className="toast-container" role="status" aria-live="polite">
|
||||
{toasts.map((t) => (
|
||||
<div key={t.id} className={`toast-item ${t.type}`} onClick={() => removeToast(t.id)}>
|
||||
{t.message}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
}
|
||||
2
src/components/toast/index.js
Normal file
@@ -0,0 +1,2 @@
|
||||
export { ToastProvider } from './ToastProvider';
|
||||
export { useToast } from './useToast';
|
||||
3
src/components/toast/toastContextValue.js
Normal file
@@ -0,0 +1,3 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export const ToastContext = createContext(null);
|
||||
8
src/components/toast/useToast.js
Normal file
@@ -0,0 +1,8 @@
|
||||
import { useContext } from 'react';
|
||||
import { ToastContext } from './toastContextValue';
|
||||
|
||||
export function useToast() {
|
||||
const ctx = useContext(ToastContext);
|
||||
if (!ctx) throw new Error('useToast must be used within ToastProvider');
|
||||
return ctx;
|
||||
}
|
||||
159
src/components/wallet/AssetsTab.jsx
Normal file
@@ -0,0 +1,159 @@
|
||||
import { useState, useEffect, useCallback, Fragment } from 'react';
|
||||
import { getAssets, getAsset, listOnMarket } from '../../api/chain';
|
||||
import { useToast } from '../toast/useToast';
|
||||
|
||||
export default function AssetsTab() {
|
||||
const toast = useToast();
|
||||
const [assets, setAssets] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [expanded, setExpanded] = useState(null);
|
||||
const [listingAsset, setListingAsset] = useState(null);
|
||||
const [listingPrice, setListingPrice] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
getAssets()
|
||||
.then((result) => {
|
||||
const ids = result?.ids || result;
|
||||
if (!ids || !Array.isArray(ids) || ids.length === 0) {
|
||||
setAssets([]);
|
||||
return;
|
||||
}
|
||||
return Promise.all(
|
||||
ids.map((id) =>
|
||||
getAsset(id)
|
||||
.then((data) => ({ ...data, _loaded: true }))
|
||||
.catch(() => ({ id, _loaded: false }))
|
||||
)
|
||||
).then(setAssets);
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error('자산 목록을 불러오지 못했습니다.');
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [toast]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const toggleExpand = (id) => {
|
||||
setExpanded((prev) => (prev === id ? null : id));
|
||||
setListingAsset(null);
|
||||
setListingPrice('');
|
||||
};
|
||||
|
||||
const handleList = async (assetId) => {
|
||||
const price = Number(listingPrice);
|
||||
if (!price || price <= 0) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await listOnMarket(assetId, price);
|
||||
toast.success('마켓에 등록되었습니다.');
|
||||
setAssets((prev) =>
|
||||
prev.map((a) => (a.id === assetId ? { ...a, active_listing_id: 'pending' } : a))
|
||||
);
|
||||
setListingAsset(null);
|
||||
setListingPrice('');
|
||||
} catch (err) {
|
||||
toast.error(err.message || '마켓 등록에 실패했습니다.');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <div className="wallet-spinner">불러오는 중...</div>;
|
||||
if (assets.length === 0) return <div className="wallet-empty">보유 자산이 없습니다</div>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
{assets.map((asset) => {
|
||||
const isListed = !!asset.active_listing_id;
|
||||
return (
|
||||
<div key={asset.id} className="asset-item">
|
||||
<div className="asset-header" onClick={() => toggleExpand(asset.id)}>
|
||||
<div>
|
||||
{asset._loaded ? (
|
||||
<>
|
||||
<strong style={{ color: '#fff' }}>{asset.template_id || '자산'}</strong>
|
||||
<span style={{ marginLeft: 12, fontSize: '0.8rem', opacity: 0.4 }}>#{asset.id}</span>
|
||||
</>
|
||||
) : (
|
||||
<span style={{ color: '#e57373' }}>로드 실패 (#{asset.id})</span>
|
||||
)}
|
||||
</div>
|
||||
{asset._loaded && (
|
||||
<span className={`wallet-tag ${asset.tradeable ? 'wallet-tag-ok' : 'wallet-tag-no'}`}>
|
||||
{asset.tradeable ? '거래 가능' : '거래 불가'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{expanded === asset.id && asset._loaded && (
|
||||
<div className="asset-detail">
|
||||
{/* 속성 */}
|
||||
{asset.properties && Object.keys(asset.properties).length > 0 && (
|
||||
<div className="asset-props">
|
||||
{Object.entries(asset.properties).map(([k, v]) => (
|
||||
<Fragment key={k}>
|
||||
<span className="asset-prop-key">{k}</span>
|
||||
<span className="asset-prop-val">{String(v)}</span>
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 마켓 등록 상태 */}
|
||||
<div style={{ marginTop: 12 }}>
|
||||
{isListed ? (
|
||||
<span className="wallet-tag wallet-tag-listed">마켓 등록됨</span>
|
||||
) : (
|
||||
<span className="wallet-tag wallet-tag-no">미등록</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 마켓 등록 버튼 */}
|
||||
{!isListed && asset.tradeable && (
|
||||
<div style={{ marginTop: 12 }}>
|
||||
{listingAsset === asset.id ? (
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<input
|
||||
type="number"
|
||||
className="wallet-input"
|
||||
placeholder="가격 (TOL)"
|
||||
value={listingPrice}
|
||||
onChange={(e) => setListingPrice(e.target.value)}
|
||||
min="1"
|
||||
style={{ width: 140 }}
|
||||
/>
|
||||
<button
|
||||
className="btn-primary"
|
||||
disabled={submitting || !listingPrice}
|
||||
onClick={() => handleList(asset.id)}
|
||||
>
|
||||
{submitting ? '처리 중...' : '등록'}
|
||||
</button>
|
||||
<button
|
||||
className="btn-copy"
|
||||
onClick={() => { setListingAsset(null); setListingPrice(''); }}
|
||||
>
|
||||
취소
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
className="btn-primary"
|
||||
onClick={(e) => { e.stopPropagation(); setListingAsset(asset.id); }}
|
||||
>
|
||||
마켓에 등록
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
45
src/components/wallet/InventoryTab.jsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { getInventory } from '../../api/chain';
|
||||
import { useToast } from '../toast/useToast';
|
||||
|
||||
export default function InventoryTab() {
|
||||
const toast = useToast();
|
||||
const [inventory, setInventory] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
getInventory()
|
||||
.then(setInventory)
|
||||
.catch(() => toast.error('인벤토리를 불러오지 못했습니다.'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [toast]);
|
||||
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
if (loading) return <div className="wallet-spinner">불러오는 중...</div>;
|
||||
|
||||
const slots = inventory?.slots;
|
||||
const entries = slots ? Object.entries(slots) : [];
|
||||
|
||||
if (entries.length === 0) return <div className="wallet-empty">인벤토리가 비어있습니다</div>;
|
||||
|
||||
return (
|
||||
<div>
|
||||
{entries.map(([slotName, assetId]) => {
|
||||
const isEmpty = !assetId;
|
||||
return (
|
||||
<div key={slotName} className={`inv-slot${isEmpty ? ' inv-slot-empty' : ''}`}>
|
||||
<span style={{ color: 'rgba(255,255,255,0.5)', fontSize: '0.85rem' }}>
|
||||
{slotName}
|
||||
</span>
|
||||
<span style={{ color: isEmpty ? 'rgba(255,255,255,0.25)' : '#fff', fontSize: '0.9rem' }}>
|
||||
{isEmpty ? '비어있음' : assetId}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
142
src/components/wallet/MarketTab.jsx
Normal file
@@ -0,0 +1,142 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { getMarketListings, getListing, getWallet, buyFromMarket, cancelListing } from '../../api/chain';
|
||||
import { useToast } from '../toast/useToast';
|
||||
import { useConfirm } from '../confirm/useConfirm';
|
||||
|
||||
function truncateAddr(addr) {
|
||||
if (!addr || addr.length <= 12) return addr || '';
|
||||
return `${addr.slice(0, 6)}...${addr.slice(-4)}`;
|
||||
}
|
||||
|
||||
export default function MarketTab() {
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const [listings, setListings] = useState([]);
|
||||
const [myPubKey, setMyPubKey] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [filter, setFilter] = useState('all');
|
||||
const [processing, setProcessing] = useState(null);
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
Promise.all([getMarketListings(), getWallet()])
|
||||
.then(([result, w]) => {
|
||||
const ids = result?.ids || result;
|
||||
setMyPubKey(w?.pubKeyHex || '');
|
||||
if (!ids || !Array.isArray(ids) || ids.length === 0) {
|
||||
setListings([]);
|
||||
return;
|
||||
}
|
||||
return Promise.all(
|
||||
ids.map((id) =>
|
||||
getListing(id)
|
||||
.then((data) => ({ ...data, _loaded: true }))
|
||||
.catch(() => ({ id, _loaded: false }))
|
||||
)
|
||||
).then((items) => setListings(items.filter((l) => l._loaded)));
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error('마켓 정보를 불러오지 못했습니다.');
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [toast]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const handleBuy = async (listing) => {
|
||||
const ok = await confirm(
|
||||
`${listing.asset_id}을(를) ${Number(listing.price).toLocaleString()} TOL에 구매하시겠습니까?`
|
||||
);
|
||||
if (!ok) return;
|
||||
setProcessing(listing.id);
|
||||
try {
|
||||
await buyFromMarket(listing.id);
|
||||
toast.success('구매가 완료되었습니다.');
|
||||
load();
|
||||
} catch (err) {
|
||||
toast.error(err.message || '구매에 실패했습니다.');
|
||||
} finally {
|
||||
setProcessing(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = async (listing) => {
|
||||
const ok = await confirm('리스팅을 취소하시겠습니까?');
|
||||
if (!ok) return;
|
||||
setProcessing(listing.id);
|
||||
try {
|
||||
await cancelListing(listing.id);
|
||||
toast.success('리스팅이 취소되었습니다.');
|
||||
load();
|
||||
} catch (err) {
|
||||
toast.error(err.message || '취소에 실패했습니다.');
|
||||
} finally {
|
||||
setProcessing(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <div className="wallet-spinner">불러오는 중...</div>;
|
||||
|
||||
const filtered = filter === 'mine'
|
||||
? listings.filter((l) => l.seller === myPubKey)
|
||||
: listings;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="market-filter">
|
||||
<button
|
||||
className={`market-filter-btn${filter === 'all' ? ' active' : ''}`}
|
||||
onClick={() => setFilter('all')}
|
||||
>
|
||||
전체
|
||||
</button>
|
||||
<button
|
||||
className={`market-filter-btn${filter === 'mine' ? ' active' : ''}`}
|
||||
onClick={() => setFilter('mine')}
|
||||
>
|
||||
내 리스팅
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{filtered.length === 0 ? (
|
||||
<div className="wallet-empty">
|
||||
{filter === 'mine' ? '내 리스팅이 없습니다' : '등록된 리스팅이 없습니다'}
|
||||
</div>
|
||||
) : (
|
||||
filtered.map((listing) => {
|
||||
const isMine = listing.seller === myPubKey;
|
||||
return (
|
||||
<div key={listing.id} className="market-item">
|
||||
<div>
|
||||
<strong style={{ color: '#fff' }}>{listing.asset_id}</strong>
|
||||
<span className="market-seller" style={{ marginLeft: 12 }}>
|
||||
{truncateAddr(listing.seller)}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
|
||||
<span className="market-price">{Number(listing.price).toLocaleString()} TOL</span>
|
||||
{isMine ? (
|
||||
<button
|
||||
className="btn-danger-outline"
|
||||
disabled={processing === listing.id}
|
||||
onClick={() => handleCancel(listing)}
|
||||
>
|
||||
{processing === listing.id ? '처리 중...' : '취소'}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
className="btn-primary"
|
||||
disabled={processing === listing.id}
|
||||
onClick={() => handleBuy(listing)}
|
||||
>
|
||||
{processing === listing.id ? '처리 중...' : '구매'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
51
src/components/wallet/WalletSummary.css
Normal file
@@ -0,0 +1,51 @@
|
||||
.wallet-summary {
|
||||
background: rgba(186, 205, 176, 0.06);
|
||||
border: 1px solid rgba(186, 205, 176, 0.15);
|
||||
border-radius: 10px;
|
||||
padding: 20px 24px;
|
||||
margin-bottom: 32px;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.2s, background 0.2s;
|
||||
}
|
||||
|
||||
.wallet-summary:hover {
|
||||
border-color: rgba(186, 205, 176, 0.3);
|
||||
background: rgba(186, 205, 176, 0.09);
|
||||
}
|
||||
|
||||
.wallet-summary-title {
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
letter-spacing: 0.08em;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.wallet-summary-balance {
|
||||
font-size: 1.8rem;
|
||||
font-weight: 700;
|
||||
color: #BACDB0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.wallet-summary-stats {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.wallet-summary-stat {
|
||||
font-size: 0.85rem;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.wallet-summary-stat strong {
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.wallet-summary-stats {
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
47
src/components/wallet/WalletSummary.jsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { getBalance, getAssets, getInventory } from '../../api/chain';
|
||||
import './WalletSummary.css';
|
||||
|
||||
export default function WalletSummary() {
|
||||
const navigate = useNavigate();
|
||||
const [balance, setBalance] = useState(null);
|
||||
const [assetCount, setAssetCount] = useState(null);
|
||||
const [equippedCount, setEquippedCount] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
getBalance().catch(() => null),
|
||||
getAssets().catch(() => null),
|
||||
getInventory().catch(() => null),
|
||||
]).then(([b, assets, inv]) => {
|
||||
setBalance(b?.balance != null ? b.balance : null);
|
||||
const ids = assets?.ids || assets;
|
||||
setAssetCount(Array.isArray(ids) ? ids.length : null);
|
||||
const slots = inv?.slots;
|
||||
setEquippedCount(
|
||||
slots != null ? Object.values(slots).filter(Boolean).length : null
|
||||
);
|
||||
}).finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
if (loading) return null;
|
||||
|
||||
return (
|
||||
<div className="wallet-summary" onClick={() => navigate('/wallet')}>
|
||||
<h3 className="wallet-summary-title">내 지갑</h3>
|
||||
<p className="wallet-summary-balance">
|
||||
{balance != null ? `${Number(balance).toLocaleString()} TOL` : '-- TOL'}
|
||||
</p>
|
||||
<div className="wallet-summary-stats">
|
||||
<span className="wallet-summary-stat">
|
||||
보유 자산 <strong>{assetCount != null ? assetCount : '--'}</strong>
|
||||
</span>
|
||||
<span className="wallet-summary-stat">
|
||||
장착 아이템 <strong>{equippedCount != null ? equippedCount : '--'}</strong>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
146
src/components/wallet/WalletTab.jsx
Normal file
@@ -0,0 +1,146 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { getBalance, getWallet, exportWalletKey } from '../../api/chain';
|
||||
import { useToast } from '../toast/useToast';
|
||||
|
||||
function truncate(str, startLen = 4, endLen = 4) {
|
||||
if (!str || str.length <= startLen + endLen + 3) return str || '';
|
||||
return `${str.slice(0, startLen)}...${str.slice(-endLen)}`;
|
||||
}
|
||||
|
||||
export default function WalletTab() {
|
||||
const toast = useToast();
|
||||
const [balance, setBalance] = useState(null);
|
||||
const [wallet, setWallet] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const [password, setPassword] = useState('');
|
||||
const [privateKey, setPrivateKey] = useState('');
|
||||
const [exportError, setExportError] = useState('');
|
||||
const [exporting, setExporting] = useState(false);
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
Promise.all([getBalance(), getWallet()])
|
||||
.then(([b, w]) => {
|
||||
setBalance(b);
|
||||
setWallet(w);
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error('지갑 정보를 불러오지 못했습니다.');
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [toast]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
// 탭 이탈 시 개인키 초기화
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setPrivateKey('');
|
||||
setPassword('');
|
||||
setExportError('');
|
||||
};
|
||||
}, []);
|
||||
|
||||
const copyToClipboard = async (text, label) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
toast.success(`${label} 복사됨`);
|
||||
} catch {
|
||||
toast.error('복사에 실패했습니다.');
|
||||
}
|
||||
};
|
||||
|
||||
const handleExport = async (e) => {
|
||||
e.preventDefault();
|
||||
if (!password) return;
|
||||
setExportError('');
|
||||
setExporting(true);
|
||||
try {
|
||||
const data = await exportWalletKey(password);
|
||||
setPrivateKey(data.privateKey);
|
||||
} catch (err) {
|
||||
if (err.status === 401) {
|
||||
setExportError(err.message);
|
||||
} else {
|
||||
toast.error(err.message || '키 내보내기에 실패했습니다.');
|
||||
}
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <div className="wallet-spinner">불러오는 중...</div>;
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* 잔액 카드 */}
|
||||
<div className="wallet-card">
|
||||
<h3 className="wallet-card-title">TOL 잔액</h3>
|
||||
<p className="wallet-balance">
|
||||
{balance?.balance != null ? Number(balance.balance).toLocaleString() : '--'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 지갑 정보 */}
|
||||
{wallet && (
|
||||
<div className="wallet-card">
|
||||
<h3 className="wallet-card-title">지갑 정보</h3>
|
||||
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<div className="wallet-label">공개키</div>
|
||||
<div className="wallet-row">
|
||||
<span className="wallet-mono">{truncate(wallet.pubKeyHex, 4, 4)}</span>
|
||||
<button className="btn-copy" onClick={() => copyToClipboard(wallet.pubKeyHex, '공개키')}>
|
||||
복사
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="wallet-label">주소</div>
|
||||
<div className="wallet-row">
|
||||
<span className="wallet-mono">{truncate(wallet.address, 8, 8)}</span>
|
||||
<button className="btn-copy" onClick={() => copyToClipboard(wallet.address, '주소')}>
|
||||
복사
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 키 내보내기 */}
|
||||
<div className="wallet-card">
|
||||
<h3 className="wallet-card-title">개인키 내보내기</h3>
|
||||
|
||||
{!privateKey ? (
|
||||
<form onSubmit={handleExport} style={{ display: 'flex', gap: 8 }}>
|
||||
<input
|
||||
type="password"
|
||||
className="wallet-input"
|
||||
placeholder="비밀번호 입력"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
<button type="submit" className="btn-primary" disabled={!password || exporting}>
|
||||
{exporting ? '처리 중...' : '내보내기'}
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<div>
|
||||
<div className="wallet-row" style={{ marginBottom: 8 }}>
|
||||
<span className="wallet-mono" style={{ flex: 1 }}>{privateKey}</span>
|
||||
<button className="btn-copy" onClick={() => copyToClipboard(privateKey, '개인키')}>
|
||||
복사
|
||||
</button>
|
||||
</div>
|
||||
<p className="wallet-warning">개인키를 안전하게 보관하세요</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{exportError && <p className="wallet-error-text">{exportError}</p>}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,37 +1,65 @@
|
||||
import { createContext, useContext, useState, useCallback } from 'react';
|
||||
import { login as apiLogin } from '../api/auth';
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { login as apiLogin, logout as apiLogout } from '../api/auth';
|
||||
import { AuthContext } from './authContextValue';
|
||||
|
||||
const AuthContext = createContext(null);
|
||||
function decodeTokenPayload(token) {
|
||||
try {
|
||||
const payload = token.split('.')[1];
|
||||
return JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }) {
|
||||
const [user, setUser] = useState(() => {
|
||||
const token = localStorage.getItem('token');
|
||||
const username = localStorage.getItem('username');
|
||||
return token ? { token, username } : null;
|
||||
if (!token) return null;
|
||||
const payload = decodeTokenPayload(token);
|
||||
return { token, username, role: payload?.role || 'user' };
|
||||
});
|
||||
|
||||
// 토큰 저장 + 유저 상태 업데이트 공통 처리 (login, setUserFromSSAFY에서 공유)
|
||||
const applySession = useCallback((data) => {
|
||||
localStorage.setItem('token', data.token);
|
||||
localStorage.setItem('username', data.username);
|
||||
const role = decodeTokenPayload(data.token)?.role || 'user';
|
||||
setUser({ token: data.token, username: data.username, role });
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (username, password) => {
|
||||
const data = await apiLogin(username, password);
|
||||
localStorage.setItem('token', data.token);
|
||||
localStorage.setItem('username', data.username);
|
||||
setUser({ token: data.token, username: data.username });
|
||||
}, []);
|
||||
applySession(data);
|
||||
}, [applySession]);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
// SSAFY OAuth 콜백에서 받은 토큰으로 로그인 처리
|
||||
const setUserFromSSAFY = useCallback((data) => {
|
||||
applySession(data);
|
||||
}, [applySession]);
|
||||
|
||||
// 로컬 세션만 정리 (토큰 만료·강제 로그아웃 시)
|
||||
const clearSession = useCallback(() => {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('username');
|
||||
setUser(null);
|
||||
}, []);
|
||||
|
||||
// 정상 로그아웃: 서버 세션(액세스 + 리프레시)도 삭제
|
||||
const logout = useCallback(async () => {
|
||||
try {
|
||||
await apiLogout();
|
||||
} catch { /* 서버 실패해도 로컬 세션은 정리 */ }
|
||||
clearSession();
|
||||
}, [clearSession]);
|
||||
|
||||
// 401 응답 시 서버 호출 없이 로컬 세션만 정리
|
||||
useEffect(() => {
|
||||
window.addEventListener('auth:unauthorized', clearSession);
|
||||
return () => window.removeEventListener('auth:unauthorized', clearSession);
|
||||
}, [clearSession]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, login, logout }}>
|
||||
<AuthContext.Provider value={{ user, login, logout, setUserFromSSAFY }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
|
||||
return ctx;
|
||||
}
|
||||
|
||||
3
src/context/authContextValue.js
Normal file
@@ -0,0 +1,3 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export const AuthContext = createContext(null);
|
||||
8
src/context/useAuth.js
Normal file
@@ -0,0 +1,8 @@
|
||||
import { useContext } from 'react';
|
||||
import { AuthContext } from './authContextValue';
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
|
||||
return ctx;
|
||||
}
|
||||
@@ -31,3 +31,53 @@ a {
|
||||
a:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
/* ── Game asset common classes ───────────────────── */
|
||||
|
||||
.btn-game {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
border: none;
|
||||
color: #fff;
|
||||
padding: 14px 40px;
|
||||
font-size: 1.1rem;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
background: url('/images/btn_normal.webp') center/100% 100% no-repeat;
|
||||
letter-spacing: 0.05em;
|
||||
overflow: hidden;
|
||||
text-decoration: none;
|
||||
transition: transform 0.15s, filter 0.15s;
|
||||
}
|
||||
.btn-game:hover { transform: translateY(-1px); filter: brightness(1.2); }
|
||||
.btn-game:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
|
||||
.btn-game > * { position: relative; z-index: 1; }
|
||||
|
||||
.card-game {
|
||||
position: relative;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.card-game::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: -8px;
|
||||
background: url('/images/card_frame.webp') center/100% 100% no-repeat;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
.card-game > * { position: relative; z-index: 1; }
|
||||
|
||||
.divider-game {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
height: 20px;
|
||||
background: url('/images/divider.webp') center/contain no-repeat;
|
||||
margin: 2rem auto;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.card-game::before { display: none; }
|
||||
.card-game { border: 1px solid rgba(186, 205, 176, 0.3); }
|
||||
}
|
||||
150
src/pages/AdminPage.css
Normal file
@@ -0,0 +1,150 @@
|
||||
.admin-page {
|
||||
min-height: 100vh;
|
||||
background-color: #2E2C2F;
|
||||
}
|
||||
|
||||
.admin-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 32px;
|
||||
border-bottom: 1px solid rgba(186, 205, 176, 0.1);
|
||||
}
|
||||
|
||||
.admin-header-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.admin-home-link {
|
||||
font-size: 0.85rem;
|
||||
color: rgba(186, 205, 176, 0.6);
|
||||
text-decoration: none;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.admin-home-link:hover {
|
||||
color: #BACDB0;
|
||||
}
|
||||
|
||||
.admin-title {
|
||||
font-size: 1.2rem;
|
||||
font-weight: 700;
|
||||
color: #BACDB0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.admin-header-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.admin-username {
|
||||
font-size: 0.9rem;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
}
|
||||
|
||||
.btn-admin-logout {
|
||||
padding: 8px 16px;
|
||||
background: transparent;
|
||||
color: rgba(186, 205, 176, 0.7);
|
||||
border: 1px solid rgba(186, 205, 176, 0.25);
|
||||
border-radius: 6px;
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.btn-admin-logout:hover {
|
||||
background: rgba(186, 205, 176, 0.08);
|
||||
}
|
||||
|
||||
.admin-tabs {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
padding: 16px 32px 0;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.admin-tab {
|
||||
padding: 10px 24px;
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.45);
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: color 0.2s, border-color 0.2s;
|
||||
margin-bottom: -1px;
|
||||
}
|
||||
|
||||
.admin-tab:hover {
|
||||
color: rgba(255, 255, 255, 0.75);
|
||||
}
|
||||
|
||||
.admin-tab.active {
|
||||
color: #BACDB0;
|
||||
border-bottom-color: #BACDB0;
|
||||
}
|
||||
|
||||
.admin-main {
|
||||
max-width: 900px;
|
||||
margin: 0 auto;
|
||||
padding: 32px 24px 80px;
|
||||
}
|
||||
|
||||
.admin-logo {
|
||||
height: 32px;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.admin-tabs-divider {
|
||||
width: 100%;
|
||||
max-width: 300px;
|
||||
height: 16px;
|
||||
background: url('/images/divider.webp') center/contain no-repeat;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* 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;
|
||||
}
|
||||
}
|
||||
58
src/pages/AdminPage.jsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useAuth } from '../context/useAuth';
|
||||
import AnnouncementAdmin from '../components/admin/AnnouncementAdmin';
|
||||
import DownloadAdmin from '../components/admin/DownloadAdmin';
|
||||
import UserAdmin from '../components/admin/UserAdmin';
|
||||
import './AdminPage.css';
|
||||
|
||||
const TABS = [
|
||||
{ key: 'announcement', label: '공지사항' },
|
||||
{ key: 'download', label: '다운로드 정보' },
|
||||
{ key: 'user', label: '유저 관리' },
|
||||
];
|
||||
|
||||
export default function AdminPage() {
|
||||
const { user, logout } = useAuth();
|
||||
const [tab, setTab] = useState('announcement');
|
||||
|
||||
return (
|
||||
<div className="admin-page">
|
||||
<header className="admin-header">
|
||||
<div className="admin-header-left">
|
||||
<Link to="/" className="admin-home-link">← 메인으로</Link>
|
||||
<img src="/images/logo.webp" alt="" className="admin-logo" />
|
||||
<h1 className="admin-title">관리자 페이지</h1>
|
||||
</div>
|
||||
<div className="admin-header-right">
|
||||
<span className="admin-username">{user?.username}</span>
|
||||
<button className="btn-admin-logout" onClick={logout}>로그아웃</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="admin-tabs" role="tablist">
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
role="tab"
|
||||
id={`tab-${t.key}`}
|
||||
aria-selected={tab === t.key}
|
||||
aria-controls={`tabpanel-${t.key}`}
|
||||
className={`admin-tab${tab === t.key ? ' active' : ''}`}
|
||||
onClick={() => setTab(t.key)}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="admin-tabs-divider"></div>
|
||||
|
||||
{/* Tabs are conditionally rendered (not hidden) to avoid stale data. Each panel re-fetches on mount. */}
|
||||
<main className="admin-main" role="tabpanel" id={`tabpanel-${tab}`} aria-labelledby={`tab-${tab}`}>
|
||||
{tab === 'announcement' && <AnnouncementAdmin />}
|
||||
{tab === 'download' && <DownloadAdmin />}
|
||||
{tab === 'user' && <UserAdmin />}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -77,6 +77,13 @@
|
||||
border-color: #BACDB0;
|
||||
}
|
||||
|
||||
.login-success {
|
||||
color: #81c784;
|
||||
font-size: 0.85rem;
|
||||
margin: 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.login-error {
|
||||
color: #e57373;
|
||||
font-size: 0.85rem;
|
||||
@@ -144,6 +151,13 @@
|
||||
border-color: rgba(186, 205, 176, 0.5);
|
||||
}
|
||||
|
||||
.login-logo {
|
||||
max-width: 120px;
|
||||
height: auto;
|
||||
margin: 0 auto 16px;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.login-back {
|
||||
display: block;
|
||||
text-align: center;
|
||||
@@ -157,3 +171,66 @@
|
||||
.login-back:hover {
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
|
||||
/* Validation feedback */
|
||||
.input-hint {
|
||||
font-size: 0.75rem;
|
||||
color: #888;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.input-hint-error {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -3,21 +3,44 @@
|
||||
background-color: #2E2C2F;
|
||||
}
|
||||
|
||||
/* Header */
|
||||
/* Header - fixed with scroll effect */
|
||||
.home-header {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 100;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 32px;
|
||||
background: transparent;
|
||||
transition: background 0.3s;
|
||||
}
|
||||
|
||||
.home-header.scrolled {
|
||||
background: rgba(46, 44, 47, 0.85);
|
||||
backdrop-filter: blur(10px);
|
||||
border-bottom: 1px solid rgba(186, 205, 176, 0.1);
|
||||
}
|
||||
|
||||
.home-logo {
|
||||
font-size: 1.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.home-logo img {
|
||||
height: 40px;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.home-logo-text {
|
||||
font-size: 1.2rem;
|
||||
font-weight: 800;
|
||||
color: #BACDB0;
|
||||
letter-spacing: 0.1em;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.home-user {
|
||||
@@ -47,6 +70,21 @@
|
||||
border-color: rgba(186, 205, 176, 0.45);
|
||||
}
|
||||
|
||||
.btn-admin-link {
|
||||
padding: 8px 16px;
|
||||
background: transparent;
|
||||
color: rgba(186, 205, 176, 0.7);
|
||||
border: 1px solid rgba(186, 205, 176, 0.25);
|
||||
border-radius: 6px;
|
||||
font-size: 0.8rem;
|
||||
text-decoration: none;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.btn-admin-link:hover {
|
||||
background: rgba(186, 205, 176, 0.08);
|
||||
}
|
||||
|
||||
.btn-header-login {
|
||||
padding: 8px 20px;
|
||||
background: #BACDB0;
|
||||
@@ -62,13 +100,11 @@
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
/* Hero banner */
|
||||
/* Hero banner - fullscreen with game background */
|
||||
.hero-banner {
|
||||
position: relative;
|
||||
height: 280px;
|
||||
background:
|
||||
linear-gradient(135deg, rgba(46, 44, 47, 0.85), rgba(46, 44, 47, 0.6)),
|
||||
linear-gradient(135deg, #2E2C2F 0%, #3a3a3a 50%, #2E2C2F 100%);
|
||||
min-height: 100vh;
|
||||
background: url('/images/bg_loading.webp') center/cover no-repeat;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -79,28 +115,62 @@
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background:
|
||||
radial-gradient(ellipse at 30% 40%, rgba(186, 205, 176, 0.12) 0%, transparent 60%),
|
||||
radial-gradient(ellipse at 70% 60%, rgba(186, 205, 176, 0.06) 0%, transparent 50%);
|
||||
background: linear-gradient(
|
||||
to bottom,
|
||||
rgba(0, 0, 0, 0.7) 0%,
|
||||
rgba(0, 0, 0, 0.3) 50%,
|
||||
rgba(0, 0, 0, 0.8) 100%
|
||||
);
|
||||
}
|
||||
|
||||
.hero-overlay {
|
||||
position: relative;
|
||||
text-align: center;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.hero-logo {
|
||||
width: 200px;
|
||||
height: auto;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.hero-title {
|
||||
font-size: 2.8rem;
|
||||
font-size: 3rem;
|
||||
font-weight: 800;
|
||||
color: #BACDB0;
|
||||
letter-spacing: 0.12em;
|
||||
letter-spacing: 0.15em;
|
||||
text-shadow: 0 2px 20px rgba(0, 0, 0, 0.5);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.hero-desc {
|
||||
font-size: 1rem;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
font-size: 1.1rem;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
letter-spacing: 0.3em;
|
||||
margin: 12px 0 0;
|
||||
text-shadow: 0 1px 10px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.hero-cta {
|
||||
margin-top: 40px;
|
||||
}
|
||||
|
||||
.hero-scroll-hint {
|
||||
position: absolute;
|
||||
bottom: 32px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
font-size: 0.8rem;
|
||||
animation: bounce 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes bounce {
|
||||
0%, 100% { transform: translateX(-50%) translateY(0); }
|
||||
50% { transform: translateX(-50%) translateY(-8px); }
|
||||
}
|
||||
|
||||
/* Main content */
|
||||
@@ -109,3 +179,48 @@
|
||||
margin: 0 auto;
|
||||
padding: 40px 24px 80px;
|
||||
}
|
||||
|
||||
/* Mobile responsive */
|
||||
@media (max-width: 768px) {
|
||||
.home-header {
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.home-header.scrolled {
|
||||
padding: 8px 16px;
|
||||
}
|
||||
|
||||
.home-user {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.hero-banner {
|
||||
min-height: 80vh;
|
||||
}
|
||||
|
||||
.hero-logo {
|
||||
width: 120px;
|
||||
}
|
||||
|
||||
.hero-title {
|
||||
font-size: 1.8rem;
|
||||
}
|
||||
|
||||
.hero-desc {
|
||||
font-size: 0.85rem;
|
||||
letter-spacing: 0.15em;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,36 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { useAuth } from '../context/useAuth';
|
||||
import DownloadSection from '../components/DownloadSection';
|
||||
import WalletSummary from '../components/wallet/WalletSummary';
|
||||
import AnnouncementBoard from '../components/AnnouncementBoard';
|
||||
import './HomePage.css';
|
||||
|
||||
export default function HomePage() {
|
||||
const { user, logout } = useAuth();
|
||||
const [scrolled, setScrolled] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const onScroll = () => setScrolled(window.scrollY > 50);
|
||||
window.addEventListener('scroll', onScroll);
|
||||
return () => window.removeEventListener('scroll', onScroll);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="home-page">
|
||||
<header className="home-header">
|
||||
<h1 className="home-logo">A301</h1>
|
||||
<header className={`home-header${scrolled ? ' scrolled' : ''}`}>
|
||||
<Link to="/" className="home-logo">
|
||||
<img src="/images/logo.webp" alt="One of the Plans" />
|
||||
<span className="home-logo-text">One of the Plans</span>
|
||||
</Link>
|
||||
<div className="home-user">
|
||||
{user ? (
|
||||
<>
|
||||
<span className="home-username">{user.username}</span>
|
||||
<Link to="/wallet" className="btn-admin-link">지갑</Link>
|
||||
{user.role === 'admin' && (
|
||||
<Link to="/admin" className="btn-admin-link">관리자</Link>
|
||||
)}
|
||||
<button className="btn-logout" onClick={logout}>로그아웃</button>
|
||||
</>
|
||||
) : (
|
||||
@@ -25,13 +41,29 @@ export default function HomePage() {
|
||||
|
||||
<section className="hero-banner">
|
||||
<div className="hero-overlay">
|
||||
<h2 className="hero-title">A301 MULTIPLAYER</h2>
|
||||
<p className="hero-desc">Unity 3D 멀티플레이어 테스트에 참여하세요</p>
|
||||
<img src="/images/logo.webp" alt="" className="hero-logo" />
|
||||
<h2 className="hero-title">One of the Plans</h2>
|
||||
<p className="hero-desc">MULTIPLAYER BOSS RAID</p>
|
||||
<div className="hero-cta">
|
||||
{user ? (
|
||||
<a href="#download" className="btn-game">
|
||||
<span>게임 시작</span>
|
||||
</a>
|
||||
) : (
|
||||
<Link to="/login" className="btn-game">
|
||||
<span>로그인</span>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="hero-scroll-hint">▼ 스크롤</div>
|
||||
</section>
|
||||
|
||||
<main className="home-main">
|
||||
<main className="home-main" id="download">
|
||||
<div className="divider-game"></div>
|
||||
{user && <WalletSummary />}
|
||||
<DownloadSection />
|
||||
<div className="divider-game"></div>
|
||||
<AnnouncementBoard />
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import './LoginPage.css';
|
||||
import { useNavigate, Link, useLocation } from 'react-router-dom';
|
||||
import { useAuth } from '../context/useAuth';
|
||||
import { getSSAFYLoginURL } from '../api/auth';
|
||||
import './AuthPage.css';
|
||||
|
||||
export default function LoginPage() {
|
||||
const [username, setUsername] = useState('');
|
||||
@@ -10,10 +11,28 @@ export default function LoginPage() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const justRegistered = location.state?.registered;
|
||||
|
||||
const handleSSAFYLogin = async () => {
|
||||
try {
|
||||
const data = await getSSAFYLoginURL();
|
||||
if (!data.url || !data.url.startsWith('https://')) {
|
||||
throw new Error('유효하지 않은 로그인 URL입니다.');
|
||||
}
|
||||
window.location.href = data.url;
|
||||
} catch {
|
||||
setError('SSAFY 로그인 URL을 가져올 수 없습니다.');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
if (!username.trim() || !password) {
|
||||
setError('아이디와 비밀번호를 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
await login(username, password);
|
||||
@@ -29,7 +48,7 @@ export default function LoginPage() {
|
||||
<div className="login-page">
|
||||
<div className="login-panel">
|
||||
<div className="login-header">
|
||||
<h1 className="game-title">A301</h1>
|
||||
<h1 className="game-title">One of the plans</h1>
|
||||
<p className="game-subtitle">MULTIPLAYER</p>
|
||||
</div>
|
||||
|
||||
@@ -43,6 +62,8 @@ export default function LoginPage() {
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="아이디를 입력하세요"
|
||||
autoComplete="username"
|
||||
maxLength={50}
|
||||
aria-describedby={error ? 'login-error' : undefined}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -55,10 +76,13 @@ export default function LoginPage() {
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="비밀번호를 입력하세요"
|
||||
autoComplete="current-password"
|
||||
maxLength={72}
|
||||
aria-describedby={error ? 'login-error' : undefined}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className="login-error">{error}</p>}
|
||||
{justRegistered && <p className="login-success">회원가입이 완료되었습니다. 로그인해주세요.</p>}
|
||||
{error && <p id="login-error" className="login-error" role="alert">{error}</p>}
|
||||
|
||||
<button type="submit" className="btn-login" disabled={loading}>
|
||||
{loading ? '로그인 중...' : '로그인'}
|
||||
@@ -72,11 +96,12 @@ export default function LoginPage() {
|
||||
<button
|
||||
type="button"
|
||||
className="btn-ssafy"
|
||||
onClick={() => alert('SSAFY 로그인은 준비 중입니다.')}
|
||||
onClick={handleSSAFYLogin}
|
||||
>
|
||||
SSAFY 계정으로 로그인
|
||||
</button>
|
||||
|
||||
<Link to="/register" className="login-back">계정이 없으신가요? 회원가입</Link>
|
||||
<Link to="/" className="login-back">메인으로 돌아가기</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
129
src/pages/LoginPage.test.jsx
Normal file
@@ -0,0 +1,129 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import LoginPage from './LoginPage';
|
||||
|
||||
// Mock useAuth
|
||||
const mockLogin = vi.fn();
|
||||
vi.mock('../context/useAuth', () => ({
|
||||
useAuth: () => ({ login: mockLogin }),
|
||||
}));
|
||||
|
||||
// Mock auth API
|
||||
vi.mock('../api/auth', () => ({
|
||||
getSSAFYLoginURL: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock useNavigate
|
||||
const mockNavigate = vi.fn();
|
||||
vi.mock('react-router-dom', async () => {
|
||||
const actual = await vi.importActual('react-router-dom');
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: () => mockNavigate,
|
||||
};
|
||||
});
|
||||
|
||||
function renderLoginPage() {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<LoginPage />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('LoginPage', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the login form with all elements', () => {
|
||||
renderLoginPage();
|
||||
expect(screen.getByText('One of the plans')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('아이디')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('비밀번호')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: '로그인' })).toBeInTheDocument();
|
||||
expect(screen.getByText('SSAFY 계정으로 로그인')).toBeInTheDocument();
|
||||
expect(screen.getByText(/회원가입/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('validation', () => {
|
||||
it('shows error when both fields are empty', async () => {
|
||||
renderLoginPage();
|
||||
fireEvent.click(screen.getByRole('button', { name: '로그인' }));
|
||||
expect(
|
||||
await screen.findByText('아이디와 비밀번호를 입력해주세요.'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error when username is empty (whitespace only)', async () => {
|
||||
renderLoginPage();
|
||||
fireEvent.change(screen.getByLabelText('아이디'), { target: { value: ' ' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'pass' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '로그인' }));
|
||||
expect(
|
||||
await screen.findByText('아이디와 비밀번호를 입력해주세요.'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error when password is empty', async () => {
|
||||
renderLoginPage();
|
||||
fireEvent.change(screen.getByLabelText('아이디'), { target: { value: 'user' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '로그인' }));
|
||||
expect(
|
||||
await screen.findByText('아이디와 비밀번호를 입력해주세요.'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('login flow', () => {
|
||||
it('calls login and navigates on success', async () => {
|
||||
mockLogin.mockResolvedValueOnce({});
|
||||
|
||||
renderLoginPage();
|
||||
fireEvent.change(screen.getByLabelText('아이디'), { target: { value: 'testuser' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'password1' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '로그인' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockLogin).toHaveBeenCalledWith('testuser', 'password1');
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/', { replace: true });
|
||||
});
|
||||
});
|
||||
|
||||
it('displays error on login failure', async () => {
|
||||
mockLogin.mockRejectedValueOnce(new Error('잘못된 아이디 또는 비밀번호입니다.'));
|
||||
|
||||
renderLoginPage();
|
||||
fireEvent.change(screen.getByLabelText('아이디'), { target: { value: 'testuser' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'wrong' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '로그인' }));
|
||||
|
||||
expect(
|
||||
await screen.findByText('잘못된 아이디 또는 비밀번호입니다.'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows loading state while submitting', async () => {
|
||||
// Make login hang so we can observe the loading state
|
||||
let resolveLogin;
|
||||
mockLogin.mockReturnValueOnce(new Promise((r) => { resolveLogin = r; }));
|
||||
|
||||
renderLoginPage();
|
||||
fireEvent.change(screen.getByLabelText('아이디'), { target: { value: 'user' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'pass' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '로그인' }));
|
||||
|
||||
expect(await screen.findByText('로그인 중...')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: '로그인 중...' })).toBeDisabled();
|
||||
|
||||
// Resolve to clean up
|
||||
resolveLogin({});
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('로그인 중...')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
11
src/pages/NotFoundPage.jsx
Normal file
@@ -0,0 +1,11 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
export default function NotFoundPage() {
|
||||
return (
|
||||
<div style={{ padding: '2rem', textAlign: 'center', color: '#aaa' }}>
|
||||
<h2>404</h2>
|
||||
<p>페이지를 찾을 수 없습니다</p>
|
||||
<Link to="/" style={{ color: '#4ea8de' }}>홈으로 돌아가기</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
148
src/pages/RegisterPage.jsx
Normal file
@@ -0,0 +1,148 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import { register } from '../api/auth';
|
||||
import './AuthPage.css';
|
||||
|
||||
const USERNAME_REGEX = /^[a-z0-9_-]{3,50}$/;
|
||||
|
||||
function getPasswordStrength(pw) {
|
||||
if (pw.length === 0) return { label: '', level: '' };
|
||||
if (pw.length < 6) return { label: '약함', level: 'weak' };
|
||||
if (pw.length < 10) return { label: '중간', level: 'medium' };
|
||||
return { label: '강함', level: 'strong' };
|
||||
}
|
||||
|
||||
export default function RegisterPage() {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirm, setConfirm] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [usernameTouched, setUsernameTouched] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const isUsernameValid = USERNAME_REGEX.test(username);
|
||||
const showUsernameError = usernameTouched && username.length > 0 && !isUsernameValid;
|
||||
const showUsernameValid = usernameTouched && username.length > 0 && isUsernameValid;
|
||||
|
||||
const passwordStrength = getPasswordStrength(password);
|
||||
const confirmMismatch = confirm.length > 0 && password !== confirm;
|
||||
const confirmMatch = confirm.length > 0 && password === confirm;
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
|
||||
const trimmed = username.trim().toLowerCase();
|
||||
if (trimmed.length === 0) {
|
||||
setError('아이디를 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
if (trimmed.length < 3) {
|
||||
setError('아이디는 3자 이상이어야 합니다.');
|
||||
return;
|
||||
}
|
||||
if (!USERNAME_REGEX.test(trimmed)) {
|
||||
setError('아이디는 영문 소문자, 숫자, _, -만 사용 가능합니다.');
|
||||
return;
|
||||
}
|
||||
if (password !== confirm) {
|
||||
setError('비밀번호가 일치하지 않습니다.');
|
||||
return;
|
||||
}
|
||||
if (password.length < 6) {
|
||||
setError('비밀번호는 6자 이상이어야 합니다.');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
await register(trimmed, password);
|
||||
navigate('/login', { state: { registered: true } });
|
||||
} catch (err) {
|
||||
setError(err.message || '회원가입에 실패했습니다.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="login-page">
|
||||
<div className="login-panel">
|
||||
<div className="login-header">
|
||||
<img src="/images/logo.webp" alt="One of the Plans" className="login-logo" />
|
||||
<h1 className="game-title">One of the plans</h1>
|
||||
<p className="game-subtitle">MULTIPLAYER</p>
|
||||
</div>
|
||||
|
||||
<form className="login-form" onSubmit={handleSubmit}>
|
||||
<div className="input-group">
|
||||
<label htmlFor="username">아이디</label>
|
||||
<input
|
||||
id="username"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
onBlur={() => setUsernameTouched(true)}
|
||||
placeholder="아이디를 입력하세요"
|
||||
autoComplete="username"
|
||||
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 className="input-group">
|
||||
<label htmlFor="password">비밀번호</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="6자 이상 입력하세요"
|
||||
autoComplete="new-password"
|
||||
maxLength={72}
|
||||
aria-describedby="password-strength"
|
||||
/>
|
||||
{passwordStrength.label && (
|
||||
<span id="password-strength" className={`password-strength strength-${passwordStrength.level}`}>
|
||||
강도: {passwordStrength.label}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label htmlFor="confirm">비밀번호 확인</label>
|
||||
<input
|
||||
id="confirm"
|
||||
type="password"
|
||||
value={confirm}
|
||||
onChange={(e) => setConfirm(e.target.value)}
|
||||
placeholder="비밀번호를 다시 입력하세요"
|
||||
autoComplete="new-password"
|
||||
maxLength={72}
|
||||
className={confirmMatch ? 'input-valid' : confirmMismatch ? 'input-invalid' : ''}
|
||||
aria-describedby="confirm-hint"
|
||||
/>
|
||||
<span id="confirm-hint" className={`input-hint ${confirmMismatch ? 'input-hint-error' : confirmMatch ? 'input-hint-success' : ''}`}>
|
||||
{confirmMismatch && '비밀번호가 일치하지 않습니다'}
|
||||
{confirmMatch && `비밀번호가 일치합니다 \u2713`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{error && <p className="login-error" role="alert">{error}</p>}
|
||||
|
||||
<button type="submit" className="btn-login btn-game" disabled={loading}>
|
||||
{loading ? '처리 중...' : '회원가입'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<Link to="/login" className="login-back">이미 계정이 있으신가요? 로그인</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
133
src/pages/RegisterPage.test.jsx
Normal file
@@ -0,0 +1,133 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import RegisterPage from './RegisterPage';
|
||||
|
||||
// Mock the auth API
|
||||
vi.mock('../api/auth', () => ({
|
||||
register: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock useNavigate
|
||||
const mockNavigate = vi.fn();
|
||||
vi.mock('react-router-dom', async () => {
|
||||
const actual = await vi.importActual('react-router-dom');
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: () => mockNavigate,
|
||||
};
|
||||
});
|
||||
|
||||
function renderRegisterPage() {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<RegisterPage />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('RegisterPage', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the registration form', () => {
|
||||
renderRegisterPage();
|
||||
expect(screen.getByLabelText('아이디')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('비밀번호')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('비밀번호 확인')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: '회원가입' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('username validation', () => {
|
||||
it('shows error when username is empty', async () => {
|
||||
renderRegisterPage();
|
||||
fireEvent.click(screen.getByRole('button', { name: '회원가입' }));
|
||||
expect(await screen.findByText('아이디를 입력해주세요.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error when username is less than 3 characters', async () => {
|
||||
renderRegisterPage();
|
||||
fireEvent.change(screen.getByLabelText('아이디'), { target: { value: 'ab' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'password1' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호 확인'), { target: { value: 'password1' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '회원가입' }));
|
||||
expect(await screen.findByText('아이디는 3자 이상이어야 합니다.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error when username contains invalid characters', async () => {
|
||||
renderRegisterPage();
|
||||
fireEvent.change(screen.getByLabelText('아이디'), { target: { value: 'user@name' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'password1' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호 확인'), { target: { value: 'password1' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '회원가입' }));
|
||||
expect(
|
||||
await screen.findByText('아이디는 영문 소문자, 숫자, _, -만 사용 가능합니다.'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('password strength', () => {
|
||||
it('shows "약함" for passwords shorter than 6 characters', () => {
|
||||
renderRegisterPage();
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abc' } });
|
||||
expect(screen.getByText(/약함/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "중간" for passwords of 6-9 characters', () => {
|
||||
renderRegisterPage();
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abcdef' } });
|
||||
expect(screen.getByText(/중간/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "강함" for passwords of 10+ characters', () => {
|
||||
renderRegisterPage();
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'abcdefghij' } });
|
||||
expect(screen.getByText(/강함/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('password confirmation', () => {
|
||||
it('shows error when passwords do not match', async () => {
|
||||
renderRegisterPage();
|
||||
fireEvent.change(screen.getByLabelText('아이디'), { target: { value: 'testuser' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'password1' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호 확인'), { target: { value: 'different' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '회원가입' }));
|
||||
expect(await screen.findByText('비밀번호가 일치하지 않습니다.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('form submission', () => {
|
||||
it('calls register and navigates on success', async () => {
|
||||
const { register } = await import('../api/auth');
|
||||
register.mockResolvedValueOnce({});
|
||||
|
||||
renderRegisterPage();
|
||||
fireEvent.change(screen.getByLabelText('아이디'), { target: { value: 'testuser' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'password1' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호 확인'), { target: { value: 'password1' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '회원가입' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(register).toHaveBeenCalledWith('testuser', 'password1');
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/login', { state: { registered: true } });
|
||||
});
|
||||
});
|
||||
|
||||
it('displays error message on registration failure', async () => {
|
||||
const { register } = await import('../api/auth');
|
||||
register.mockRejectedValueOnce(new Error('이미 존재하는 아이디입니다.'));
|
||||
|
||||
renderRegisterPage();
|
||||
fireEvent.change(screen.getByLabelText('아이디'), { target: { value: 'existing' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호'), { target: { value: 'password1' } });
|
||||
fireEvent.change(screen.getByLabelText('비밀번호 확인'), { target: { value: 'password1' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '회원가입' }));
|
||||
|
||||
expect(await screen.findByText('이미 존재하는 아이디입니다.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
55
src/pages/SSAFYCallbackPage.jsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import { useEffect, useState, useRef } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useAuth } from '../context/useAuth';
|
||||
import { ssafyCallback } from '../api/auth';
|
||||
import './AuthPage.css';
|
||||
|
||||
// Inline styles are intentional for this simple callback/loading page — layout only, AuthPage.css handles buttons.
|
||||
export default function SSAFYCallbackPage() {
|
||||
const [error, setError] = useState('');
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const { setUserFromSSAFY } = useAuth();
|
||||
// useRef(false) prevents double-execution in React 18+ StrictMode,
|
||||
// which remounts components in development. The ref persists across
|
||||
// the StrictMode remount, ensuring the OAuth callback runs only once.
|
||||
const called = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (called.current) return;
|
||||
called.current = true;
|
||||
|
||||
const code = searchParams.get('code');
|
||||
const state = searchParams.get('state');
|
||||
if (!code) {
|
||||
setError('인가 코드가 없습니다.'); // eslint-disable-line react-hooks/set-state-in-effect -- error state from URL param check
|
||||
return;
|
||||
}
|
||||
|
||||
ssafyCallback(code, state)
|
||||
.then((data) => {
|
||||
setUserFromSSAFY(data);
|
||||
navigate('/', { replace: true });
|
||||
})
|
||||
.catch((err) => {
|
||||
setError(err.message || 'SSAFY 로그인에 실패했습니다.');
|
||||
});
|
||||
}, [searchParams, setUserFromSSAFY, navigate]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div style={{ textAlign: 'center', marginTop: '4rem' }}>
|
||||
<p style={{ color: '#e74c3c' }}>{error}</p>
|
||||
<button className="btn-login" onClick={() => navigate('/login', { replace: true })}>
|
||||
로그인 페이지로 돌아가기
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ textAlign: 'center', marginTop: '4rem' }}>
|
||||
<p>SSAFY 로그인 처리 중...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
433
src/pages/WalletPage.css
Normal file
@@ -0,0 +1,433 @@
|
||||
.wallet-page {
|
||||
min-height: 100vh;
|
||||
background-color: #2E2C2F;
|
||||
}
|
||||
|
||||
.wallet-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 32px;
|
||||
border-bottom: 1px solid rgba(186, 205, 176, 0.1);
|
||||
}
|
||||
|
||||
.wallet-header-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.wallet-home-link {
|
||||
font-size: 0.85rem;
|
||||
color: rgba(186, 205, 176, 0.6);
|
||||
text-decoration: none;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.wallet-home-link:hover {
|
||||
color: #BACDB0;
|
||||
}
|
||||
|
||||
.wallet-title {
|
||||
font-size: 1.2rem;
|
||||
font-weight: 700;
|
||||
color: #BACDB0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.wallet-header-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.wallet-username {
|
||||
font-size: 0.9rem;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
}
|
||||
|
||||
.btn-wallet-logout {
|
||||
padding: 8px 16px;
|
||||
background: transparent;
|
||||
color: rgba(186, 205, 176, 0.7);
|
||||
border: 1px solid rgba(186, 205, 176, 0.25);
|
||||
border-radius: 6px;
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.btn-wallet-logout:hover {
|
||||
background: rgba(186, 205, 176, 0.08);
|
||||
}
|
||||
|
||||
.wallet-tabs {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
padding: 16px 32px 0;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.wallet-tab {
|
||||
padding: 10px 24px;
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.45);
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: color 0.2s, border-color 0.2s;
|
||||
margin-bottom: -1px;
|
||||
}
|
||||
|
||||
.wallet-tab:hover {
|
||||
color: rgba(255, 255, 255, 0.75);
|
||||
}
|
||||
|
||||
.wallet-tab.active {
|
||||
color: #BACDB0;
|
||||
border-bottom-color: #BACDB0;
|
||||
}
|
||||
|
||||
.wallet-main {
|
||||
max-width: 900px;
|
||||
margin: 0 auto;
|
||||
padding: 32px 24px 80px;
|
||||
}
|
||||
|
||||
/* === Tab content shared styles === */
|
||||
|
||||
.wallet-card {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border: 1px solid rgba(186, 205, 176, 0.12);
|
||||
border-radius: 8px;
|
||||
padding: 24px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.wallet-card-title {
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
letter-spacing: 0.08em;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.wallet-balance {
|
||||
font-size: 2rem;
|
||||
font-weight: 700;
|
||||
color: #BACDB0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.wallet-mono {
|
||||
font-family: monospace;
|
||||
font-size: 0.85rem;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.wallet-label {
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.wallet-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.btn-copy {
|
||||
padding: 4px 12px;
|
||||
background: transparent;
|
||||
color: rgba(186, 205, 176, 0.6);
|
||||
border: 1px solid rgba(186, 205, 176, 0.2);
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.btn-copy:hover {
|
||||
background: rgba(186, 205, 176, 0.08);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
padding: 8px 20px;
|
||||
background: #BACDB0;
|
||||
color: #2E2C2F;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.btn-primary:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-danger-outline {
|
||||
padding: 8px 20px;
|
||||
background: transparent;
|
||||
color: #e57373;
|
||||
border: 1px solid rgba(229, 115, 115, 0.4);
|
||||
border-radius: 6px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.btn-danger-outline:hover {
|
||||
background: rgba(229, 115, 115, 0.08);
|
||||
}
|
||||
|
||||
.wallet-input {
|
||||
padding: 8px 12px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(186, 205, 176, 0.2);
|
||||
border-radius: 6px;
|
||||
color: #fff;
|
||||
font-size: 0.85rem;
|
||||
outline: none;
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
.wallet-input:focus {
|
||||
border-color: rgba(186, 205, 176, 0.5);
|
||||
}
|
||||
|
||||
.wallet-input::placeholder {
|
||||
color: rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
|
||||
.wallet-spinner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 60px 0;
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.wallet-empty {
|
||||
text-align: center;
|
||||
padding: 40px 0;
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.wallet-error-text {
|
||||
color: #e57373;
|
||||
font-size: 0.85rem;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.wallet-warning {
|
||||
color: #ffb74d;
|
||||
font-size: 0.8rem;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.wallet-tag {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.wallet-tag-ok {
|
||||
background: rgba(186, 205, 176, 0.15);
|
||||
color: #BACDB0;
|
||||
}
|
||||
|
||||
.wallet-tag-no {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
|
||||
.wallet-tag-listed {
|
||||
background: rgba(78, 168, 222, 0.15);
|
||||
color: #4ea8de;
|
||||
}
|
||||
|
||||
/* Asset list */
|
||||
.asset-item {
|
||||
border: 1px solid rgba(186, 205, 176, 0.1);
|
||||
border-radius: 8px;
|
||||
margin-bottom: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.asset-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 14px 16px;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.asset-header:hover {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
|
||||
.asset-detail {
|
||||
padding: 0 16px 16px;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.asset-props {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 6px 16px;
|
||||
font-size: 0.85rem;
|
||||
margin: 12px 0;
|
||||
}
|
||||
|
||||
.asset-prop-key {
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
|
||||
.asset-prop-val {
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
}
|
||||
|
||||
/* Inventory slots */
|
||||
.inv-slot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid rgba(186, 205, 176, 0.1);
|
||||
border-radius: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.inv-slot-empty {
|
||||
border-style: dashed;
|
||||
color: rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
|
||||
/* Market listings */
|
||||
.market-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid rgba(186, 205, 176, 0.1);
|
||||
border-radius: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.market-price {
|
||||
font-weight: 600;
|
||||
color: #BACDB0;
|
||||
}
|
||||
|
||||
.market-seller {
|
||||
font-family: monospace;
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
|
||||
.market-filter {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.market-filter-btn {
|
||||
padding: 6px 16px;
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 6px;
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.market-filter-btn.active {
|
||||
color: #BACDB0;
|
||||
border-color: rgba(186, 205, 176, 0.4);
|
||||
background: rgba(186, 205, 176, 0.08);
|
||||
}
|
||||
|
||||
|
||||
.wallet-logo {
|
||||
height: 32px;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.wallet-tabs-divider {
|
||||
width: 100%;
|
||||
max-width: 300px;
|
||||
height: 16px;
|
||||
background: url('/images/divider.webp') center/contain no-repeat;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* Mobile responsive */
|
||||
@media (max-width: 768px) {
|
||||
.wallet-header {
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.wallet-header-left {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.wallet-header-right {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.wallet-tabs {
|
||||
padding: 12px 16px 0;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.wallet-tabs::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.wallet-tab {
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
min-height: 44px;
|
||||
}
|
||||
|
||||
.wallet-main {
|
||||
padding: 20px 12px 60px;
|
||||
}
|
||||
|
||||
.wallet-row {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.market-item {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
58
src/pages/WalletPage.jsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useAuth } from '../context/useAuth';
|
||||
import WalletTab from '../components/wallet/WalletTab';
|
||||
import AssetsTab from '../components/wallet/AssetsTab';
|
||||
import InventoryTab from '../components/wallet/InventoryTab';
|
||||
import MarketTab from '../components/wallet/MarketTab';
|
||||
import './WalletPage.css';
|
||||
|
||||
const TABS = [
|
||||
{ key: 'wallet', label: '지갑' },
|
||||
{ key: 'assets', label: '자산' },
|
||||
{ key: 'inventory', label: '인벤토리' },
|
||||
{ key: 'market', label: '마켓' },
|
||||
];
|
||||
|
||||
export default function WalletPage() {
|
||||
const { user, logout } = useAuth();
|
||||
const [tab, setTab] = useState('wallet');
|
||||
|
||||
return (
|
||||
<div className="wallet-page">
|
||||
<header className="wallet-header">
|
||||
<div className="wallet-header-left">
|
||||
<Link to="/" className="wallet-home-link">← 메인으로</Link>
|
||||
<h1 className="wallet-title">지갑</h1>
|
||||
</div>
|
||||
<div className="wallet-header-right">
|
||||
<span className="wallet-username">{user?.username}</span>
|
||||
<button className="btn-wallet-logout" onClick={logout}>로그아웃</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="wallet-tabs" role="tablist">
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
role="tab"
|
||||
id={`tab-${t.key}`}
|
||||
aria-selected={tab === t.key}
|
||||
aria-controls={`tabpanel-${t.key}`}
|
||||
className={`wallet-tab${tab === t.key ? ' active' : ''}`}
|
||||
onClick={() => setTab(t.key)}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<main className="wallet-main" role="tabpanel" id={`tabpanel-${tab}`} aria-labelledby={`tab-${tab}`}>
|
||||
{tab === 'wallet' && <WalletTab />}
|
||||
{tab === 'assets' && <AssetsTab />}
|
||||
{tab === 'inventory' && <InventoryTab />}
|
||||
{tab === 'market' && <MarketTab />}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
19
src/test/setup.js
Normal file
@@ -0,0 +1,19 @@
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -4,4 +4,14 @@ import react from '@vitejs/plugin-react'
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8080',
|
||||
},
|
||||
},
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
setupFiles: './src/test/setup.js',
|
||||
},
|
||||
})
|
||||
|
||||