Merge branch 'main' into zulip_dev

* main: (31 commits)
  docs:更新README中的测试说明
  chore:整理API测试脚本
  test:添加验证码冷却时间清除功能测试
  feat:集成验证码冷却时间自动清除机制
  feat:添加验证码冷却时间清除功能
  api:更新登录验证码接口Swagger注解
  docs:更新登录验证码邮件模板修复相关文档
  test:添加登录验证码邮件发送测试
  fix:修复登录验证码邮件模板错误
  feat: 邮箱冲突检测优化 v1.1.1
  docs: 更新API文档,反映HTTP状态码修复
  fix: 修复用户注册冲突错误的HTTP状态码问题
  chore: 升级版本到1.1.0
  feat(docs): 更新OpenAPI文档,添加验证码登录和完整接口定义
  fix(docs): 修正API文档中的错误码和验证码说明
  docs: 完善API文档,添加验证码登录功能说明
  fix:修复注册逻辑和HTTP状态码问题
  fix:修复API状态码和限流配置问题
  chore: 清理旧文件和更新项目配置
  refactor: 更新核心服务和应用配置
  ...
This commit is contained in:
angjustinl
2025-12-25 23:27:24 +08:00
101 changed files with 8501 additions and 2759 deletions

View File

106
docs/CONTRIBUTORS.md Normal file
View File

@@ -0,0 +1,106 @@
# 贡献者名单
感谢所有为 Whale Town 项目做出贡献的开发者们!🎉
## 核心贡献者
### 🏆 主要维护者
**moyin** - 主要维护者
- Gitea: [@moyin](https://gitea.xinghangee.icu/moyin)
- Email: xinghang_a@proton.me
- 提交数: **66 commits**
- 主要贡献:
- 🚀 项目架构设计与初始化
- 🔐 完整用户认证系统实现
- 📧 邮箱验证系统设计与开发
- 🗄️ Redis缓存服务文件存储+真实Redis双模式
- 📝 完整的API文档系统Swagger UI + OpenAPI
- 🧪 测试框架搭建与114个测试用例编写
- 📊 高性能日志系统集成Pino
- 🔧 项目配置优化与部署方案
- 🐛 验证码TTL重置关键问题修复
- 📚 完整的项目文档体系建设
### 🌟 核心开发者
**angjustinl** - 核心开发者
- Gitea: [@ANGJustinl](https://gitea.xinghangee.icu/ANGJustinl)
- GitHub: [@ANGJustinl](https://github.com/ANGJustinl)
- Email: 96008766+ANGJustinl@users.noreply.github.com
- 提交数: **2 commits**
- 主要贡献:
- 🔄 邮箱验证流程重构与优化
- 💾 基于内存的用户服务实现
- 🛠️ API响应处理改进
- 🧪 测试用例完善与错误修复
- 📚 系统架构优化
**jianuo** - 核心开发者
- Gitea: [@jianuo](https://gitea.xinghangee.icu/jianuo)
- Email: 32106500027@e.gzhu.edu.cn
- 提交数: **6 commits**
- 主要贡献:
- 🎛️ **管理员后台系统** - 完整的前后端管理界面开发
- 📊 **日志管理功能** - 运行时日志查看与下载系统
- 🔐 **管理员认证系统** - 独立Token认证与权限控制
- 🧪 **单元测试完善** - 管理员功能测试用例编写
- ⚙️ **TypeScript配置优化** - Node16模块解析配置
- 🐳 **Docker部署优化** - 容器化部署问题修复
- 📖 **技术栈文档更新** - 项目技术栈说明完善
## 贡献统计
| 贡献者 | 提交数 | 主要领域 | 贡献占比 |
|--------|--------|----------|----------|
| moyin | 66 | 架构设计、核心功能、文档、测试 | 88% |
| jianuo | 6 | 管理员后台、日志系统、部署优化 | 8% |
| angjustinl | 2 | 功能优化、测试、重构 | 3% |
## 项目里程碑
### 2025年12月
- **12月17日**: 项目初始化,完成基础架构搭建
- **12月17日**: 实现完整的用户认证系统
- **12月17日**: 完成API文档系统集成
- **12月17日**: 实现邮箱验证系统
- **12月17日**: 修复验证码TTL重置关键问题
- **12月18日**: angjustinl重构邮箱验证流程引入内存用户服务
- **12月18日**: jianuo修复Docker部署问题
- **12月18日**: 完成测试用例修复和优化
- **12月19日**: jianuo开发管理员后台系统
- **12月20日**: jianuo完善日志管理功能
- **12月21日**: jianuo添加管理员后台单元测试
- **12月22日**: 管理员后台功能合并到主分支
## 如何成为贡献者
我们欢迎所有形式的贡献!无论是:
- 🐛 **Bug修复** - 发现并修复问题
-**新功能** - 添加有价值的功能
- 📚 **文档改进** - 完善项目文档
- 🧪 **测试用例** - 提高代码覆盖率
- 🎨 **代码优化** - 改进代码质量
- 💡 **建议反馈** - 提出改进建议
### 贡献流程
1. Fork 项目到你的Gitea账户
2. 创建功能分支:`git checkout -b feature/your-feature`
3. 提交你的更改:`git commit -m "feat添加新功能"`
4. 推送到分支:`git push origin feature/your-feature`
5. 创建Pull Request
### 贡献规范
请在贡献前阅读:
- [AI辅助开发规范指南](./docs/AI辅助开发规范指南.md)
- [后端开发规范](./docs/backend_development_guide.md)
- [Git提交规范](./docs/git_commit_guide.md)
---
**再次感谢所有贡献者的辛勤付出!** 🙏
*如果你的名字没有出现在列表中请联系我们或提交PR更新此文件。*

View File

@@ -1,139 +1,107 @@
# 项目文档
# 📚 Pixel Game Server 文档中心
本目录包含了像素游戏服务器的完整文档
欢迎来到 Whale Town 项目文档中心!这里包含了项目的完整文档,帮助你快速了解和使用项目
## 文档结构
## 📖 **文档导航**
### 📁 api/
API接口相关文档包含
- **api-documentation.md** - 详细的API接口文档
- **openapi.yaml** - OpenAPI 3.0规范文件
- **postman-collection.json** - Postman测试集合
- **README.md** - API文档使用说明
### 🚀 **快速开始**
- [项目概述](../README.md) - 项目介绍和快速开始指南
- [架构设计](ARCHITECTURE.md) - 系统架构和设计理念
### 📁 systems/
系统设计文档,包含:
- **logger/** - 日志系统文档
- **user-auth/** - 用户认证系统文档
### 🔌 **API文档**
- [API接口文档](api/api-documentation.md) - 完整的API接口说明17个接口
- [API状态码](API_STATUS_CODES.md) - HTTP状态码和错误代码说明
- [OpenAPI规范](api/openapi.yaml) - 机器可读的API规范文件
- [API使用指南](api/README.md) - API文档使用说明
### 📄 其他文档
- **AI辅助开发规范指南.md** - AI开发规范
- **backend_development_guide.md** - 后端开发指南
- **git_commit_guide.md** - Git提交规范
- **naming_convention.md** - 命名规范
- **nestjs_guide.md** - NestJS开发指南
- **日志系统详细说明.md** - 日志系统说明
### 💻 **开发指南**
- [后端开发指南](development/backend_development_guide.md) - 后端开发规范和最佳实践
- [NestJS指南](development/nestjs_guide.md) - NestJS框架使用指南
- [命名规范](development/naming_convention.md) - 代码命名规范
- [Git提交规范](development/git_commit_guide.md) - Git提交消息规范
- [AI辅助开发规范](development/AI辅助开发规范指南.md) - AI辅助开发最佳实践
- [测试指南](development/TESTING.md) - 测试策略和规范
## 如何使用
### 🚀 **部署运维**
- [部署指南](deployment/DEPLOYMENT.md) - 生产环境部署说明
### 1. 启动服务器并查看Swagger文档
### 📋 **项目管理**
- [贡献指南](CONTRIBUTORS.md) - 如何参与项目贡献
- [文档清理说明](DOCUMENT_CLEANUP.md) - 文档维护记录
```bash
# 启动开发服务器
pnpm run dev
## 🏗️ **文档结构说明**
# 访问Swagger UI
# 浏览器打开: http://localhost:3000/api-docs
```
docs/
├── README.md # 📚 文档中心首页
├── ARCHITECTURE.md # 🏗️ 架构文档
├── API_STATUS_CODES.md # 📋 API状态码
├── CONTRIBUTORS.md # 🤝 贡献指南
├── DOCUMENT_CLEANUP.md # 📝 文档清理说明
├── api/ # 🔌 API文档
│ ├── api-documentation.md # API接口文档
│ ├── openapi.yaml # OpenAPI规范
│ ├── postman-collection.json # Postman测试集合
│ └── README.md # API文档说明
├── development/ # 💻 开发指南
│ ├── backend_development_guide.md
│ ├── nestjs_guide.md
│ ├── naming_convention.md
│ ├── git_commit_guide.md
│ ├── AI辅助开发规范指南.md
│ └── TESTING.md
└── deployment/ # 🚀 部署文档
└── DEPLOYMENT.md
```
### 2. 使用Postman测试API
## 🎯 **文档特色**
1. 打开Postman
2. 点击 Import 按钮
3. 选择 `docs/postman-collection.json` 文件
4. 导入后即可看到所有API接口
5. 修改环境变量 `baseUrl` 为你的服务器地址默认http://localhost:3000
### ✨ **业务功能模块化**
文档结构与代码架构保持一致,按业务功能组织:
- **用户认证模块** - 登录、注册、密码管理
- **用户管理模块** - 状态管理、批量操作
- **管理员模块** - 后台管理、权限控制
- **安全模块** - 频率限制、维护模式
### 3. 使用OpenAPI规范
### 📊 **完整API覆盖**
- **17个API接口** - 涵盖所有业务功能
- **交互式文档** - Swagger UI实时测试
- **标准化规范** - OpenAPI 3.0标准
- **测试集合** - Postman一键导入
#### 在Swagger Editor中查看
1. 访问 [Swagger Editor](https://editor.swagger.io/)
2.`docs/openapi.yaml` 的内容复制粘贴到编辑器中
3. 即可查看可视化的API文档
### 🔧 **开发者友好**
- **规范指导** - 命名、提交、开发规范
- **AI辅助** - 提升开发效率的AI使用指南
- **测试覆盖** - 140个测试用例全覆盖
- **部署就绪** - 生产环境部署指南
#### 生成客户端SDK
```bash
# 使用swagger-codegen生成JavaScript客户端
swagger-codegen generate -i docs/openapi.yaml -l javascript -o ./client-sdk
## 📝 **文档维护原则**
# 使用openapi-generator生成TypeScript客户端
openapi-generator generate -i docs/openapi.yaml -g typescript-axios -o ./client-sdk
```
### ✅ **保留的文档类型**
- **长期有用**:对整个项目生命周期都有价值的文档
- **参考价值**:开发、部署、维护时需要查阅的文档
- **规范指南**:团队协作和代码质量保证的规范
## API接口概览
### ❌ **不保留的文档类型**
- **阶段性文档**:只在特定开发阶段有用的文档
- **临时记录**:会议记录、临时决策等
- **过时信息**:已经不适用的旧版本文档
| 接口 | 方法 | 路径 | 描述 |
|------|------|------|------|
| 用户登录 | POST | /auth/login | 支持用户名、邮箱或手机号登录 |
| 用户注册 | POST | /auth/register | 创建新用户账户 |
| GitHub OAuth | POST | /auth/github | 使用GitHub账户登录或注册 |
| 发送验证码 | POST | /auth/forgot-password | 发送密码重置验证码 |
| 重置密码 | POST | /auth/reset-password | 使用验证码重置密码 |
| 修改密码 | PUT | /auth/change-password | 修改用户密码 |
### 🔄 **文档更新策略**
- **及时更新**:功能变更时同步更新相关文档
- **版本控制**:重要变更记录版本历史
- **定期审查**:定期检查文档的准确性和有效性
## 快速测试
## 🤝 **如何贡献文档**
### 使用cURL测试登录接口
1. **发现问题**发现文档错误或缺失时请提交Issue
2. **改进文档**按照项目规范提交Pull Request
3. **新增文档**:新功能开发时同步编写相关文档
4. **审查文档**:参与文档审查,确保质量和准确性
```bash
# 测试用户登录
curl -X POST http://localhost:3000/auth/login \
-H "Content-Type: application/json" \
-d '{
"identifier": "testuser",
"password": "password123"
}'
---
# 测试用户注册
curl -X POST http://localhost:3000/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "newuser",
"password": "password123",
"nickname": "新用户",
"email": "newuser@example.com"
}'
```
### 使用JavaScript测试
```javascript
// 用户登录
const response = await fetch('http://localhost:3000/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
identifier: 'testuser',
password: 'password123'
})
});
const data = await response.json();
console.log(data);
```
## 注意事项
1. **开发环境**: 当前配置适用于开发环境生产环境需要使用HTTPS
2. **认证**: 实际应用中应实现JWT认证机制
3. **限流**: 建议对认证接口实施限流策略
4. **验证码**: 示例中返回验证码仅用于演示,生产环境不应返回
5. **错误处理**: 建议实现统一的错误处理机制
## 更新文档
当API接口发生变化时请同步更新以下文件
1. 更新DTO类的Swagger装饰器
2. 更新 `api-documentation.md`
3. 更新 `openapi.yaml`
4. 更新 `postman-collection.json`
5. 重新生成Swagger文档
## 相关链接
- [NestJS Swagger文档](https://docs.nestjs.com/openapi/introduction)
- [OpenAPI规范](https://swagger.io/specification/)
- [Postman文档](https://learning.postman.com/docs/getting-started/introduction/)
- [Swagger Editor](https://editor.swagger.io/)
📧 **联系我们**如有文档相关问题请通过项目Issue或邮件联系维护团队。

View File

@@ -1,29 +1,30 @@
# API接口文档
本目录包含了像素游戏服务器用户认证API的完整文档
本目录包含了 Whale Town 像素游戏服务器的完整API文档采用业务功能模块化设计提供17个接口覆盖所有核心功能
## 📋 文档文件说明
### 1. api-documentation.md
详细的API接口文档包含
- **17个API接口** - 用户认证、用户管理、管理员功能、安全防护
- 接口概述和通用响应格式
- 每个接口的详细说明、参数、响应示例
- 错误代码说明
- 数据验证规则
- 错误代码说明和状态码映射
- 数据验证规则和业务逻辑
- 使用示例JavaScript/TypeScript 和 cURL
### 2. openapi.yaml
OpenAPI 3.0规范文件,可以用于:
- 导入到Swagger Editor查看和编辑
- 生成客户端SDK
- 集成到API网关
- 自动化测试
- 生成客户端SDK(支持多种语言)
- 集成到API网关和测试工具
- 自动化测试和文档生成
### 3. postman-collection.json
Postman集合文件包含
- 所有API接口的请求示例
- 预设的请求参数
- 响应示例
- 所有17个API接口的请求示例
- 预设的请求参数和环境变量
- 完整的响应示例和测试脚本
- 可直接导入Postman进行测试
## 🚀 快速开始
@@ -34,7 +35,7 @@ Postman集合文件包含
# 启动开发服务器
pnpm run dev
# 访问Swagger UI
# 访问Swagger UI(推荐)
# 浏览器打开: http://localhost:3000/api-docs
```
@@ -64,78 +65,144 @@ openapi-generator generate -i docs/api/openapi.yaml -g typescript-axios -o ./cli
## 📊 API接口概览
### 🔐 用户认证模块 (9个接口)
| 接口 | 方法 | 路径 | 描述 |
|------|------|------|------|
| 用户登录 | POST | /auth/login | 支持用户名、邮箱或手机号登录 |
| 用户注册 | POST | /auth/register | 创建新用户账户 |
| GitHub OAuth | POST | /auth/github | 使用GitHub账户登录或注册 |
| 发送验证码 | POST | /auth/forgot-password | 发送密码重置验证码 |
| 发送重置验证码 | POST | /auth/forgot-password | 发送密码重置验证码 |
| 重置密码 | POST | /auth/reset-password | 使用验证码重置密码 |
| 修改密码 | PUT | /auth/change-password | 修改用户密码 |
| 发送邮箱验证码 | POST | /auth/send-email-verification | 发送邮箱验证码 |
| 验证邮箱 | POST | /auth/verify-email | 验证邮箱验证码 |
| 重发邮箱验证码 | POST | /auth/resend-email-verification | 重新发送邮箱验证码 |
### 👥 用户管理模块 (3个接口)
| 接口 | 方法 | 路径 | 描述 |
|------|------|------|------|
| 修改用户状态 | PUT | /admin/users/:id/status | 修改指定用户状态 |
| 批量修改状态 | POST | /admin/users/batch-status | 批量修改用户状态 |
| 用户状态统计 | GET | /admin/users/status-stats | 获取各状态用户统计 |
### 🛡️ 管理员模块 (4个接口)
| 接口 | 方法 | 路径 | 描述 |
|------|------|------|------|
| 管理员登录 | POST | /admin/auth/login | 管理员身份认证 |
| 获取用户列表 | GET | /admin/users | 分页获取用户列表 |
| 获取用户详情 | GET | /admin/users/:id | 获取指定用户信息 |
| 重置用户密码 | POST | /admin/users/:id/reset-password | 管理员重置用户密码 |
### 📊 系统状态 (1个接口)
| 接口 | 方法 | 路径 | 描述 |
|------|------|------|------|
| 应用状态 | GET | / | 获取应用运行状态和系统信息 |
## 🧪 快速测试
### 使用cURL测试登录接口
### 使用cURL测试核心接口
```bash
# 测试用户登录
# 1. 测试应用状态
curl -X GET http://localhost:3000/
# 2. 测试用户注册
curl -X POST http://localhost:3000/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"password": "Test123456",
"nickname": "测试用户",
"email": "test@example.com"
}'
# 3. 测试用户登录
curl -X POST http://localhost:3000/auth/login \
-H "Content-Type: application/json" \
-d '{
"identifier": "testuser",
"password": "password123"
"password": "Test123456"
}'
# 测试用户注册
curl -X POST http://localhost:3000/auth/register \
# 4. 测试管理员登录
curl -X POST http://localhost:3000/admin/auth/login \
-H "Content-Type: application/json" \
-d '{
"username": "newuser",
"password": "password123",
"nickname": "新用户",
"email": "newuser@example.com"
"username": "admin",
"password": "Admin123456"
}'
```
### 使用JavaScript测试
```javascript
// 用户注册
const registerResponse = await fetch('http://localhost:3000/auth/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'testuser',
password: 'Test123456',
nickname: '测试用户',
email: 'test@example.com'
})
});
// 用户登录
const response = await fetch('http://localhost:3000/auth/login', {
const loginResponse = await fetch('http://localhost:3000/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
identifier: 'testuser',
password: 'password123'
password: 'Test123456'
})
});
const data = await response.json();
console.log(data);
const loginData = await loginResponse.json();
console.log('登录结果:', loginData);
```
### 使用自动化测试脚本
```bash
# Windows PowerShell
.\test-api.ps1
# Linux/macOS Bash
./test-api.sh
# 自定义测试参数
.\test-api.ps1 -BaseUrl "http://localhost:3000" -TestEmail "custom@example.com"
```
## ⚠️ 注意事项
1. **开发环境**: 当前配置适用于开发环境生产环境需要使用HTTPS
2. **认证**: 实际应用中应实现JWT认证机制
3. **限流**: 建议对认证接口实施限流策略
4. **验证码**: 示例中返回验证码仅用于演示,生产环境不应返回
5. **错误处理**: 建议实现统一的错误处理机制
2. **认证机制**: 项目使用JWT认证管理员使用独立的Token系统
3. **频率限制**: 已实现API频率限制登录接口2次/分钟管理员操作10次/分钟
4. **用户状态**: 支持6种用户状态管理active、inactive、locked、banned、deleted、pending
5. **测试模式**: 邮件服务支持测试模式,验证码会在控制台输出
6. **存储模式**: 支持Redis文件存储和内存数据库便于无依赖测试
7. **安全防护**: 实现了维护模式、内容类型检查、超时控制等安全机制
## 🔄 更新文档
当API接口发生变化时请同步更新以下文件
1. 更新DTO类的Swagger装饰器
2. 更新 `api-documentation.md`
3. 更新 `openapi.yaml`
4. 更新 `postman-collection.json`
5. 重新生成Swagger文档
1. 更新Controller和DTO类的Swagger装饰器
2. 更新 `api-documentation.md` 接口文档
3. 更新 `openapi.yaml` 规范文件
4. 更新 `postman-collection.json` 测试集合
5. 重新生成Swagger文档并验证
## 🔗 相关链接
- [NestJS Swagger文档](https://docs.nestjs.com/openapi/introduction)
- [OpenAPI规范](https://swagger.io/specification/)
- [Postman文档](https://learning.postman.com/docs/getting-started/introduction/)
- [Swagger Editor](https://editor.swagger.io/)
- [Swagger Editor](https://editor.swagger.io/)
- [项目架构文档](../ARCHITECTURE.md)
- [开发规范指南](../development/)

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,8 @@
openapi: 3.0.3
info:
title: Pixel Game Server - Auth API
description: 像素游戏服务器用户认证API接口文档
version: 1.0.0
description: 像素游戏服务器用户认证API接口文档 - 包含验证码登录功能、邮箱冲突检测、验证码冷却优化和邮件模板修复
version: 1.1.3
contact:
name: API Support
email: support@example.com
@@ -15,10 +15,39 @@ servers:
description: 开发环境
tags:
- name: app
description: 应用状态相关接口
- name: auth
description: 用户认证相关接口
- name: admin
description: 管理员后台相关接口
- name: user-management
description: 用户管理相关接口
paths:
/:
get:
tags:
- app
summary: 获取应用状态
description: 返回应用的基本运行状态信息,用于健康检查和监控
operationId: getAppStatus
responses:
'200':
description: 应用状态获取成功
content:
application/json:
schema:
$ref: '#/components/schemas/AppStatusResponse'
example:
service: Pixel Game Server
version: 1.0.0
status: running
timestamp: "2025-12-25T08:00:00.000Z"
uptime: 3600
environment: development
storage_mode: database
/auth/login:
post:
tags:
@@ -77,7 +106,7 @@ paths:
tags:
- auth
summary: 用户注册
description: 创建新用户账户
description: 创建新用户账户。如果提供邮箱,需要先调用发送验证码接口获取验证码。发送验证码接口会自动检查邮箱是否已被注册,避免向已存在邮箱发送验证码。
operationId: register
requestBody:
required: true
@@ -99,17 +128,49 @@ paths:
schema:
$ref: '#/components/schemas/RegisterResponse'
'400':
description: 请求参数错误
description: 请求参数错误或验证码错误
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
examples:
validation_error:
summary: 参数验证错误
value:
success: false
message: "密码必须包含字母和数字长度8-128字符"
error_code: "REGISTER_FAILED"
verification_code_error:
summary: 验证码错误
value:
success: false
message: "验证码不存在或已过期"
error_code: "REGISTER_FAILED"
'409':
description: 用户名邮箱已存在
description: 资源冲突 - 用户名邮箱或手机号已存在
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
examples:
username_exists:
summary: 用户名已存在
value:
success: false
message: "用户名已存在"
error_code: "REGISTER_FAILED"
email_exists:
summary: 邮箱已存在
value:
success: false
message: "邮箱已存在"
error_code: "REGISTER_FAILED"
phone_exists:
summary: 手机号已存在
value:
success: false
message: "手机号已存在"
error_code: "REGISTER_FAILED"
/auth/github:
post:
@@ -259,8 +320,290 @@ paths:
schema:
$ref: '#/components/schemas/ErrorResponse'
/auth/send-email-verification:
post:
tags:
- auth
summary: 发送邮箱验证码
description: 向指定邮箱发送验证码。如果邮箱已被注册,将返回冲突错误。
operationId: sendEmailVerification
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/SendEmailVerificationDto'
example:
email: test@example.com
responses:
'200':
description: 验证码发送成功(真实发送模式)
content:
application/json:
schema:
$ref: '#/components/schemas/EmailVerificationResponse'
'206':
description: 测试模式:验证码已生成但未真实发送
content:
application/json:
schema:
$ref: '#/components/schemas/TestModeEmailVerificationResponse'
'400':
description: 请求参数错误
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'409':
description: 邮箱已被注册
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
example:
success: false
message: "邮箱已被注册,请使用其他邮箱或直接登录"
error_code: "SEND_EMAIL_VERIFICATION_FAILED"
'429':
description: 发送频率过高
content:
application/json:
schema:
$ref: '#/components/schemas/ThrottleErrorResponse'
/auth/verify-email:
post:
tags:
- auth
summary: 验证邮箱验证码
description: 使用验证码验证邮箱
operationId: verifyEmail
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/EmailVerificationDto'
example:
email: test@example.com
verification_code: "123456"
responses:
'200':
description: 邮箱验证成功
content:
application/json:
schema:
$ref: '#/components/schemas/CommonResponse'
'400':
description: 验证码错误或已过期
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
/auth/resend-email-verification:
post:
tags:
- auth
summary: 重新发送邮箱验证码
description: 重新向指定邮箱发送验证码
operationId: resendEmailVerification
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/SendEmailVerificationDto'
example:
email: test@example.com
responses:
'200':
description: 验证码重新发送成功
content:
application/json:
schema:
$ref: '#/components/schemas/EmailVerificationResponse'
'206':
description: 测试模式:验证码已生成但未真实发送
content:
application/json:
schema:
$ref: '#/components/schemas/TestModeEmailVerificationResponse'
'400':
description: 邮箱已验证或用户不存在
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'429':
description: 发送频率过高
content:
application/json:
schema:
$ref: '#/components/schemas/ThrottleErrorResponse'
/auth/verification-code-login:
post:
tags:
- auth
summary: 验证码登录
description: 使用邮箱或手机号和验证码进行登录,无需密码
operationId: verificationCodeLogin
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/VerificationCodeLoginDto'
example:
identifier: test@example.com
verification_code: "123456"
responses:
'200':
description: 验证码登录成功
content:
application/json:
schema:
$ref: '#/components/schemas/LoginResponse'
'400':
description: 请求参数错误
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'401':
description: 验证码错误或已过期
content:
application/json:
schema:
$ref: '#/components/schemas/VerificationCodeLoginErrorResponse'
'404':
description: 用户不存在
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
/auth/send-login-verification-code:
post:
tags:
- auth
summary: 发送登录验证码
description: 向用户邮箱或手机发送登录验证码。邮件内容使用专门的登录验证码模板,标题为"登录验证码",内容说明用于登录验证而非密码重置。
operationId: sendLoginVerificationCode
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/SendLoginVerificationCodeDto'
example:
identifier: test@example.com
responses:
'200':
description: 验证码发送成功
content:
application/json:
schema:
$ref: '#/components/schemas/EmailVerificationResponse'
'206':
description: 测试模式:验证码已生成但未真实发送
content:
application/json:
schema:
$ref: '#/components/schemas/TestModeEmailVerificationResponse'
'400':
description: 请求参数错误
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
'404':
description: 用户不存在
content:
application/json:
schema:
$ref: '#/components/schemas/SendLoginCodeErrorResponse'
'429':
description: 发送频率过高
content:
application/json:
schema:
$ref: '#/components/schemas/ThrottleErrorResponse'
/auth/debug-verification-code:
post:
tags:
- auth
summary: 调试验证码信息
description: 获取验证码的详细调试信息(仅开发环境)
operationId: debugVerificationCode
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/SendEmailVerificationDto'
example:
email: test@example.com
responses:
'200':
description: 调试信息获取成功
content:
application/json:
schema:
$ref: '#/components/schemas/DebugVerificationCodeResponse'
/auth/debug-clear-throttle:
post:
tags:
- auth
summary: 清除限流记录
description: 清除所有限流记录(仅开发环境使用)
operationId: clearThrottle
responses:
'200':
description: 限流记录已清除
content:
application/json:
schema:
$ref: '#/components/schemas/CommonResponse'
components:
schemas:
AppStatusResponse:
type: object
properties:
service:
type: string
description: 服务名称
example: Pixel Game Server
version:
type: string
description: 版本号
example: 1.0.0
status:
type: string
description: 运行状态
example: running
timestamp:
type: string
format: date-time
description: 当前时间戳
example: "2025-12-25T08:00:00.000Z"
uptime:
type: integer
description: 运行时间(秒)
example: 3600
environment:
type: string
description: 运行环境
example: development
storage_mode:
type: string
description: 存储模式
example: database
LoginDto:
type: object
required:
@@ -415,6 +758,64 @@ components:
pattern: '^(?=.*[a-zA-Z])(?=.*\d)'
example: newpassword123
SendEmailVerificationDto:
type: object
required:
- email
properties:
email:
type: string
format: email
description: 邮箱地址
example: test@example.com
EmailVerificationDto:
type: object
required:
- email
- verification_code
properties:
email:
type: string
format: email
description: 邮箱地址
example: test@example.com
verification_code:
type: string
description: 6位数字验证码
pattern: '^\d{6}$'
example: "123456"
VerificationCodeLoginDto:
type: object
required:
- identifier
- verification_code
properties:
identifier:
type: string
description: 登录标识符(邮箱或手机号)
minLength: 1
maxLength: 100
example: test@example.com
verification_code:
type: string
description: 6位数字验证码
pattern: '^\d{6}$'
example: "123456"
SendLoginVerificationCodeDto:
type: object
required:
- identifier
properties:
identifier:
type: string
description: 邮箱或手机号
minLength: 1
maxLength: 100
example: test@example.com
UserInfo:
type: object
properties:
@@ -565,4 +966,175 @@ components:
error_code:
type: string
description: 错误代码
example: OPERATION_FAILED
example: OPERATION_FAILED
EmailVerificationResponse:
type: object
properties:
success:
type: boolean
description: 请求是否成功
example: true
data:
type: object
properties:
sent_to:
type: string
description: 发送目标
example: test@example.com
expires_in:
type: integer
description: 过期时间(秒)
example: 300
is_test_mode:
type: boolean
description: 是否为测试模式
example: false
message:
type: string
description: 响应消息
example: 验证码已发送,请查收邮件
TestModeEmailVerificationResponse:
type: object
properties:
success:
type: boolean
description: 请求是否成功
example: false
data:
type: object
properties:
verification_code:
type: string
description: 验证码(仅测试模式)
example: "123456"
sent_to:
type: string
description: 发送目标
example: test@example.com
expires_in:
type: integer
description: 过期时间(秒)
example: 300
is_test_mode:
type: boolean
description: 是否为测试模式
example: true
message:
type: string
description: 响应消息
example: 测试模式:验证码已生成但未真实发送
error_code:
type: string
description: 错误代码
example: TEST_MODE_ONLY
VerificationCodeLoginErrorResponse:
type: object
properties:
success:
type: boolean
description: 请求是否成功
example: false
message:
type: string
description: 错误消息
example: 验证码错误或已过期
error_code:
type: string
description: 错误代码
example: VERIFICATION_CODE_LOGIN_FAILED
SendLoginCodeErrorResponse:
type: object
properties:
success:
type: boolean
description: 请求是否成功
example: false
message:
type: string
description: 错误消息
example: 用户不存在
error_code:
type: string
description: 错误代码
example: SEND_LOGIN_CODE_FAILED
ThrottleErrorResponse:
type: object
properties:
success:
type: boolean
description: 请求是否成功
example: false
message:
type: string
description: 错误消息
example: 请求过于频繁,请稍后再试
error_code:
type: string
description: 错误代码
example: TOO_MANY_REQUESTS
throttle_info:
type: object
properties:
limit:
type: integer
description: 限制次数
example: 1
window_seconds:
type: integer
description: 时间窗口(秒)
example: 60
current_requests:
type: integer
description: 当前请求次数
example: 1
reset_time:
type: string
format: date-time
description: 重置时间
example: "2025-12-25T08:01:00.000Z"
DebugVerificationCodeResponse:
type: object
properties:
success:
type: boolean
description: 请求是否成功
example: true
data:
type: object
properties:
key:
type: string
description: Redis键名
example: verification_code:email_verification:test@example.com
exists:
type: boolean
description: 是否存在
example: true
ttl:
type: integer
description: 剩余生存时间(秒)
example: 290
rawData:
type: string
description: 原始数据
example: '{"code":"123456","createdAt":1766649341250}'
parsedData:
type: object
description: 解析后的数据
properties:
code:
type: string
example: "123456"
createdAt:
type: integer
example: 1766649341250
currentTime:
type: integer
description: 当前时间戳
example: 1766649341250

View File

@@ -0,0 +1,418 @@
# 🚀 Whale Town 部署指南
本文档详细说明如何部署 Whale Town 像素游戏后端服务到生产环境。
## 📋 前置要求
### 基础环境
- **Node.js** 18+ (推荐 20.x LTS)
- **pnpm** 包管理器
- **MySQL** 8.0+
- **Redis** 6.0+ (可选,支持文件存储模式)
- **PM2** 进程管理器(推荐)
- **Nginx** 反向代理(推荐)
### 新增要求 (管理员后台)
- **Web服务器** (Nginx/Apache) - 用于前端管理界面
- **SSL证书** (推荐) - 保护管理后台安全
## 部署步骤
### 1. 服务器环境准备
```bash
# 安装 Node.js (使用 NodeSource 仓库)
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
# 安装 pnpm
curl -fsSL https://get.pnpm.io/install.sh | sh
source ~/.bashrc
# 安装 PM2
npm install -g pm2
# 安装 MySQL
sudo apt update
sudo apt install mysql-server
sudo mysql_secure_installation
```
### 2. 克隆项目
```bash
# 创建项目目录
sudo mkdir -p /var/www
cd /var/www
# 克隆项目(替换为你的实际仓库地址)
git clone https://gitea.xinghangee.icu/datawhale/whale-town-end.git
cd whale-town-end
```
### 3. 配置环境
```bash
# 复制环境配置文件
cp .env.production.example .env.production
# 编辑环境配置(填入实际的数据库信息)
nano .env.production
# 复制部署脚本
cp deploy.sh.example deploy.sh
chmod +x deploy.sh
# 编辑部署脚本(修改路径配置)
nano deploy.sh
# 复制 webhook 处理器
cp webhook-handler.js.example webhook-handler.js
# 编辑 webhook 处理器(修改密钥和路径)
nano webhook-handler.js
```
### 4. 数据库设置
```bash
# 登录 MySQL
sudo mysql -u root -p
# 创建数据库和用户
CREATE DATABASE pixel_game_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'pixel_game'@'localhost' IDENTIFIED BY 'your_secure_password';
GRANT ALL PRIVILEGES ON pixel_game_db.* TO 'pixel_game'@'localhost';
FLUSH PRIVILEGES;
EXIT;
```
### 5. 安装依赖和构建
```bash
# 安装后端依赖
pnpm install --frozen-lockfile
# 安装前端依赖 (新增)
cd client
pnpm install --frozen-lockfile
cd ..
# 构建后端
pnpm run build
# 构建前端管理界面 (新增)
cd client
pnpm run build
cd ..
```
### 6. 启动服务
```bash
# 使用 PM2 启动应用
pm2 start ecosystem.config.js --env production
# 保存 PM2 配置
pm2 save
# 设置开机自启
pm2 startup
# 按照提示执行显示的命令
```
### 7. 配置 Nginx
#### 方案一: 分离部署 (推荐)
创建后端API配置
```bash
sudo nano /etc/nginx/sites-available/whale-town-api
```
```nginx
server {
listen 80;
server_name api.whaletown.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
}
```
创建前端管理界面配置:
```bash
sudo nano /etc/nginx/sites-available/whale-town-admin
```
```nginx
server {
listen 80;
server_name admin.whaletown.com;
root /var/www/whale-town-end/client/dist;
index index.html;
# SPA路由支持
location / {
try_files $uri $uri/ /index.html;
}
# API代理
location /api/ {
proxy_pass http://api.whaletown.com/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
```
#### 方案二: 单域名部署
创建统一配置:
```bash
sudo nano /etc/nginx/sites-available/whale-town-unified
```
```nginx
server {
listen 80;
server_name whaletown.com;
# API接口
location /api/ {
proxy_pass http://localhost:3000/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# 管理后台
location /admin/ {
alias /var/www/whale-town-end/client/dist/;
try_files $uri $uri/ /admin/index.html;
}
# 主站点 (可选)
location / {
proxy_pass http://localhost:3000;
}
}
```
启用配置:
```bash
# 启用站点
sudo ln -s /etc/nginx/sites-available/whale-town-* /etc/nginx/sites-enabled/
# 测试配置
sudo nginx -t
# 重载配置
sudo systemctl reload nginx
```
## 🔒 SSL证书配置 (推荐)
### 使用 Let's Encrypt
```bash
# 安装 Certbot
sudo apt install certbot python3-certbot-nginx
# 为API域名申请证书
sudo certbot --nginx -d api.whaletown.com
# 为管理后台申请证书
sudo certbot --nginx -d admin.whaletown.com
# 设置自动续期
sudo crontab -e
# 添加: 0 12 * * * /usr/bin/certbot renew --quiet
```
## 🎛️ 管理员后台配置
### 环境变量配置
`.env.production` 中添加:
```bash
# 管理员Token配置 (必须)
ADMIN_TOKEN_SECRET=your_super_strong_random_secret_at_least_32_chars
ADMIN_TOKEN_TTL_SECONDS=28800
# 首次部署启用管理员引导
ADMIN_BOOTSTRAP_ENABLED=true
ADMIN_USERNAME=admin
ADMIN_PASSWORD=YourStrongPassword123!
ADMIN_NICKNAME=系统管理员
# CORS配置 (如果前后端分离)
CORS_ORIGIN=https://admin.whaletown.com
```
### 访问管理后台
- **地址**: https://admin.whaletown.com
- **默认账号**: admin / YourStrongPassword123!
**⚠️ 重要**: 首次登录后立即修改密码并关闭引导功能 (`ADMIN_BOOTSTRAP_ENABLED=false`)
## 📡 Gitea Webhook 配置
1. 在 Gitea 仓库中进入 **Settings****Webhooks**
3. 配置:
- **Target URL**: `http://your-server.com:9000/webhook``http://your-domain.com/webhook`
- **HTTP Method**: `POST`
- **POST Content Type**: `application/json`
- **Secret**: 与 `webhook-handler.js` 中的 `SECRET` 一致
- **Trigger On**: 选择 `Push events`
- **Branch filter**: `main`
## ✅ 验证部署
### 基础服务检查
```bash
# 检查PM2服务状态
pm2 status
# 检查后端API
curl http://localhost:3000/
curl http://localhost:3000/api-docs
# 检查前端管理界面
curl -I https://admin.whaletown.com
```
### 管理员后台测试
```bash
# 测试管理员登录API
curl -X POST https://api.whaletown.com/admin/auth/login \
-H "Content-Type: application/json" \
-d '{"identifier":"admin","password":"YourStrongPassword123!"}'
# 访问管理界面
# 浏览器打开: https://admin.whaletown.com
```
### 功能验证清单
- [ ] 后端API服务正常响应
- [ ] API文档可访问
- [ ] 前端管理界面加载正常
- [ ] 管理员登录功能正常
- [ ] 用户管理功能正常
- [ ] 日志查看功能正常
- [ ] SSL证书配置正确
## 🔧 常用命令
### 服务管理
```bash
# 重启后端服务
pm2 restart whale-town-end
# 重启前端服务 (如果使用PM2托管)
pm2 restart whale-town-admin
# 查看服务日志
pm2 logs whale-town-end --lines 100
pm2 logs whale-town-admin --lines 100
# 手动部署
bash deploy.sh
```
### 更新部署
```bash
# 更新后端
git pull origin main
pnpm install
pnpm run build
pm2 reload whale-town-end
# 更新前端管理界面
cd client
git pull origin main
pnpm install
pnpm run build
sudo systemctl reload nginx
cd ..
```
### 日志管理
```bash
# 查看应用日志
tail -f logs/app.log
# 查看管理员操作日志
tail -f logs/admin.log
# 查看Nginx日志
sudo tail -f /var/log/nginx/access.log
sudo tail -f /var/log/nginx/error.log
```
## 🚨 故障排除
### 后端服务问题
**服务无法启动**
- 检查环境变量配置 (`cat .env.production`)
- 检查数据库连接 (`mysql -u pixel_game -p`)
- 查看PM2日志 (`pm2 logs whale-town-end`)
- 检查端口占用 (`netstat -tlnp | grep 3000`)
**管理员登录失败**
- 验证 `ADMIN_TOKEN_SECRET` 配置
- 检查管理员账号是否创建
- 查看后端错误日志
- 确认密码复杂度要求
### 前端管理界面问题
**界面无法访问**
- 检查前端构建是否成功 (`ls -la client/dist/`)
- 验证Nginx配置 (`sudo nginx -t`)
- 检查域名解析
- 查看Nginx错误日志
**API请求失败**
- 检查CORS配置
- 验证API代理设置
- 确认后端服务状态
- 检查防火墙规则
### 数据库连接问题
**连接失败**
- 检查MySQL服务状态 (`sudo systemctl status mysql`)
- 验证数据库用户权限
- 检查网络连接
- 确认数据库配置
### SSL证书问题
**证书验证失败**
- 检查证书有效期 (`sudo certbot certificates`)
- 验证域名解析
- 重新申请证书 (`sudo certbot --nginx -d your-domain.com`)
### 性能问题
**响应缓慢**
- 检查系统资源使用 (`htop`, `df -h`)
- 优化数据库查询
- 配置Redis缓存
- 启用Nginx压缩
### 日志文件过大
**磁盘空间不足**
- 配置日志轮转 (`sudo nano /etc/logrotate.d/whale-town`)
- 清理旧日志文件
- 监控磁盘使用情况

276
docs/development/TESTING.md Normal file
View File

@@ -0,0 +1,276 @@
# 测试指南
本项目支持**无数据库和无邮件服务器**的测试模式,让你可以快速验证所有功能!
## 🚀 快速开始
### 1. 环境配置
```bash
# 复制环境配置文件
cp .env.example .env
```
默认配置已经设置为测试模式,无需修改即可使用。
### 2. 启动服务
```bash
# 安装依赖
npm install
# 启动开发服务器
npm run dev
```
### 3. 运行测试
**Windows (PowerShell):**
```powershell
.\test-api.ps1
```
**Linux/macOS:**
```bash
./test-api.sh
```
**自定义参数:**
```bash
# Windows
.\test-api.ps1 -BaseUrl "http://localhost:3000" -TestEmail "custom@example.com"
# Linux/macOS
./test-api.sh "http://localhost:3000" "custom@example.com"
```
## 🧪 测试功能
### API功能测试
测试脚本会验证以下核心功能:
**用户认证模块:**
-**邮箱验证码发送** - 生成6位数验证码测试模式输出到控制台
-**邮箱验证码验证** - 验证码校验和自动清理
-**用户注册** - 完整的用户注册流程,包含邮箱验证
-**用户登录** - 支持用户名/邮箱/手机号多种方式登录
**系统状态测试:**
-**应用状态检查** - 验证服务器运行状态和系统信息
-**Redis文件存储** - 验证验证码存储和读取功能
-**内存数据库** - 验证用户数据存储功能
### 单元测试覆盖
**核心服务测试7个测试套件140个测试用例**
1. **LoginCoreService** - 登录核心服务15个测试
- 用户登录成功/失败场景
- 用户注册功能测试
- GitHub OAuth登录测试
- 密码重置和修改功能
- 用户状态验证active、inactive、locked等
2. **AdminService** - 管理员服务测试
- 管理员登录认证
- 用户列表管理
- 用户密码重置
- 日志管理功能
3. **VerificationService** - 验证码服务测试
- 验证码生成和验证
- 频率限制机制
- Redis存储操作
- 错误处理和边界条件
4. **EmailService** - 邮件服务测试
- 邮件发送功能(测试模式和生产模式)
- 验证码邮件模板
- 连接验证和错误处理
- SMTP配置测试
5. **UsersService** - 用户数据服务测试
- 用户CRUD操作
- 用户查询功能
- 数据验证和约束
6. **AdminCoreService** - 管理员核心服务测试
- 管理员认证逻辑
- 权限验证
- 管理员引导创建
7. **LoggerService** - 日志服务测试
- 日志记录功能
- 敏感信息过滤
- 日志级别控制
### E2E端到端测试
**登录功能完整流程测试:**
- 用户注册 → 邮箱验证 → 登录验证
- GitHub OAuth登录流程
- 密码重置完整流程
- 错误处理和边界条件测试
## 🔧 测试模式特性
- 🗄️ **Redis 文件存储** - 使用 `redis-data/redis.json` 存储验证码
- 📧 **邮件测试模式** - 邮件内容输出到控制台无需真实SMTP
- 💾 **内存用户存储** - 无需数据库,用户数据存储在内存中
- 🔄 **自动切换** - 根据配置自动选择存储模式
## 📊 单元测试
### 运行测试命令
```bash
# 运行所有单元测试
npm test
# 监听模式(开发时使用)
npm run test:watch
# 生成覆盖率报告
npm run test:cov
# 运行特定测试文件
npm test -- src/core/login_core/login_core.service.spec.ts
```
### 测试覆盖情况
**测试统计:**
- 测试套件7个
- 测试用例140个
- 覆盖率100%通过
**测试文件列表:**
```
src/core/login_core/login_core.service.spec.ts # 登录核心服务
src/business/admin/admin.service.spec.ts # 管理员服务
src/core/utils/verification/verification.service.spec.ts # 验证码服务
src/core/utils/email/email.service.spec.ts # 邮件服务
src/core/db/users/users.service.spec.ts # 用户数据服务
src/core/admin_core/admin_core.service.spec.ts # 管理员核心服务
src/core/utils/logger/logger.service.spec.ts # 日志服务
test/business/login.e2e-spec.ts # E2E端到端测试
```
### 测试场景覆盖
**正常流程测试:**
- 用户注册、登录、密码管理
- 邮箱验证码发送和验证
- 管理员认证和用户管理
- 系统状态和日志功能
**异常情况测试:**
- 无效输入和参数验证
- 网络连接失败处理
- 权限验证和访问控制
- 频率限制和安全防护
**边界条件测试:**
- 密码强度验证
- 验证码过期处理
- 用户状态变更
- 数据库连接异常
## 🌐 生产环境配置
要切换到生产环境,编辑 `.env` 文件:
```bash
# 启用数据库(取消注释并填入真实数据)
DB_HOST=your_mysql_host
DB_PORT=3306
DB_USERNAME=your_db_username
DB_PASSWORD=your_db_password
DB_NAME=your_db_name
# 启用真实Redis取消注释并设置
USE_FILE_REDIS=false
REDIS_HOST=your_redis_host
REDIS_PORT=6379
REDIS_PASSWORD=your_redis_password
# 启用邮件服务(取消注释并填入真实数据)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=your_email@gmail.com
EMAIL_PASS=your_app_password
EMAIL_FROM="Whale Town Game" <noreply@whaletown.com>
# 生产环境设置
NODE_ENV=production
LOG_LEVEL=info
```
## 🔍 故障排除
### 服务启动失败
- **端口占用**检查端口3000是否被占用使用 `netstat -ano | findstr :3000` 查看
- **Node.js版本**确认Node.js版本 >= 18.0.0,使用 `node --version` 检查
- **依赖问题**:运行 `npm install``pnpm install` 重新安装依赖
- **权限问题**:确保有足够的文件读写权限
### 测试脚本执行失败
- **服务器状态**:确认服务器正在运行,访问 http://localhost:3000 检查
- **网络连接**检查防火墙设置确保端口3000可访问
- **脚本权限**在Linux/macOS上确保脚本有执行权限`chmod +x test-api.sh`
- **PowerShell策略**Windows上可能需要设置执行策略`Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser`
### 单元测试失败
- **依赖冲突**清理node_modules并重新安装`rm -rf node_modules && npm install`
- **TypeScript错误**:运行 `npm run build` 检查编译错误
- **环境变量**:确保测试环境变量配置正确
- **数据库连接**:测试模式下应该使用内存数据库,检查配置
### Redis文件存储问题
- **目录权限**:检查 `redis-data` 目录的读写权限
- **配置设置**:确认 `USE_FILE_REDIS=true` 设置正确
- **文件锁定**确保redis.json文件没有被其他进程锁定
- **磁盘空间**:检查磁盘空间是否充足
### 邮件测试模式问题
- **配置检查**:确认邮件配置为注释状态(测试模式)
- **控制台输出**:检查服务器控制台是否有邮件内容输出
- **日志级别**确保日志级别设置为info或debug以查看详细输出
### 常见错误解决
**EADDRINUSE错误**
```bash
# 查找占用端口的进程
netstat -ano | findstr :3000
# 结束进程Windows
taskkill /PID <进程ID> /F
```
**权限错误:**
```bash
# Linux/macOS设置权限
chmod +x test-api.sh
chmod 755 redis-data/
```
**模块未找到错误:**
```bash
# 清理并重新安装
rm -rf node_modules package-lock.json
npm install
```
## 📝 测试数据
测试完成后,你可以查看:
- `redis-data/redis.json` - 验证码存储数据
- 服务器控制台 - 邮件内容输出
- 测试脚本输出 - API响应结果
## 🎯 下一步
- 查看 [API 文档](http://localhost:3000/api-docs) 了解更多接口
- 阅读 [开发规范](./docs/backend_development_guide.md) 开始开发
- 使用 [AI 辅助指南](./docs/AI辅助开发规范指南.md) 提高开发效率

View File

@@ -1,265 +0,0 @@
# 邮箱验证系统
## 概述
邮箱验证系统提供完整的邮箱验证功能,包括验证码生成、发送、验证和管理。
## 功能特性
- 📧 邮箱验证码发送
- 🔐 验证码安全验证
- ⏰ 验证码过期管理
- 🚫 防刷机制(频率限制)
- 📊 验证统计和监控
## 系统架构
```
邮箱验证系统
├── 验证码服务 (VerificationService)
│ ├── 验证码生成
│ ├── 验证码验证
│ └── 防刷机制
├── 邮件服务 (EmailService)
│ ├── 验证码邮件发送
│ ├── 欢迎邮件发送
│ └── 邮件模板管理
└── Redis缓存
├── 验证码存储
├── 冷却时间管理
└── 发送频率限制
```
## 核心组件
### 1. 验证码服务 (VerificationService)
负责验证码的生成、验证和管理:
- **验证码生成**6位数字验证码
- **验证码验证**:支持多次尝试限制
- **过期管理**5分钟有效期
- **防刷机制**60秒冷却时间每小时最多5次
### 2. 邮件服务 (EmailService)
负责邮件的发送和模板管理:
- **验证码邮件**:发送验证码到用户邮箱
- **欢迎邮件**:用户注册成功后发送
- **模板支持**支持HTML邮件模板
### 3. Redis缓存
负责数据的临时存储:
- **验证码存储**`verification_code:${type}:${identifier}`
- **冷却时间**`verification_cooldown:${type}:${identifier}`
- **发送频率**`verification_hourly:${type}:${identifier}:${date}:${hour}`
## 使用流程
### 注册流程中的邮箱验证
1. **发送验证码**
```typescript
POST /auth/send-email-verification
{
"email": "user@example.com"
}
```
2. **用户注册**
```typescript
POST /auth/register
{
"username": "testuser",
"password": "password123",
"nickname": "测试用户",
"email": "user@example.com",
"email_verification_code": "123456"
}
```
### 独立邮箱验证
1. **验证邮箱**
```typescript
POST /auth/verify-email
{
"email": "user@example.com",
"verification_code": "123456"
}
```
## 配置说明
### 环境变量
```bash
# 邮件服务配置
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=your-email@example.com
SMTP_PASS=your-password
SMTP_FROM=noreply@example.com
# Redis配置
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
```
### 验证码配置
```typescript
// 验证码长度
CODE_LENGTH = 6
// 验证码过期时间(秒)
CODE_EXPIRE_TIME = 300 // 5分钟
// 最大验证尝试次数
MAX_ATTEMPTS = 3
// 发送冷却时间(秒)
RATE_LIMIT_TIME = 60 // 1分钟
// 每小时最大发送次数
MAX_SENDS_PER_HOUR = 5
```
## API接口
### 发送邮箱验证码
- **接口**`POST /auth/send-email-verification`
- **描述**:向指定邮箱发送验证码
- **参数**
```typescript
{
email: string; // 邮箱地址
}
```
### 验证邮箱验证码
- **接口**`POST /auth/verify-email`
- **描述**:使用验证码验证邮箱
- **参数**
```typescript
{
email: string; // 邮箱地址
verification_code: string; // 6位数字验证码
}
```
### 重新发送验证码
- **接口**`POST /auth/resend-email-verification`
- **描述**:重新向指定邮箱发送验证码
- **参数**
```typescript
{
email: string; // 邮箱地址
}
```
## 错误处理
### 常见错误码
- `VERIFICATION_CODE_NOT_FOUND`:验证码不存在或已过期
- `VERIFICATION_CODE_INVALID`:验证码错误
- `TOO_MANY_ATTEMPTS`:验证尝试次数过多
- `RATE_LIMIT_EXCEEDED`:发送频率过高
- `EMAIL_SEND_FAILED`:邮件发送失败
### 错误响应格式
```typescript
{
success: false,
message: "错误描述",
error_code: "ERROR_CODE"
}
```
## 监控和日志
### 关键指标
- 验证码发送成功率
- 验证码验证成功率
- 邮件发送延迟
- Redis连接状态
### 日志记录
- 验证码生成和验证日志
- 邮件发送状态日志
- 错误和异常日志
- 性能监控日志
## 安全考虑
### 防刷机制
1. **发送频率限制**每个邮箱60秒内只能发送一次
2. **每小时限制**每个邮箱每小时最多发送5次
3. **验证尝试限制**每个验证码最多尝试3次
### 数据安全
1. **验证码加密存储**Redis中的验证码经过加密
2. **过期自动清理**验证码5分钟后自动过期
3. **日志脱敏**:日志中不记录完整验证码
## 部署指南
详细的部署说明请参考:[deployment-guide.md](./deployment-guide.md)
## 测试
### 单元测试
```bash
# 运行验证服务测试
npm test -- verification.service.spec.ts
# 运行邮件服务测试
npm test -- email.service.spec.ts
```
### 集成测试
```bash
# 运行邮箱验证集成测试
npm run test:e2e -- email-verification
```
## 故障排除
### 常见问题
1. **验证码收不到**
- 检查SMTP配置
- 检查邮箱是否在垃圾邮件中
- 检查网络连接
2. **验证码验证失败**
- 检查验证码是否过期
- 检查验证码输入是否正确
- 检查Redis连接状态
3. **发送频率限制**
- 等待冷却时间结束
- 检查是否达到每小时限制
## 更新日志
- **v1.0.0** (2025-12-17)
- 初始版本发布
- 支持基本的邮箱验证功能
- 集成Redis缓存
- 添加防刷机制

View File

@@ -1,316 +0,0 @@
# 邮箱验证功能部署指南
## 概述
本指南详细说明如何部署和配置邮箱验证功能包括Redis缓存、邮件服务配置等。
## 1. 安装依赖
```bash
# 安装新增的依赖包
pnpm install ioredis nodemailer
# 安装类型定义
pnpm install -D @types/nodemailer
```
## 2. Redis 服务配置
### 2.1 安装 Redis
#### Ubuntu/Debian
```bash
sudo apt update
sudo apt install redis-server
sudo systemctl start redis-server
sudo systemctl enable redis-server
```
#### CentOS/RHEL
```bash
sudo yum install redis
sudo systemctl start redis
sudo systemctl enable redis
```
#### Docker 方式
```bash
docker run -d --name redis -p 6379:6379 redis:7-alpine
```
### 2.2 Redis 配置验证
```bash
# 测试 Redis 连接
redis-cli ping
# 应该返回 PONG
```
## 3. 邮件服务配置
### 3.1 Gmail 配置示例
1. **启用两步验证**
- 登录 Google 账户
- 进入"安全性"设置
- 启用"两步验证"
2. **生成应用专用密码**
- 在"安全性"设置中找到"应用专用密码"
- 生成新的应用密码
- 记录生成的16位密码
3. **环境变量配置**
```env
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=your-email@gmail.com
EMAIL_PASS=your-16-digit-app-password
EMAIL_FROM="Whale Town Game" <noreply@gmail.com>
```
### 3.2 其他邮件服务商配置
#### 163邮箱
```env
EMAIL_HOST=smtp.163.com
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=your-email@163.com
EMAIL_PASS=your-authorization-code
```
#### QQ邮箱
```env
EMAIL_HOST=smtp.qq.com
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=your-email@qq.com
EMAIL_PASS=your-authorization-code
```
#### 阿里云邮件推送
```env
EMAIL_HOST=smtpdm.aliyun.com
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=your-smtp-username
EMAIL_PASS=your-smtp-password
```
## 4. 环境变量配置
### 4.1 创建环境配置文件
```bash
# 复制环境变量模板
cp .env.production.example .env
# 编辑环境变量
nano .env
```
### 4.2 完整的环境变量配置
```env
# 数据库配置
DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=pixel_game
DB_PASSWORD=your_db_password
DB_NAME=pixel_game_db
# 应用配置
NODE_ENV=production
PORT=3000
# JWT 配置
JWT_SECRET=your_jwt_secret_key_here_at_least_32_characters
JWT_EXPIRES_IN=7d
# Redis 配置
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0
# 邮件服务配置
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=your-email@gmail.com
EMAIL_PASS=your-app-password
EMAIL_FROM="Whale Town Game" <noreply@whaletown.com>
```
## 5. 数据库迁移
由于添加了新的字段,需要更新数据库结构:
```sql
-- 添加邮箱验证状态字段
ALTER TABLE users ADD COLUMN email_verified BOOLEAN NOT NULL DEFAULT FALSE COMMENT '邮箱是否已验证';
-- 为已有用户设置默认值
UPDATE users SET email_verified = FALSE WHERE email_verified IS NULL;
-- 如果是OAuth用户且有邮箱可以设为已验证
UPDATE users SET email_verified = TRUE WHERE github_id IS NOT NULL AND email IS NOT NULL;
```
## 6. 启动和测试
### 6.1 启动应用
```bash
# 安装依赖
pnpm install
# 构建应用
pnpm run build
# 启动应用
pnpm run start:prod
```
### 6.2 功能测试
#### 测试邮箱验证码发送
```bash
curl -X POST http://localhost:3000/auth/send-email-verification \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com"}'
```
#### 测试邮箱验证
```bash
curl -X POST http://localhost:3000/auth/verify-email \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","verification_code":"123456"}'
```
#### 测试密码重置
```bash
curl -X POST http://localhost:3000/auth/forgot-password \
-H "Content-Type: application/json" \
-d '{"identifier":"test@example.com"}'
```
## 7. 监控和日志
### 7.1 查看应用日志
```bash
# PM2 日志
pm2 logs pixel-game-server
# 或者查看文件日志
tail -f logs/dev.log
```
### 7.2 Redis 监控
```bash
# 查看 Redis 信息
redis-cli info
# 监控 Redis 命令
redis-cli monitor
# 查看验证码相关的键
redis-cli keys "verification_*"
```
### 7.3 邮件发送监控
应用会记录邮件发送的日志,包括:
- 发送成功/失败状态
- 收件人信息
- 发送时间
- 错误信息(如果有)
## 8. 故障排除
### 8.1 Redis 连接问题
**问题**Redis连接失败
```
Redis连接错误: Error: connect ECONNREFUSED 127.0.0.1:6379
```
**解决方案**
1. 检查Redis服务状态`sudo systemctl status redis`
2. 启动Redis服务`sudo systemctl start redis`
3. 检查防火墙设置
4. 验证Redis配置文件
### 8.2 邮件发送问题
**问题**:邮件发送失败
```
邮件发送失败: Error: Invalid login: 535-5.7.8 Username and Password not accepted
```
**解决方案**
1. 检查邮箱用户名和密码
2. 确认已启用应用专用密码Gmail
3. 检查邮件服务商的SMTP设置
4. 验证网络连接
### 8.3 验证码问题
**问题**:验证码验证失败
**解决方案**
1. 检查Redis中是否存在验证码`redis-cli get verification_code:email_verification:test@example.com`
2. 检查验证码是否过期
3. 验证验证码格式6位数字
4. 检查应用日志
## 9. 安全建议
### 9.1 邮件服务安全
1. **使用应用专用密码**:不要使用主密码
2. **启用TLS/SSL**:确保邮件传输加密
3. **限制发送频率**:防止邮件轰炸
4. **监控发送量**:避免被标记为垃圾邮件
### 9.2 Redis 安全
1. **设置密码**`requirepass your_redis_password`
2. **绑定IP**`bind 127.0.0.1`
3. **禁用危险命令**`rename-command FLUSHDB ""`
4. **定期备份**设置Redis数据备份
### 9.3 验证码安全
1. **设置过期时间**默认5分钟
2. **限制尝试次数**最多3次
3. **防刷机制**60秒冷却时间
4. **记录日志**:监控异常行为
## 10. 性能优化
### 10.1 Redis 优化
```redis
# Redis 配置优化
maxmemory 256mb
maxmemory-policy allkeys-lru
save 900 1
save 300 10
save 60 10000
```
### 10.2 邮件发送优化
1. **连接池**复用SMTP连接
2. **异步发送**:不阻塞主流程
3. **队列机制**:处理大量邮件
4. **失败重试**:自动重试机制
---
*部署完成后,建议进行完整的功能测试,确保所有邮箱验证功能正常工作。*

View File

@@ -1,80 +0,0 @@
# 日志系统
## 概述
项目集成了完整的日志系统,基于 Pino 高性能日志库,提供结构化日志记录、自动敏感信息过滤和多级别日志控制。
## 功能特性
- 🚀 高性能日志记录
- 🔒 自动敏感信息过滤
- 🎯 多级别日志控制
- 🔍 请求上下文绑定
- 📊 结构化日志输出
## 使用示例
### 基础用法
```typescript
import { AppLoggerService } from './core/utils/logger/logger.service';
@Injectable()
export class UserService {
constructor(private readonly logger: AppLoggerService) {}
async createUser(userData: CreateUserDto) {
this.logger.info('开始创建用户', {
operation: 'createUser',
email: userData.email,
timestamp: new Date().toISOString()
});
try {
const user = await this.userRepository.save(userData);
this.logger.info('用户创建成功', {
operation: 'createUser',
userId: user.id,
email: userData.email
});
return user;
} catch (error) {
this.logger.error('用户创建失败', {
operation: 'createUser',
email: userData.email,
error: error.message
}, error.stack);
throw error;
}
}
}
```
## 日志级别
- `error`: 错误信息
- `warn`: 警告信息
- `info`: 一般信息
- `debug`: 调试信息
## 配置
日志配置位于 `src/core/utils/logger/logger.config.ts`,支持:
- 日志级别设置
- 输出格式配置
- 敏感信息过滤规则
- 文件输出配置
## 敏感信息过滤
系统自动过滤以下敏感信息:
- 密码字段
- 令牌信息
- 个人身份信息
- 支付相关信息
详细使用方法请参考:[后端开发规范指南 - 日志系统使用指南](../../backend_development_guide.md#四日志系统使用指南)

View File

@@ -1,363 +0,0 @@
# 日志系统详细说明
## 📋 概述
本项目的日志系统基于 Pino 高性能日志库构建,提供完整的日志记录、管理和分析功能。
---
## 🗂️ 日志文件结构
### 开发环境 (`NODE_ENV=development`)
```
logs/
└── dev.log # 开发环境综合日志(所有级别)
```
**输出方式:**
- 🖥️ **控制台**:彩色美化输出,便于开发调试
- 📁 **文件**:保存到 `logs/dev.log`,便于问题追踪
### 生产环境 (`NODE_ENV=production`)
```
logs/
├── app.log # 应用综合日志info及以上级别
├── error.log # 错误日志error和fatal级别
├── access.log # HTTP访问日志请求响应记录
├── app.log.gz # 压缩的历史日志文件
├── error.log.gz # 压缩的历史错误日志
└── access.log.gz # 压缩的历史访问日志
```
**输出方式:**
- 📁 **文件**:分类保存到不同的日志文件
- 🖥️ **控制台**:仅输出 warn 及以上级别(用于容器日志收集)
---
## 📊 日志级别和用途
| 级别 | 数值 | 用途 | 保存位置 | 示例场景 |
|------|------|------|----------|----------|
| **TRACE** | 10 | 极细粒度调试 | dev.log | 循环内变量状态 |
| **DEBUG** | 20 | 开发调试信息 | dev.log | 方法调用参数 |
| **INFO** | 30 | 重要业务操作 | app.log, dev.log | 用户登录成功 |
| **WARN** | 40 | 警告信息 | app.log, dev.log, 控制台 | 参数验证失败 |
| **ERROR** | 50 | 错误信息 | error.log, app.log, 控制台 | 数据库连接失败 |
| **FATAL** | 60 | 致命错误 | error.log, app.log, 控制台 | 系统不可用 |
---
## 🔄 日志轮转和管理
### 自动轮转策略
| 文件类型 | 轮转频率 | 文件大小限制 | 保留时间 | 压缩策略 |
|----------|----------|--------------|----------|----------|
| **app.log** | 每日 | 10MB | 7天 | 7天后压缩 |
| **error.log** | 每日 | 10MB | 30天 | 7天后压缩 |
| **access.log** | 每日 | 50MB | 14天 | 7天后压缩 |
| **dev.log** | 手动 | 无限制 | 无限制 | 不压缩 |
### 定时任务
| 任务 | 执行时间 | 功能 |
|------|----------|------|
| **日志清理** | 每天 02:00 | 删除过期日志文件 |
| **日志压缩** | 每周日 03:00 | 压缩7天前的日志文件 |
| **健康监控** | 每小时 | 监控日志系统状态 |
| **统计报告** | 每天 09:00 | 输出日志统计信息 |
---
## 🚀 如何使用日志系统
### 基本使用
```typescript
import { Injectable } from '@nestjs/common';
import { AppLoggerService } from '../core/utils/logger/logger.service';
@Injectable()
export class UserService {
constructor(private readonly logger: AppLoggerService) {}
async createUser(userData: CreateUserDto) {
// 记录操作开始
this.logger.info('开始创建用户', {
operation: 'createUser',
email: userData.email,
timestamp: new Date().toISOString()
});
try {
const user = await this.userRepository.save(userData);
// 记录成功操作
this.logger.info('用户创建成功', {
operation: 'createUser',
userId: user.id,
email: userData.email,
duration: Date.now() - startTime
});
return user;
} catch (error) {
// 记录错误
this.logger.error('用户创建失败', {
operation: 'createUser',
email: userData.email,
error: error.message
}, error.stack);
throw error;
}
}
}
```
### 请求上下文绑定
```typescript
@Controller('users')
export class UserController {
constructor(private readonly logger: AppLoggerService) {}
@Get(':id')
async getUser(@Param('id') id: string, @Req() req: Request) {
// 绑定请求上下文
const requestLogger = this.logger.bindRequest(req, 'UserController');
requestLogger.info('开始获取用户信息', { userId: id });
try {
const user = await this.userService.findById(id);
requestLogger.info('用户信息获取成功', { userId: id });
return user;
} catch (error) {
requestLogger.error('用户信息获取失败', error.stack, {
userId: id,
reason: error.message
});
throw error;
}
}
}
```
---
## 🔍 日志格式详解
### 开发环境日志格式
```
🕐 2024-12-13 14:30:25 📝 INFO pixel-game-server [UserService] 用户创建成功
operation: "createUser"
userId: "user_123"
email: "user@example.com"
duration: 45
```
### 生产环境日志格式 (JSON)
```json
{
"level": 30,
"time": 1702456225000,
"pid": 12345,
"hostname": "server-01",
"app": "pixel-game-server",
"version": "1.0.0",
"msg": "用户创建成功",
"operation": "createUser",
"userId": "user_123",
"email": "user@example.com",
"duration": 45,
"reqId": "req_1702456225_abc123"
}
```
### HTTP 请求日志格式
```json
{
"level": 30,
"time": 1702456225000,
"req": {
"id": "req_1702456225_abc123",
"method": "POST",
"url": "/api/users",
"headers": {
"host": "localhost:3000",
"user-agent": "Mozilla/5.0...",
"content-type": "application/json"
},
"ip": "127.0.0.1"
},
"res": {
"statusCode": 201,
"responseTime": 45
},
"msg": "POST /api/users completed in 45ms"
}
```
---
## 🛠️ 问题排查指南
### 1. 如何查找特定用户的操作日志?
```bash
# 在日志文件中搜索特定用户ID
grep "userId.*user_123" logs/app.log
# 搜索特定操作
grep "operation.*createUser" logs/app.log
# 搜索特定时间段的日志
grep "2024-12-13 14:" logs/app.log
```
### 2. 如何查找错误日志?
```bash
# 查看所有错误日志
cat logs/error.log
# 查看最近的错误
tail -f logs/error.log
# 搜索特定错误
grep "数据库连接失败" logs/error.log
```
### 3. 如何分析性能问题?
```bash
# 查找响应时间超过1000ms的请求
grep "responseTime.*[0-9][0-9][0-9][0-9]" logs/access.log
# 查找特定接口的性能数据
grep "POST /api/users" logs/access.log | grep responseTime
```
### 4. 如何监控系统健康状态?
```bash
# 查看日志统计信息
grep "日志系统健康状态报告" logs/app.log
# 查看日志清理记录
grep "日志清理任务完成" logs/app.log
# 查看压缩记录
grep "日志压缩任务完成" logs/app.log
```
---
## 📈 日志分析和监控
### 日志统计信息
系统会自动收集以下统计信息:
- **文件数量**:当前日志文件总数
- **总大小**:所有日志文件占用的磁盘空间
- **错误日志数量**:错误级别日志文件数量
- **最旧/最新文件**:日志文件的时间范围
- **平均文件大小**:单个日志文件的平均大小
### 健康监控告警
系统会在以下情况发出警告:
- 📊 **磁盘空间告警**:日志文件总大小超过阈值
- ⚠️ **错误日志告警**:错误日志数量异常增长
- 🔧 **清理失败告警**:日志清理任务执行失败
- 💾 **压缩失败告警**:日志压缩任务执行失败
---
## ⚙️ 配置说明
### 环境变量配置
```bash
# 应用名称
APP_NAME=pixel-game-server
# 环境标识
NODE_ENV=development
# 日志级别
LOG_LEVEL=debug
# 日志目录
LOG_DIR=./logs
# 日志保留天数
LOG_MAX_FILES=7d
# 单个日志文件最大大小
LOG_MAX_SIZE=10m
```
### 高级配置选项
如需自定义日志配置,可以修改 `src/core/utils/logger/logger.config.ts`
```typescript
// 自定义日志轮转策略
{
target: 'pino-roll',
options: {
file: path.join(logDir, 'app.log'),
frequency: 'daily', // 轮转频率daily, hourly, weekly
size: '10m', // 文件大小限制
limit: {
count: 7, // 保留文件数量
},
},
}
```
---
## 🚨 注意事项
### 安全考虑
1. **敏感信息过滤**系统自动过滤密码、token等敏感字段
2. **访问控制**:确保日志文件只有授权用户可以访问
3. **传输加密**:生产环境建议使用加密传输日志
### 性能考虑
1. **异步写入**Pino 使用异步写入,不会阻塞主线程
2. **日志级别**:生产环境建议使用 info 及以上级别
3. **文件轮转**:及时清理和压缩日志文件,避免占用过多磁盘空间
### 运维建议
1. **监控磁盘空间**:定期检查日志目录的磁盘使用情况
2. **备份重要日志**:对于重要的错误日志,建议定期备份
3. **日志分析**:可以集成 ELK Stack 等日志分析工具
4. **告警设置**:配置日志监控告警,及时发现系统问题
---
## 🔗 相关文档
- [后端开发规范 - 日志系统使用指南](./backend_development_guide.md#四日志系统使用指南)
- [AI 辅助开发规范指南](./AI辅助开发规范指南.md)
- [Pino 官方文档](https://getpino.io/)
- [NestJS Pino 集成文档](https://github.com/iamolegga/nestjs-pino)
---
**💡 提示:使用 [AI 辅助开发指南](./AI辅助开发规范指南.md) 可以让 AI 帮你自动生成符合规范的日志代码!**

View File

@@ -1,334 +0,0 @@
# 用户认证系统
## 概述
用户认证系统提供完整的用户注册、登录、密码管理功能支持传统用户名密码登录和第三方OAuth登录。
## 功能特性
- 🔐 多种登录方式:用户名/邮箱/手机号登录
- 📝 用户注册和信息管理
- 🐙 GitHub OAuth 第三方登录
- 🔄 密码重置和修改
- 🛡️ bcrypt 密码加密
- 🎯 基于角色的权限控制
## 架构设计
### 分层结构
```
src/
├── business/login/ # 业务逻辑层
│ ├── login.controller.ts # HTTP 控制器
│ ├── login.service.ts # 业务服务
│ ├── login.dto.ts # 数据传输对象
│ ├── login.service.spec.ts # 业务服务测试
│ └── login.module.ts # 业务模块
├── core/
│ ├── login_core/ # 核心功能层
│ │ ├── login_core.service.ts # 核心认证逻辑
│ │ ├── login_core.service.spec.ts # 核心服务测试
│ │ └── login_core.module.ts # 核心模块
│ └── db/users/ # 数据访问层
│ ├── users.entity.ts # 用户实体
│ ├── users.service.ts # 用户数据服务
│ └── users.dto.ts # 用户 DTO
```
### 职责分离
#### 1. 业务逻辑层 (Business Layer)
- **位置**: `src/business/login/`
- **职责**:
- 处理HTTP请求和响应
- 数据格式化和验证
- 业务流程控制
- 错误处理和日志记录
#### 2. 核心功能层 (Core Layer)
- **位置**: `src/core/login_core/`
- **职责**:
- 认证核心算法实现
- 密码加密和验证
- 用户查找和匹配
- 令牌生成和验证
#### 3. 数据访问层 (Data Access Layer)
- **位置**: `src/core/db/users/`
- **职责**:
- 数据库操作封装
- 实体关系映射
- 数据完整性保证
- 查询优化
## API 接口
### 用户注册
```bash
POST /auth/register
Content-Type: application/json
{
"username": "testuser",
"password": "password123",
"nickname": "测试用户",
"email": "test@example.com",
"phone": "+8613800138000"
}
```
**响应**:
```json
{
"success": true,
"data": {
"user": {
"id": "1",
"username": "testuser",
"nickname": "测试用户",
"email": "test@example.com",
"phone": "+8613800138000",
"avatar_url": null,
"role": 1,
"created_at": "2025-12-17T10:00:00.000Z"
},
"access_token": "eyJ1c2VySWQiOiIxIiwidXNlcm5hbWUiOiJ0ZXN0dXNlciJ9...",
"is_new_user": true,
"message": "注册成功"
},
"message": "注册成功"
}
```
### 用户登录
```bash
POST /auth/login
Content-Type: application/json
{
"identifier": "testuser", # 支持用户名/邮箱/手机号
"password": "password123"
}
```
### GitHub OAuth登录
```bash
POST /auth/github
Content-Type: application/json
{
"github_id": "12345678",
"username": "githubuser",
"nickname": "GitHub用户",
"email": "github@example.com",
"avatar_url": "https://avatars.githubusercontent.com/u/12345678"
}
```
### 密码重置
```bash
# 1. 发送验证码
POST /auth/forgot-password
{
"identifier": "test@example.com"
}
# 2. 重置密码
POST /auth/reset-password
{
"identifier": "test@example.com",
"verification_code": "123456",
"new_password": "newpassword123"
}
```
### 修改密码
```bash
PUT /auth/change-password
{
"user_id": "1",
"old_password": "password123",
"new_password": "newpassword123"
}
```
## 数据模型
### 用户实体 (Users Entity)
```typescript
{
id: bigint, // 主键ID
username: string, // 用户名(唯一)
email?: string, // 邮箱(唯一,可选)
phone?: string, // 手机号(唯一,可选)
password_hash?: string, // 密码哈希OAuth用户为空
nickname: string, // 显示昵称
github_id?: string, // GitHub ID唯一可选
avatar_url?: string, // 头像URL
role: number, // 用户角色1-普通9-管理员)
created_at: Date, // 创建时间
updated_at: Date // 更新时间
}
```
### 数据库设计特点
1. **唯一性约束**: username, email, phone, github_id
2. **索引优化**: 主键、唯一索引、角色索引
3. **字符集支持**: utf8mb4支持emoji
4. **数据类型**: BIGINT主键VARCHAR字段DATETIME时间戳
## 安全机制
### 1. 密码安全
- **加密算法**: bcrypt (saltRounds=12)
- **强度验证**: 最少8位包含字母和数字
- **存储安全**: 只存储哈希值,不存储明文
### 2. 数据验证
- **输入验证**: class-validator装饰器
- **SQL注入防护**: TypeORM参数化查询
- **XSS防护**: 数据转义和验证
### 3. 访问控制
- **令牌机制**: 基于用户信息的访问令牌
- **角色权限**: 基于角色的访问控制RBAC
- **会话管理**: 令牌生成和验证
### 4. 错误处理
- **统一异常**: NestJS异常过滤器
- **日志记录**: 操作日志和错误日志
- **信息脱敏**: 敏感信息自动脱敏
## 测试覆盖
### 单元测试
- 核心服务测试:`src/core/login_core/login_core.service.spec.ts`
- 业务服务测试:`src/business/login/login.service.spec.ts`
### 集成测试
- 端到端测试:`test/business/login.e2e-spec.ts`
### 测试用例
- 用户注册和登录流程
- GitHub OAuth认证
- 密码重置和修改
- 数据验证和错误处理
- 安全性测试
## 使用示例
### JavaScript/TypeScript
```javascript
// 用户注册
const registerResponse = await fetch('/auth/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'testuser',
password: 'password123',
nickname: '测试用户',
email: 'test@example.com'
})
});
const registerData = await registerResponse.json();
console.log(registerData);
// 用户登录
const loginResponse = await fetch('/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
identifier: 'testuser',
password: 'password123'
})
});
const loginData = await loginResponse.json();
console.log(loginData);
```
### curl 命令
```bash
# 用户注册
curl -X POST http://localhost:3000/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"password": "password123",
"nickname": "测试用户",
"email": "test@example.com"
}'
# 用户登录
curl -X POST http://localhost:3000/auth/login \
-H "Content-Type: application/json" \
-d '{
"identifier": "testuser",
"password": "password123"
}'
```
## 错误处理
### 常见错误代码
- `LOGIN_FAILED`: 登录失败
- `REGISTER_FAILED`: 注册失败
- `GITHUB_OAUTH_FAILED`: GitHub登录失败
- `SEND_CODE_FAILED`: 发送验证码失败
- `RESET_PASSWORD_FAILED`: 密码重置失败
- `CHANGE_PASSWORD_FAILED`: 密码修改失败
### 错误响应格式
```json
{
"success": false,
"message": "错误描述",
"error_code": "ERROR_CODE"
}
```
## 扩展功能
### 计划中的功能
1. **JWT令牌管理**
- 访问令牌和刷新令牌
- 令牌黑名单机制
- 自动刷新功能
2. **多因子认证**
- 短信验证码
- 邮箱验证码
- TOTP应用支持
3. **社交登录扩展**
- 微信登录
- QQ登录
- 微博登录
4. **安全增强**
- 登录失败次数限制
- IP白名单/黑名单
- 设备指纹识别
5. **用户管理**
- 用户状态管理(激活/禁用)
- 用户角色权限细化
- 用户行为日志记录