2 Commits

Author SHA1 Message Date
432b875ba4 皮肤部分拿apifox测过了 2026-01-20 11:50:24 +08:00
116612ffec 修改了皮肤收藏部分 2026-01-13 18:34:21 +08:00
103 changed files with 3277 additions and 5089 deletions

110
.env Normal file
View File

@@ -0,0 +1,110 @@
# =============================================================================
# 站点配置
# =============================================================================
SITE_NAME=CarrotSkin
SITE_DESCRIPTION=一个优秀的Minecraft皮肤站
REGISTRATION_ENABLED=true
DEFAULT_AVATAR=
# =============================================================================
# 用户限制配置
# =============================================================================
MAX_TEXTURES_PER_USER=50
MAX_PROFILES_PER_USER=5
# =============================================================================
# 积分配置
# =============================================================================
CHECKIN_REWARD=10
TEXTURE_DOWNLOAD_REWARD=1
# =============================================================================
# 服务器配置
# =============================================================================
SERVER_PORT=:8080
SERVER_MODE=debug
SERVER_READ_TIMEOUT=30s
SERVER_WRITE_TIMEOUT=30s
SERVER_SWAGGER_ENABLED=true
# =============================================================================
# 数据库配置
# =============================================================================
DATABASE_DRIVER=postgres
DATABASE_HOST=120.27.110.94
DATABASE_PORT=5432
DATABASE_USERNAME=user_wc2MbZ
DATABASE_PASSWORD=password_65b5aN
DATABASE_NAME=carrotskin
DATABASE_SSL_MODE=disable
DATABASE_TIMEZONE=Asia/Shanghai
DATABASE_MAX_IDLE_CONNS=10
DATABASE_MAX_OPEN_CONNS=100
DATABASE_CONN_MAX_LIFETIME=1h
DATABASE_CONN_MAX_IDLE_TIME=10m
# =============================================================================
# Redis配置
# =============================================================================
REDIS_HOST=120.27.110.94
REDIS_PORT=6379
REDIS_PASSWORD=redis_ZXjbN5
REDIS_DATABASE=0
REDIS_POOL_SIZE=10
# =============================================================================
# RustFS对象存储配置 (S3兼容)
# =============================================================================
RUSTFS_ENDPOINT=120.27.110.94:9000
RUSTFS_PUBLIC_URL=http://120.27.110.94:9000
RUSTFS_ACCESS_KEY=ftbulyR6rj0AZ4n5ID7g
RUSTFS_SECRET_KEY=P8q3VZ1wfMEdGJayu4sxh7NRSAB2H0tkFeTQlXLW
RUSTFS_USE_SSL=false
RUSTFS_BUCKET_TEXTURES=carrot-skin-textures
RUSTFS_BUCKET_AVATARS=carrot-skin-avatars
# =============================================================================
# JWT配置
# =============================================================================
JWT_SECRET=your-jwt-secret-key-change-this-in-production
JWT_EXPIRE_HOURS=168
# =============================================================================
# 日志配置
# =============================================================================
LOG_LEVEL=info
LOG_FORMAT=json
LOG_OUTPUT=logs/app.log
# 保留的旧配置项
LOG_MAX_SIZE=100
LOG_MAX_BACKUPS=3
LOG_MAX_AGE=28
LOG_COMPRESS=true
# =============================================================================
# 文件上传配置 (保留的旧配置项)
# =============================================================================
UPLOAD_MAX_SIZE=10485760
UPLOAD_TEXTURE_MAX_SIZE=2097152
UPLOAD_AVATAR_MAX_SIZE=1048576
# =============================================================================
# 安全配置
# =============================================================================
# CORS 允许的来源,多个用逗号分隔
SECURITY_ALLOWED_ORIGINS=*
# 允许的头像/材质URL域名多个用逗号分隔
SECURITY_ALLOWED_DOMAINS=localhost,127.0.0.1,120.27.110.94
# 保留的旧配置项
MAX_LOGIN_ATTEMPTS=5
LOGIN_LOCK_DURATION=30m
# =============================================================================
# 邮件配置
# =============================================================================
EMAIL_ENABLED=true
EMAIL_SMTP_HOST=smtp.exmail.qq.com
EMAIL_SMTP_PORT=465
EMAIL_USERNAME=system@qczlit.cn
EMAIL_PASSWORD=545mkewZwMzEWUjD
EMAIL_FROM_NAME=CarrotSkin

View File

@@ -1,166 +0,0 @@
# CarrotSkin 环境配置文件示例
# 复制此文件为 .env 并修改相应的配置值
# =============================================================================
# 站点配置
# =============================================================================
SITE_NAME=CarrotSkin
SITE_DESCRIPTION=一个优秀的Minecraft皮肤站
REGISTRATION_ENABLED=true
DEFAULT_AVATAR=
# =============================================================================
# 用户限制配置
# =============================================================================
MAX_TEXTURES_PER_USER=50
MAX_PROFILES_PER_USER=5
# =============================================================================
# 积分配置
# =============================================================================
CHECKIN_REWARD=10
TEXTURE_DOWNLOAD_REWARD=1
# =============================================================================
# 服务器配置
# =============================================================================
SERVER_PORT=:8080
SERVER_MODE=debug
SERVER_READ_TIMEOUT=30s
SERVER_WRITE_TIMEOUT=30s
SERVER_SWAGGER_ENABLED=true
# =============================================================================
# 应用环境
# =============================================================================
# 用于 service 层 IsTestEnvironment() 短路验证码/邮件等
# 取值development / test / production
ENVIRONMENT=production
# =============================================================================
# 数据库配置
# =============================================================================
DATABASE_DRIVER=postgres
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_USERNAME=postgres
DATABASE_PASSWORD=your_password_here
DATABASE_NAME=carrotskin
DATABASE_SSL_MODE=disable
DATABASE_TIMEZONE=Asia/Shanghai
# 连接池配置(优化后的默认值)
# 最大空闲连接数:在连接池中保持的最大空闲连接数
# 建议值CPU核心数 * 2 ~ CPU核心数 * 4
DATABASE_MAX_IDLE_CONNS=10
# 最大打开连接数:允许的最大并发连接数
# 建议值根据并发需求调整高并发场景可设置更高如200-500
DATABASE_MAX_OPEN_CONNS=100
# 连接最大生命周期:连接被重用前的最大存活时间
# 建议值30分钟到1小时避免长时间占用连接
DATABASE_CONN_MAX_LIFETIME=1h
# 连接最大空闲时间:连接被关闭前的最大空闲时间
# 建议值5-15分钟避免长时间空闲占用资源
DATABASE_CONN_MAX_IDLE_TIME=10m
# 连接获取超时:等待获取连接的超时时间(新增)
# 建议值1-5秒避免长时间阻塞
DATABASE_CONN_TIMEOUT=5s
# 查询超时:单次查询的最大执行时间(新增)
# 建议值5-30秒根据业务查询复杂度调整
DATABASE_QUERY_TIMEOUT=30s
# 慢查询阈值记录慢查询的阈值优化从200ms调整为100ms
# 超过此时间的查询将被记录为警告
DATABASE_SLOW_THRESHOLD=100ms
# 健康检查间隔:定期检查数据库连接健康的间隔(新增)
# 建议值30秒到5分钟
DATABASE_HEALTH_CHECK_INTERVAL=30s
# =============================================================================
# Redis配置优化后的默认值
# =============================================================================
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DATABASE=0
# 连接池配置(优化后的默认值)
# 连接池大小:允许的最大并发连接数
# 建议值CPU核心数 * 4 ~ CPU核心数 * 8根据并发需求调整
REDIS_POOL_SIZE=16
# 最小空闲连接数:在连接池中保持的最小空闲连接数
# 建议值CPU核心数 * 2 ~ CPU核心数 * 4
REDIS_MIN_IDLE_CONNS=8
# 最大重试次数:操作失败时的最大重试次数
REDIS_MAX_RETRIES=3
# 连接超时:建立连接的超时时间
# 建议值3-10秒
REDIS_DIAL_TIMEOUT=5s
# 读取超时:读取数据的超时时间
# 建议值3-5秒
REDIS_READ_TIMEOUT=3s
# 写入超时:写入数据的超时时间
# 建议值3-5秒
REDIS_WRITE_TIMEOUT=3s
# 连接池超时:等待获取连接的超时时间
# 建议值3-5秒
REDIS_POOL_TIMEOUT=4s
# 连接最大空闲时间:连接被关闭前的最大空闲时间
# 建议值5-15分钟避免长时间空闲占用资源
REDIS_CONN_MAX_IDLE_TIME=10m
# 连接最大生命周期:连接被重用前的最大存活时间
# 建议值15-30分钟避免长时间占用导致连接问题
REDIS_CONN_MAX_LIFETIME=30m
# 健康检查间隔定期检查Redis连接健康的间隔
# 建议值30秒到5分钟
REDIS_HEALTH_CHECK_INTERVAL=30s
# 错误时启用重试:操作失败时是否启用自动重试
# 建议值true生产环境开发环境可设为false
REDIS_ENABLE_RETRY_ON_ERROR=true
# =============================================================================
# RustFS对象存储配置 (S3兼容)
# =============================================================================
RUSTFS_ENDPOINT=127.0.0.1:9000
RUSTFS_PUBLIC_URL=http://127.0.0.1:9000
RUSTFS_ACCESS_KEY=your_access_key
RUSTFS_SECRET_KEY=your_secret_key
RUSTFS_USE_SSL=false
RUSTFS_BUCKET_TEXTURES=carrot-skin-textures
RUSTFS_BUCKET_AVATARS=carrot-skin-avatars
# =============================================================================
# JWT配置
# =============================================================================
JWT_SECRET=your-jwt-secret-key-change-this-in-production
JWT_EXPIRE_HOURS=168
# =============================================================================
# 日志配置
# =============================================================================
LOG_LEVEL=info
LOG_FORMAT=json
LOG_OUTPUT=logs/app.log
# 日志轮转参数(用于 lumberjack
LOG_MAX_SIZE=100 # 单文件最大 MB
LOG_MAX_BACKUPS=3 # 保留旧文件数
LOG_MAX_AGE=28 # 旧文件最大保留天数
LOG_COMPRESS=true # 是否压缩旧文件
# =============================================================================
# 安全配置
# =============================================================================
# CORS 允许的来源,多个用逗号分隔
SECURITY_ALLOWED_ORIGINS=*
# 允许的头像/材质URL域名多个用逗号分隔
SECURITY_ALLOWED_DOMAINS=localhost,127.0.0.1
# =============================================================================
# 邮件配置
# 腾讯企业邮箱SSL配置示例smtp.exmail.qq.com, 端口465
# =============================================================================
EMAIL_ENABLED=false
EMAIL_SMTP_HOST=smtp.example.com
EMAIL_SMTP_PORT=587
EMAIL_USERNAME=noreply@example.com
EMAIL_PASSWORD=your-email-password
EMAIL_FROM_NAME=CarrotSkin

View File

@@ -32,7 +32,6 @@ jobs:
GOOS: linux
GOARCH: amd64
CGO_ENABLED: 0
GOEXPERIMENT: greenteagc
run: go build -v -o mcauth-linux-amd64 ./cmd/server
- name: Upload artifacts

3
.gitignore vendored
View File

@@ -60,7 +60,7 @@ configs/config.yaml
.env.production
# Keep example files
!.env.example
!.env
# Database files
*.db
@@ -110,4 +110,3 @@ service_coverage
.gitignore
docs/
blessing skin材质渲染示例/
plan/

218
README.md
View File

@@ -8,7 +8,7 @@
- **邮箱与验证码**:验证码发送频率控制、邮箱绑定与变更
- **材质中心**:皮肤/披风上传、搜索、收藏、下载统计、Hash 去重
- **角色档案**Minecraft Profile 管理、RSA 密钥对生成、活跃档案切换
- **存储与上传**RustFS/MinIOS3 兼容直接上传Hash 分片存储
- **存储与上传**RustFS/MinIO 预签名 URL减轻服务器带宽压力
- **任务与日志**:登录日志、操作审计、材质下载记录、定时任务
- **权限体系**Casbin RBAC支持细粒度路线授权
- **配置管理**100% 依赖环境变量,`SERVER_SWAGGER_ENABLED` 控制 Swagger
@@ -18,58 +18,44 @@
| 类型 | 选型 |
| --- | --- |
| 语言 / 运行时 | Go 1.25+ |
| 语言 / 运行时 | Go 1.24+ |
| Web 框架 | Gin |
| ORM | GORM (PostgreSQL 驱动) |
| 数据库 | PostgreSQL 15+ |
| 缓存 / 消息 | Redis 6+ |
| 对象存储 | RustFS / MinIOS3 兼容) |
| 权限控制 | Casbin v3 |
| 依赖注入 | uber-go/fx |
| 配置 | Viper + godotenv + `.env` |
| 权限控制 | Casbin |
| 配置 | Viper + `.env` |
| API 文档 | swaggo / Swagger UI |
| 滑动验证码 | wenlng/go-captcha |
| 日志 | Uber Zap |
## 📁 目录结构
```
backend/
├── cmd/server/ # 应用入口main.go:极简 fx 装配
├── cmd/server/ # 应用入口main.go
├── internal/
│ ├── app/ # uber-go/fx 装配层(唯一依赖注入入口)
│ ├── module.go # 聚合根 Module
│ ├── infra_module.go # Logger/DB/Redis/Storage/Email/JWT/Casbin + 子配置 Provider + Lifecycle
│ ├── container_module.go # Container 聚合 + 迁移/路由/HTTP/任务生命周期
│ ├── repository_module.go # Repository Provider占位Container 模式暂未启用)
│ ├── service_module.go # Service Provider占位
│ ├── handler_module.go # Handler Provider占位
├── server_module.go # HTTP 服务器模块(占位
└── task_module.go # 后台任务模块(占位
│ ├── container/ # 过渡期手动 DI 容器fx 迁移期的聚合层
│ ├── handler/ # HTTP Handler 与 Swagger 注解
│ ├── service/ # 业务逻辑(接口 + 实现)
│ ├── repository/ # 数据访问(接口 + GORM 实现)
│ ├── model/ # GORM 数据模型与响应结构
│ ├── types/ # 请求/响应 DTO
│ ├── errors/ # 统一错误定义apperrors
│ ├── middleware/ # Gin 中间件
│ └── task/ # 定时任务与后台作业
├── pkg/ # 可复用组件config、database、auth、logger、redis、storage、email、utils
├── configs/casbin/ # Casbin RBAC 模型定义rbac_model.conf
├── start.sh # 启动脚本(自动 swag init
├── docker-compose.yml # 本地容器编排(含 rustfs-init 自动建桶)
├── .env.example # 环境变量示例
└── go.mod # Go Module 定义
│ ├── handler/ # HTTP Handler 与 Swagger 注解
│ ├── service/ # 业务逻辑
│ ├── repository/ # 数据访问
│ ├── model/ # GORM 数据模型
│ ├── types/ # 请求/响应 DTO
│ ├── middleware/ # Gin 中间件
└── task/ # 定时任务与后台作业
├── pkg/ # 可复用组件config、database、auth、logger、redis、storage 等
├── docs/ # swagger 生成产物docs.go / swagger.json / swagger.yaml
├── start.sh # 启动脚本(自动 swag init
├── docker-compose.yml # 本地容器编排
├── .env.example # 环境变量示例
└── go.mod # Go Module 定义
```
## ✅ 前置要求
- Go 1.25+
- Go 1.24+
- PostgreSQL 15+
- Redis 6+
- RustFS / MinIO或其他兼容 S3 的对象存储,用于皮肤与头像)
- swag生成 Swagger 文档,见 <https://github.com/swaggo/swag>
## 🚀 快速开始
@@ -86,7 +72,7 @@ backend/
3. **配置环境变量**
```bash
cp .env.example .env
cp .env .env
# 根据实际环境填写数据库、Redis、对象存储、邮件等信息
```
@@ -95,144 +81,25 @@ backend/
createdb carrotskin
# 或 psql -c "CREATE DATABASE carrotskin;"
```
> 应用启动时会执行 `AutoMigrate`,自动创建 / 更新表结构,并写入种子数据(默认管理员 + Casbin 规则)
> 应用启动时会执行 `AutoMigrate`,自动创建 / 更新表结构。
5. **准备对象存储**(创建存储桶 + 配置策略与跨域,**见下方 [🪣 对象存储配置](#-对象存储配置) 章节**
6. **启动服务**
- **推荐**`./start.sh`(自动 `swag init`,随后 `go run ./cmd/server`
5. **启动服务**
- **推荐**`./start.sh`(自动 `swag init`,随后 `go run cmd/server/main.go`
- **手动启动**
```bash
swag init -g cmd/server/main.go -o docs
go run ./cmd/server
go run cmd/server/main.go
```
7. **访问接口**
6. **访问接口**
- API Root: `http://localhost:8080`
- Swagger: `http://localhost:8080/swagger/index.html`(需 `SERVER_SWAGGER_ENABLED=true`
- 健康检查: `http://localhost:8080/health`
### 默认管理员
首次启动会自动 seed 一个管理员账号,**首次登录后请立即修改密码**
| 用户名 | 密码 | 邮箱 |
| --- | --- | --- |
| `admin` | `admin123456` | `admin@example.com` |
## 🪣 对象存储配置
后端使用 S3 兼容的对象存储RustFS / MinIO保存皮肤与头像需要两个存储桶
| 桶名(由环境变量指定) | 默认名 | 用途 |
| --- | --- | --- |
| `RUSTFS_BUCKET_TEXTURES` | `carrot-skin-textures` | 皮肤 / 披风文件 |
| `RUSTFS_BUCKET_AVATARS` | `carrot-skin-avatars` | 用户头像文件 |
> ⚠️ **后端不会自动创建存储桶**。请在启动后端前,手动创建这两个桶并配置好访问策略与跨域,否则上传会失败、前端 3D 皮肤将无法渲染。
### 步骤 1创建存储桶
在 RustFS / MinIO 控制台(默认 `http://<host>:9001`)创建上述两个桶,或使用 `mc` 客户端:
```bash
mc alias set myrustfs http://<host>:9000 <access-key> <secret-key>
mc mb myrustfs/carrot-skin-textures --ignore-existing
mc mb myrustfs/carrot-skin-avatars --ignore-existing
```
### 步骤 2配置桶访问策略匿名只读
皮肤和头像需要被浏览器与 Minecraft 启动器**匿名下载**(后端用密钥上传即可)。给每个桶配置如下 S3 Bucket Policy以 `carrot-skin-textures` 为例,`avatars` 桶把 `Resource` 里的桶名换掉即可):
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::carrot-skin-textures/*"
}
]
}
```
等价的 `mc` 命令:
```bash
mc anonymous set download myrustfs/carrot-skin-textures
mc anonymous set download myrustfs/carrot-skin-avatars
```
### 步骤 3配置 CORS跨域**前端 3D 渲染必需**
> 🔴 **这一步极其关键**。普通的 `<img>` 标签加载图片不要求 CORS但前端用 skinview3d / three.js 通过 **WebGL 纹理**渲染 3D 皮肤时,浏览器**强制要求**图片响应带 `Access-Control-Allow-Origin` 头,否则 canvas 会被判定为 tainted3D 皮肤将加载失败/显示空白。
在 RustFS / MinIO 控制台为**两个桶**各配置一条 CORS 规则,允许前端来源以 GET 方法跨域访问。CORS 规则 JSON贴入桶的 CORS 配置编辑器):
```json
[
{
"AllowedOrigins": ["*"],
"AllowedMethods": ["GET", "HEAD"],
"AllowedHeaders": ["*"],
"ExposeHeaders": ["ETag"],
"MaxAgeSeconds": 86400
}
]
```
> 生产环境建议把 `AllowedOrigins` 收紧为你的前端实际域名(如 `["https://skins.example.com"]`),而不是 `*`。
等价的 `mc` 命令(将 JSON 存为 `cors.json` 后应用):
```bash
mc cors add myrustfs/carrot-skin-textures < cors.json
mc cors add myrustfs/carrot-skin-avatars < cors.json
```
### 验证存储配置是否生效
匿名 GET 任意一个桶内对象,期望返回 `HTTP 200` 且响应头包含 `access-control-allow-origin`
```bash
curl -I -H "Origin: http://localhost:3000" http://<host>:9000/carrot-skin-textures/<某对象路径>
# 期望看到:
# HTTP/1.1 200 OK
# access-control-allow-origin: *
```
若 `access-control-allow-origin` 缺失,说明 CORS 未生效,前端 3D 皮肤将无法渲染。
### 关于 `RUSTFS_PUBLIC_URL`
`RUSTFS_PUBLIC_URL` 决定后端生成的文件访问 URL 前缀(`<public_url>/<bucket>/<object>`)。
- 留空时:用 `RUSTFS_ENDPOINT` + 协议拼接(适合 endpoint 本身就是浏览器可达地址的场景)
- 生产环境:务必填写**浏览器可访问的公网地址**,例如 `https://rustfs.example.com`,否则后端返回给前端的 URL 浏览器打不开
## 🐳 Docker 部署
`docker-compose.yml` 提供了完整的本地编排,包含 PostgreSQL、Redis、RustFS以及一个一次性的 `rustfs-init` 服务自动创建存储桶并设置匿名下载策略:
```bash
# 启动全部基础设施(含存储)
docker compose --profile storage up -d
# 仅启动应用
docker compose up -d
```
> `rustfs-init` 使用 `mc` 完成建桶与策略配置。CORS 仍需按上文 [步骤 3](#步骤-3配置-cors跨域前端-3d-渲染必需) 手动配置。
## ⚙️ 关键环境变量
| 变量 | 说明 | 示例 |
| --- | --- | --- |
| `SERVER_PORT` | 服务监听端口 | `:8080` |
| `SERVER_PORT` | 服务监听端口 | `8080` |
| `SERVER_MODE` | Gin 模式debug/release | `debug` |
| `SERVER_SWAGGER_ENABLED` | 是否暴露 Swagger UI | `true` |
| `DATABASE_HOST` / `DATABASE_PORT` | PostgreSQL 地址 | `localhost` / `5432` |
@@ -240,16 +107,12 @@ docker compose up -d
| `DATABASE_NAME` | 数据库名称 | `carrotskin` |
| `REDIS_HOST` / `REDIS_PORT` | Redis 地址 | `localhost` / `6379` |
| `REDIS_PASSWORD` | Redis 密码(无可为空) | `` |
| `RUSTFS_ENDPOINT` | RustFS/MinIO 访问地址(后端内网连接用) | `127.0.0.1:9000` |
| `RUSTFS_PUBLIC_URL` | 生成文件 URL 的公开前缀(浏览器可达) | `https://rustfs.example.com` |
| `RUSTFS_ENDPOINT` | RustFS/MinIO 访问地址 | `127.0.0.1:9000` |
| `RUSTFS_ACCESS_KEY` / `RUSTFS_SECRET_KEY` | 对象存储凭据 | `minioadmin` |
| `RUSTFS_BUCKET_TEXTURES` / `RUSTFS_BUCKET_AVATARS` | 存储桶名称 | `carrot-skin-textures` |
| `RUSTFS_BUCKET_TEXTURES` / `RUSTFS_BUCKET_AVATARS` | 存储桶名称 | `carrotskin-textures` |
| `JWT_SECRET` | JWT 签名密钥 | `change-me` |
| `EMAIL_ENABLED` | 是否开启邮件服务 | `true` |
| `EMAIL_SMTP_HOST` / `EMAIL_SMTP_PORT` | SMTP 配置 | `smtp.example.com` / `587` |
| `ENVIRONMENT` | 应用环境(用于 service 层 `IsTestEnvironment()` 短路) | `production` |
| `SECURITY_ALLOWED_ORIGINS` | API CORS 允许的来源(逗号分隔) | `*` |
| `SECURITY_ALLOWED_DOMAINS` | 头像/材质 URL 允许的域名(逗号分隔) | `localhost,127.0.0.1` |
更多变量请参考 `.env.example` 与 `.env.docker.example`。
@@ -269,28 +132,17 @@ golangci-lint run (若已安装)
## 🧱 架构说明
- **分层设计**Handler Service Repository Model层次清晰、职责单一。
- Handler 不得直连 `*gorm.DB` 或 `*Repository`,必须通过 Service
- Service 的数据访问通过 Repository 接口(个别需要跨表事务的场景除外)。
- **依赖注入uber-go/fx**
- `internal/app/` 是唯一的依赖装配入口。每个基础设施 / 仓储 / 服务作为 `fx.Provider` 注册。
- **子配置 Provider**`infra_module.go` 从 `*config.Config` 提取 `DatabaseConfig` / `RedisConfig` / `RustFSConfig` / `LogConfig` / `EmailConfig` 等子结构,按值注入到各 `pkg/*` 包的构造函数。
- **生命周期管理**DB / Redis / Storage / Logger / HTTP Server / Task Runner 通过 `fx.Lifecycle` 的 `OnStart` / `OnStop` Hook 统一管理,彻底替代散落在 `main()` 的 `defer Close()` 链。
- **优雅关闭**`fx.New(app.Module(cfg)).Run()` 监听 `SIGINT` / `SIGTERM`,按依赖逆序触发 `OnStop`,先关 HTTP Server30s 超时),再关 Task Runner最后关 DB/Redis。
- **Dev/Test 自动回退**Redis 连接失败且环境为 `development` / `test` / `dev` / `USE_MINIREDIS=true` 时自动启用 `miniredis`。
- **启动时错误检查**:循环依赖、缺失 Provider、Provider 返回 error 全部在 `fx.New()` 阶段立即检测。
- **错误与响应统一**
- 错误统一在 `internal/errors/`(别名 `apperrors`),通过 `errors.Is/As` 匹配。
- 响应统一使用 `model.Response` / `model.PaginationResponse` / `model.NewErrorResponse`。
- Middleware 错误响应也走 `model.NewErrorResponse`,不再使用裸 `gin.H`。
- **配置优先级**`config.Load()` 读取 `.env` → 环境变量 → viper 默认值;`*config.Config` 由 `fx.Supply` 注入。
- **分层设计**Handler -> Service -> Repository -> Model层次清晰、职责单一。
- **依赖管理器**`pkg/*/manager.go` 使用 `sync.Once` 实现线程安全单例DB / Redis / Logger / Storage / Email / Auth / Config
- **Swagger 注解**:所有 Handler、模型、DTO 均补齐 `@Summary` / `@Description` / `@Success`,可直接生成 OpenAPI 文档。
- **配置优先级**`.env` -> 系统环境变量,所有配置均可通过容器注入。
- **自动任务**`internal/task` 承载后台作业,可按需扩展。
## 📝 Swagger 说明
- `start.sh` 会在启动前执行 `swag init -g cmd/server/main.go -o docs`,生成 `docs/` 目录(`docs.go` / `swagger.json` / `swagger.yaml`)。
- `docs/` 为生成产物,**不在仓库内跟踪**,首次启动会自动生成。
- 通过 `SERVER_SWAGGER_ENABLED=false` 可在生产环境关闭 Swagger UI 暴露
- `start.sh` 会在启动前执行 `swag init -g cmd/server/main.go -o docs`
- 若手动运行,需要保证 `docs/` 下的 `docs.go`、`swagger.json`、`swagger.yaml` 与代码同步
- 通过 `SERVER_SWAGGER_ENABLED=false` 可在生产环境关闭 Swagger UI 暴露
## 🤝 贡献指南

View File

@@ -1,21 +0,0 @@
package main
import (
"fmt"
"os"
"carrotskin/pkg/auth"
)
func main() {
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, "usage: genhash <password>")
os.Exit(2)
}
h, err := auth.HashPassword(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, "err:", err)
os.Exit(1)
}
fmt.Print(h)
}

View File

@@ -10,28 +10,171 @@
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
_ "time/tzdata"
"carrotskin/internal/app"
"carrotskin/internal/container"
"carrotskin/internal/handler"
"carrotskin/internal/middleware"
"carrotskin/internal/task"
"carrotskin/pkg/auth"
"carrotskin/pkg/config"
"carrotskin/pkg/database"
"carrotskin/pkg/email"
"carrotskin/pkg/logger"
"carrotskin/pkg/redis"
"carrotskin/pkg/storage"
"go.uber.org/fx"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// main 应用入口。通过 uber-go/fx 装配所有依赖并管理生命周期。
//
// fx.Run() 会:
// 1. 按 fx.Supply/Provide 构建依赖图
// 2. 执行所有 fx.Invoke迁移、路由注册、服务器/任务启动)
// 3. 监听 SIGINT/SIGTERM 信号
// 4. 按依赖逆序执行所有 OnStop 钩子(优雅关闭)
func main() {
// 加载配置(唯一的全局入口,配置本身是无状态的纯数据)
cfg, err := config.Load()
if err != nil {
// 初始化配置
if err := config.Init(); err != nil {
log.Fatalf("配置加载失败: %v", err)
}
cfg := config.MustGetConfig()
// 创建并运行 fx 应用
fx.New(app.Module(cfg)).Run()
// 初始化日志
if err := logger.Init(cfg.Log); err != nil {
log.Fatalf("日志初始化失败: %v", err)
}
loggerInstance := logger.MustGetLogger()
defer loggerInstance.Sync()
// 初始化数据库
if err := database.Init(cfg.Database, loggerInstance); err != nil {
loggerInstance.Fatal("数据库初始化失败", zap.Error(err))
}
defer database.Close()
// 执行数据库迁移
if err := database.AutoMigrate(loggerInstance); err != nil {
loggerInstance.Fatal("数据库迁移失败", zap.Error(err))
}
// 初始化种子数据
if err := database.Seed(loggerInstance); err != nil {
loggerInstance.Fatal("种子数据初始化失败", zap.Error(err))
}
// 初始化JWT服务
if err := auth.Init(cfg.JWT); err != nil {
loggerInstance.Fatal("JWT服务初始化失败", zap.Error(err))
}
// 初始化Redis开发/测试环境失败时会自动回退到miniredis
if err := redis.Init(cfg.Redis, loggerInstance); err != nil {
loggerInstance.Fatal("Redis初始化失败", zap.Error(err))
}
defer redis.Close()
// 记录Redis模式
if redis.IsUsingMiniRedis() {
loggerInstance.Info("使用miniredis进行开发/测试")
} else {
loggerInstance.Info("使用生产Redis")
}
// 初始化对象存储 (RustFS - S3兼容)
var storageClient *storage.StorageClient
if err := storage.Init(cfg.RustFS); err != nil {
loggerInstance.Warn("对象存储连接失败,某些功能可能不可用", zap.Error(err))
} else {
storageClient = storage.MustGetClient()
loggerInstance.Info("对象存储连接成功")
}
// 初始化邮件服务
if err := email.Init(cfg.Email, loggerInstance); err != nil {
loggerInstance.Fatal("邮件服务初始化失败", zap.Error(err))
}
emailServiceInstance := email.MustGetService()
// 初始化Casbin权限服务
casbinService, err := auth.NewCasbinService(database.MustGetDB(), cfg.Casbin.ModelPath, loggerInstance)
if err != nil {
loggerInstance.Fatal("Casbin服务初始化失败", zap.Error(err))
}
// 创建依赖注入容器
c := container.NewContainer(
database.MustGetDB(),
redis.MustGetClient(),
loggerInstance,
auth.MustGetJWTService(),
casbinService,
storageClient,
emailServiceInstance,
)
// 设置Gin模式
if cfg.Server.Mode == "production" {
gin.SetMode(gin.ReleaseMode)
}
// 创建路由
router := gin.New()
// 禁用自动重定向允许API路径带或不带/结尾都能正常访问
router.RedirectTrailingSlash = false
router.RedirectFixedPath = false
// 添加中间件
router.Use(middleware.Logger(loggerInstance))
router.Use(middleware.Recovery(loggerInstance))
router.Use(middleware.CORS())
// 使用依赖注入方式注册路由
handler.RegisterRoutesWithDI(router, c)
// 启动后台任务Token已迁移到Redis不再需要清理任务
// 如需使用数据库Token存储可以恢复TokenCleanupTask
taskRunner := task.NewRunner(loggerInstance)
taskCtx, taskCancel := context.WithCancel(context.Background())
defer taskCancel()
taskRunner.Start(taskCtx)
// 创建HTTP服务器
srv := &http.Server{
Addr: cfg.Server.Port,
Handler: router,
ReadTimeout: cfg.Server.ReadTimeout,
WriteTimeout: cfg.Server.WriteTimeout,
}
// 启动服务器
go func() {
loggerInstance.Info("服务器启动", zap.String("port", cfg.Server.Port))
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
loggerInstance.Fatal("服务器启动失败", zap.Error(err))
}
}()
// 等待中断信号优雅关闭
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
loggerInstance.Info("正在关闭服务器...")
// 停止后台任务
taskCancel()
taskRunner.Wait()
// 设置关闭超时
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
loggerInstance.Fatal("服务器强制关闭", zap.Error(err))
}
loggerInstance.Info("服务器已关闭")
}

126
go.mod
View File

@@ -1,27 +1,24 @@
module carrotskin
go 1.25.0
go 1.24.0
// Enable new GC (Generational GC) for Go 1.25
// GOGC=100 (default), GOMEMLIMIT=0 (no limit)
// Build with: go build -gcflags="-G=3" to enable generational GC
toolchain go1.24.2
require (
github.com/alicebob/miniredis/v2 v2.36.1
github.com/casbin/casbin/v3 v3.10.0
github.com/alicebob/miniredis/v2 v2.31.1
github.com/casbin/casbin/v2 v2.123.0
github.com/gin-gonic/gin v1.11.0
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/golang-jwt/jwt/v5 v5.3.0
github.com/joho/godotenv v1.5.1
github.com/minio/minio-go/v7 v7.0.98
github.com/redis/go-redis/v9 v9.18.0
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible
github.com/minio/minio-go/v7 v7.0.97
github.com/redis/go-redis/v9 v9.17.2
github.com/spf13/viper v1.21.0
github.com/swaggo/files v1.0.1
github.com/swaggo/gin-swagger v1.6.1
github.com/wenlng/go-captcha-assets v1.0.7
github.com/wenlng/go-captcha/v2 v2.0.4
go.uber.org/fx v1.24.0
go.uber.org/zap v1.27.1
gopkg.in/mail.v2 v2.3.1
gorm.io/datatypes v1.2.7
gorm.io/driver/postgres v1.6.0
gorm.io/driver/sqlite v1.6.0
@@ -29,86 +26,79 @@ require (
)
require (
filippo.io/edwards25519 v1.2.0 // indirect
filippo.io/edwards25519 v1.1.0 // indirect
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/bmatcuk/doublestar/v4 v4.10.0 // indirect
github.com/PuerkitoBio/purell v1.1.1 // indirect
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a // indirect
github.com/bmatcuk/doublestar/v4 v4.6.1 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/casbin/govaluate v1.10.0 // indirect
github.com/bytedance/sonic/loader v0.4.0 // indirect
github.com/casbin/govaluate v1.3.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/glebarez/go-sqlite v1.22.0 // indirect
github.com/glebarez/sqlite v1.11.0 // indirect
github.com/glebarez/go-sqlite v1.20.3 // indirect
github.com/glebarez/sqlite v1.7.0 // indirect
github.com/go-ini/ini v1.67.0 // indirect
github.com/go-openapi/jsonpointer v0.22.4 // indirect
github.com/go-openapi/jsonreference v0.21.4 // indirect
github.com/go-openapi/spec v0.22.3 // indirect
github.com/go-openapi/swag/conv v0.25.4 // indirect
github.com/go-openapi/swag/jsonname v0.25.4 // indirect
github.com/go-openapi/swag/jsonutils v0.25.4 // indirect
github.com/go-openapi/swag/loading v0.25.4 // indirect
github.com/go-openapi/swag/stringutils v0.25.4 // indirect
github.com/go-openapi/swag/typeutils v0.25.4 // indirect
github.com/go-openapi/swag/yamlutils v0.25.4 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.19.6 // indirect
github.com/go-openapi/spec v0.20.4 // indirect
github.com/go-openapi/swag v0.19.15 // indirect
github.com/go-sql-driver/mysql v1.9.3 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/goccy/go-yaml v1.18.0 // indirect
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
github.com/golang-sql/sqlexp v0.1.0 // indirect
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/klauspost/crc32 v1.3.0 // indirect
github.com/mattn/go-sqlite3 v1.14.34 // indirect
github.com/microsoft/go-mssqldb v1.9.6 // indirect
github.com/minio/crc64nvme v1.1.1 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/mailru/easyjson v0.7.6 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/microsoft/go-mssqldb v1.7.2 // indirect
github.com/minio/crc64nvme v1.1.0 // indirect
github.com/philhofer/fwd v1.2.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/quic-go/qpack v0.5.1 // indirect
github.com/quic-go/quic-go v0.54.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230126093431-47fa9a501578 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
github.com/tinylib/msgp v1.6.3 // indirect
github.com/yuin/gopher-lua v1.1.1 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/dig v1.19.0 // indirect
go.uber.org/mock v0.6.0 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect
golang.org/x/image v0.36.0 // indirect
golang.org/x/mod v0.33.0 // indirect
golang.org/x/sync v0.19.0 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
github.com/tinylib/msgp v1.3.0 // indirect
github.com/yuin/gopher-lua v1.1.0 // indirect
go.uber.org/mock v0.5.0 // indirect
golang.org/x/image v0.33.0 // indirect
golang.org/x/mod v0.30.0 // indirect
golang.org/x/sync v0.18.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gorm.io/driver/mysql v1.6.0 // indirect
gorm.io/driver/sqlserver v1.6.3 // indirect
gorm.io/plugin/dbresolver v1.6.2 // indirect
modernc.org/libc v1.68.0 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
modernc.org/sqlite v1.46.1 // indirect
gorm.io/driver/sqlserver v1.6.0 // indirect
gorm.io/plugin/dbresolver v1.6.0 // indirect
modernc.org/libc v1.22.2 // indirect
modernc.org/mathutil v1.5.0 // indirect
modernc.org/memory v1.5.0 // indirect
modernc.org/sqlite v1.20.3 // indirect
)
require (
github.com/bytedance/sonic v1.15.0 // indirect
github.com/casbin/gorm-adapter/v3 v3.41.0
github.com/bytedance/sonic v1.14.2 // indirect
github.com/casbin/gorm-adapter/v3 v3.39.0
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
github.com/gabriel-vasile/mimetype v1.4.11 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/go-playground/validator/v10 v10.28.0 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/google/uuid v1.6.0
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.8.0 // indirect
github.com/jackc/pgx/v5 v5.7.6
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12
github.com/klauspost/compress v1.18.4 // indirect
github.com/klauspost/compress v1.18.2 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
@@ -126,11 +116,13 @@ require (
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/arch v0.24.0 // indirect
golang.org/x/crypto v0.48.0
golang.org/x/net v0.50.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/text v0.34.0 // indirect
golang.org/x/tools v0.42.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/arch v0.23.0 // indirect
golang.org/x/crypto v0.45.0
golang.org/x/net v0.47.0 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/text v0.31.0 // indirect
golang.org/x/tools v0.39.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

398
go.sum
View File

@@ -1,55 +1,56 @@
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.7.0/go.mod h1:bjGvMhVMb+EEm3VRNQawDMUyMMjo+S5ewNjflkep/0Q=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.7.1/go.mod h1:bjGvMhVMb+EEm3VRNQawDMUyMMjo+S5ewNjflkep/0Q=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.11.1/go.mod h1:a6xsAQUZg+VsS3TJ05SRp524Hs4pZ/AeFSr5ENf0Yjo=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.18.0 h1:Gt0j3wceWMwPmiazCa8MzMA0MfhmPIz0Qp0FJ6qcM0U=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.18.0/go.mod h1:Ot/6aikWnKWi4l9QB7qVSwa8iMphQNqkWALMoNT3rzM=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.3.1/go.mod h1:uE9zaUfEQT/nbQjVi2IblCG9iaLtZsuYZ8ne+PuQ02M=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.6.0/go.mod h1:9kIvujWAA58nmPmWB1m23fyWic1kYZMxD9CxaWn4Qpg=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.10.1 h1:B+blDbyVIG3WaikNxPnhPiJ1MThR03b3vKGtER95TP4=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.10.1/go.mod h1:JdM5psgjfBf5fo2uWOZhflPWyDBZ/O/CNAH9CtsuZE4=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0/go.mod h1:okt5dMMTOFjX/aovMlrjvvXoPMBVSPzk9185BT0+eZM=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2/go.mod h1:yInRyqWXAuaPrgI7p70+lDDgh3mlBohis29jGMISnmc=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.8.0/go.mod h1:4OG6tQ9EOP/MT0NMjDlRzWoVFxfu9rN9B2X+tlSVktg=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.1 h1:FPKJS1T+clwv+OLGt13a8UjqeRuh0O4SJ3lUriThc+4=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.1/go.mod h1:j2chePtV91HrC22tGoRX3sGY42uF13WzmmV80/OdVAA=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.0.0/go.mod h1:uGG2W01BaETf0Ozp+QxxKJdMBNRWPdstHG0Fmdwn1/U=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.1.2/go.mod h1:uGG2W01BaETf0Ozp+QxxKJdMBNRWPdstHG0Fmdwn1/U=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1 h1:lGlwhPtrX6EVml1hO0ivjkUxsSyl4dsiw9qcA1k/3IQ=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.1/go.mod h1:RKUqNu35KJYcVG/fqTRqmuXJZYNhYkBrnC/hX7yGbTA=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.1.0/go.mod h1:bhXu1AjYL+wutSL/kpSq6s7733q2Rb0yuot9Zgfqa/0=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1 h1:sO0/P7g68FrryJzljemN+6GTssUXdANk6aJ7T1ZxnsQ=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1/go.mod h1:h8hyGFDsU5HMivxiS2iYFZsgDbU9OnnJ163x5UGVKYo=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.0.0/go.mod h1:eWRD7oawr1Mu1sLCawqVc0CUiF43ia3qQMxLscsKQ9w=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1 h1:6oNBlSdi1QqM1PNW7FPA6xOGA5UNsXnkaYZz9vdPGhA=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.1/go.mod h1:s4kgfzA0covAXNicZHDMN58jExvcng2mC/DepXiF1EI=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.0.1 h1:MyVTgWR8qd/Jw1Le0NZebGBUCLbtak3bJ3z1OlqZBpw=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.0.1/go.mod h1:GpPjLhVR9dnUoJMyHWSPy71xY9/lcmpzIPZXmF0FCVY=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.3.1 h1:Wgf5rZba3YZqeTNJPtvqZoBu1sBN/L4sry+u2U3Y75w=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.3.1/go.mod h1:xxCBG/f/4Vbmh2XQJBsOmNdxWUY5j/s27jujKPbQf14=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.0 h1:D3occbWoio4EBLkbkevetNMAVX197GkzbUMtqjGWn80=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.0/go.mod h1:bTSOgj05NGRuHHhQwAdPnYr9TOdNmKlZTgGLL6nyAdI=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.1 h1:bFWuoEKg+gImo7pvkiQEFAc8ocibADgXeiLAxWhWmkI=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.1/go.mod h1:Vih/3yc6yac2JzU4hzpaDupBJP0Flaia9rXXrU8xyww=
github.com/AzureAD/microsoft-authentication-library-for-go v1.1.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI=
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI=
github.com/AzureAD/microsoft-authentication-library-for-go v1.4.2 h1:oygO0locgZJe7PpYPXT5A29ZkwJaPqcva7BVeemZOZs=
github.com/AzureAD/microsoft-authentication-library-for-go v1.4.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI=
github.com/AzureAD/microsoft-authentication-library-for-go v0.5.1/go.mod h1:Vt9sXTKwMyGcOxSmLDMnGPgqsUg7m8pe215qMLrDXw4=
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1 h1:DzHpqpoJVaCgOUdVHxE8QB52S6NiVdDQvGlny1qvPqA=
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI=
github.com/DmitriyVTitov/size v1.5.0/go.mod h1:le6rNI4CoLQV1b9gzp1+3d7hMAD/uu2QcJ+aYbNgiU0=
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
github.com/alicebob/miniredis/v2 v2.36.1 h1:Dvc5oAnNOr7BIfPn7tF269U8DvRW1dBG2D5n0WrfYMI=
github.com/alicebob/miniredis/v2 v2.36.1/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM=
github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a h1:HbKu58rmZpUGpz5+4FfNmIU+FmZg2P3Xaj2v2bfNWmk=
github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
github.com/alicebob/miniredis/v2 v2.31.1 h1:7XAt0uUg3DtwEKW5ZAGa+K7FZV2DdKQo5K/6TTnfX8Y=
github.com/alicebob/miniredis/v2 v2.31.1/go.mod h1:UB/T2Uztp7MlFSDakaX1sTXUv5CASoprx0wulRT6HBg=
github.com/bmatcuk/doublestar/v4 v4.6.1 h1:FH9SifrbvJhnlQpztAx++wlkk70QBf0iBWDwNy7PA4I=
github.com/bmatcuk/doublestar/v4 v4.6.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=
github.com/bmatcuk/doublestar/v4 v4.10.0 h1:zU9WiOla1YA122oLM6i4EXvGW62DvKZVxIe6TYWexEs=
github.com/bmatcuk/doublestar/v4 v4.10.0/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/casbin/casbin/v3 v3.10.0 h1:039ORla55vCeIZWd0LfzWFt1yiEA5X4W41xBW2bQuHs=
github.com/casbin/casbin/v3 v3.10.0/go.mod h1:5rJbQr2e6AuuDDNxnPc5lQlC9nIgg6nS1zYwKXhpHC8=
github.com/casbin/gorm-adapter/v3 v3.41.0 h1:Xhpi0tfRP9aKPDWDf6dgBxHZ9UM6IophxxPIEGWqCNM=
github.com/casbin/gorm-adapter/v3 v3.41.0/go.mod h1:BQZRJhwUnwMpI+pT2m7/cUJwXxrHfzpBpPcNTyMGeGA=
github.com/bytedance/sonic v1.14.2 h1:k1twIoe97C1DtYUo+fZQy865IuHia4PR5RPiuGPPIIE=
github.com/bytedance/sonic v1.14.2/go.mod h1:T80iDELeHiHKSc0C9tubFygiuXoGzrkjKzX2quAx980=
github.com/bytedance/sonic/loader v0.4.0 h1:olZ7lEqcxtZygCK9EKYKADnpQoYkRQxaeY2NYzevs+o=
github.com/bytedance/sonic/loader v0.4.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/casbin/casbin/v2 v2.123.0 h1:UkiMllBgn3MrwHGiZTDFVTV9up+W2CRLufZwKiuAmpA=
github.com/casbin/casbin/v2 v2.123.0/go.mod h1:Ee33aqGrmES+GNL17L0h9X28wXuo829wnNUnS0edAco=
github.com/casbin/gorm-adapter/v3 v3.39.0 h1:k15txH6vE4796MuA+LFcU8I1vMjutklyzMXfjDz7lzo=
github.com/casbin/gorm-adapter/v3 v3.39.0/go.mod h1:kjXoK8MqA3E/CcqEF2l3SCkhJj1YiHVR6SF0LMvJoH4=
github.com/casbin/govaluate v1.3.0 h1:VA0eSY0M2lA86dYd5kPPuNZMUD9QkWnOCnavGrw9myc=
github.com/casbin/govaluate v1.3.0/go.mod h1:G/UnbIjZk/0uMNaLwZZmFQrR72tYRZWQkO70si/iR7A=
github.com/casbin/govaluate v1.10.0 h1:ffGw51/hYH3w3rZcxO/KcaUIDOLP84w7nsidMVgaDG0=
github.com/casbin/govaluate v1.10.0/go.mod h1:G/UnbIjZk/0uMNaLwZZmFQrR72tYRZWQkO70si/iR7A=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
@@ -66,102 +67,87 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gabriel-vasile/mimetype v1.4.11 h1:AQvxbp830wPhHTqc1u7nzoLT+ZFxGY7emj5DR5DYFik=
github.com/gabriel-vasile/mimetype v1.4.11/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4=
github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec+ruQ=
github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc=
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
github.com/glebarez/go-sqlite v1.20.3 h1:89BkqGOXR9oRmG58ZrzgoY/Fhy5x0M+/WV48U5zVrZ4=
github.com/glebarez/go-sqlite v1.20.3/go.mod h1:u3N6D/wftiAzIOJtZl6BmedqxmmkDfH3q+ihjqxC9u0=
github.com/glebarez/sqlite v1.7.0 h1:A7Xj/KN2Lvie4Z4rrgQHY8MsbebX3NyWsL3n2i82MVI=
github.com/glebarez/sqlite v1.7.0/go.mod h1:PkeevrRlF/1BhQBCnzcMWzgrIk7IOop+qS2jUYLfHhk=
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
github.com/go-openapi/jsonpointer v0.22.4 h1:dZtK82WlNpVLDW2jlA1YCiVJFVqkED1MegOUy9kR5T4=
github.com/go-openapi/jsonpointer v0.22.4/go.mod h1:elX9+UgznpFhgBuaMQ7iu4lvvX1nvNsesQ3oxmYTw80=
github.com/go-openapi/jsonreference v0.21.4 h1:24qaE2y9bx/q3uRK/qN+TDwbok1NhbSmGjjySRCHtC8=
github.com/go-openapi/jsonreference v0.21.4/go.mod h1:rIENPTjDbLpzQmQWCj5kKj3ZlmEh+EFVbz3RTUh30/4=
github.com/go-openapi/spec v0.22.3 h1:qRSmj6Smz2rEBxMnLRBMeBWxbbOvuOoElvSvObIgwQc=
github.com/go-openapi/spec v0.22.3/go.mod h1:iIImLODL2loCh3Vnox8TY2YWYJZjMAKYyLH2Mu8lOZs=
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs=
github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns=
github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M=
github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I=
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
github.com/go-openapi/swag/conv v0.25.4 h1:/Dd7p0LZXczgUcC/Ikm1+YqVzkEeCc9LnOWjfkpkfe4=
github.com/go-openapi/swag/conv v0.25.4/go.mod h1:3LXfie/lwoAv0NHoEuY1hjoFAYkvlqI/Bn5EQDD3PPU=
github.com/go-openapi/swag/jsonname v0.25.4 h1:bZH0+MsS03MbnwBXYhuTttMOqk+5KcQ9869Vye1bNHI=
github.com/go-openapi/swag/jsonname v0.25.4/go.mod h1:GPVEk9CWVhNvWhZgrnvRA6utbAltopbKwDu8mXNUMag=
github.com/go-openapi/swag/jsonutils v0.25.4 h1:VSchfbGhD4UTf4vCdR2F4TLBdLwHyUDTd1/q4i+jGZA=
github.com/go-openapi/swag/jsonutils v0.25.4/go.mod h1:7OYGXpvVFPn4PpaSdPHJBtF0iGnbEaTk8AvBkoWnaAY=
github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4 h1:IACsSvBhiNJwlDix7wq39SS2Fh7lUOCJRmx/4SN4sVo=
github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4/go.mod h1:Mt0Ost9l3cUzVv4OEZG+WSeoHwjWLnarzMePNDAOBiM=
github.com/go-openapi/swag/loading v0.25.4 h1:jN4MvLj0X6yhCDduRsxDDw1aHe+ZWoLjW+9ZQWIKn2s=
github.com/go-openapi/swag/loading v0.25.4/go.mod h1:rpUM1ZiyEP9+mNLIQUdMiD7dCETXvkkC30z53i+ftTE=
github.com/go-openapi/swag/stringutils v0.25.4 h1:O6dU1Rd8bej4HPA3/CLPciNBBDwZj9HiEpdVsb8B5A8=
github.com/go-openapi/swag/stringutils v0.25.4/go.mod h1:GTsRvhJW5xM5gkgiFe0fV3PUlFm0dr8vki6/VSRaZK0=
github.com/go-openapi/swag/typeutils v0.25.4 h1:1/fbZOUN472NTc39zpa+YGHn3jzHWhv42wAJSN91wRw=
github.com/go-openapi/swag/typeutils v0.25.4/go.mod h1:Ou7g//Wx8tTLS9vG0UmzfCsjZjKhpjxayRKTHXf2pTE=
github.com/go-openapi/swag/yamlutils v0.25.4 h1:6jdaeSItEUb7ioS9lFoCZ65Cne1/RZtPBZ9A56h92Sw=
github.com/go-openapi/swag/yamlutils v0.25.4/go.mod h1:MNzq1ulQu+yd8Kl7wPOut/YHAAU/H6hL91fF+E2RFwc=
github.com/go-openapi/testify/enable/yaml/v2 v2.0.2 h1:0+Y41Pz1NkbTHz8NngxTuAXxEodtNSI1WG1c/m5Akw4=
github.com/go-openapi/testify/enable/yaml/v2 v2.0.2/go.mod h1:kme83333GCtJQHXQ8UKX3IBZu6z8T5Dvy5+CW3NLUUg=
github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls=
github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54=
github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688=
github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU=
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang-jwt/jwt v3.2.1+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A=
github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc=
github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=
github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=
github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs=
github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM=
github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo=
github.com/jcmturner/gofork v1.0.0/go.mod h1:MK8+TM0La+2rjBD4jE12Kj1pCCxK7d2LK/UM3ncEo0o=
github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg=
github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=
github.com/jcmturner/gokrb5/v8 v8.4.2/go.mod h1:sb+Xq/fTY5yktf/VxLsE3wlfPqQjp0aWNYyvBVK62bc=
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
@@ -169,16 +155,20 @@ github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible h1:jdpOPRN1zP63Td1hDQbZW73xKmzDvZHzVdNYxhnTMDA=
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible/go.mod h1:1c7szIrayyPPB/987hsnvNzLushdWf4o/79s3P08L8A=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=
github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk=
github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
@@ -191,58 +181,58 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lib/pq v1.10.2 h1:AqzbZs4ZoCBp+GtejcpCpcxM3zlSMx29dXbUSeVtJb8=
github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.34 h1:3NtcvcUnFBPsuRcno8pUtupspG/GM+9nZ88zgJcp6Zk=
github.com/mattn/go-sqlite3 v1.14.34/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/microsoft/go-mssqldb v1.8.2/go.mod h1:vp38dT33FGfVotRiTmDo3bFyaHq+p3LektQrjTULowo=
github.com/microsoft/go-mssqldb v1.9.6 h1:1MNQg5UiSsokiPz3++K2KPx4moKrwIqly1wv+RyCKTw=
github.com/microsoft/go-mssqldb v1.9.6/go.mod h1:yYMPDufyoF2vVuVCUGtZARr06DKFIhMrluTcgWlXpr4=
github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI=
github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/microsoft/go-mssqldb v0.19.0/go.mod h1:ukJCBnnzLzpVF0qYRT+eg1e+eSwjeQ7IvenUv8QPook=
github.com/microsoft/go-mssqldb v1.7.2 h1:CHkFJiObW7ItKTJfHo1QX7QBBD1iV+mn1eOyRP3b/PA=
github.com/microsoft/go-mssqldb v1.7.2/go.mod h1:kOvZKUdrhhFQmxLZqbwUV0rHkNkZpthMITIb2Ko1IoA=
github.com/minio/crc64nvme v1.1.0 h1:e/tAguZ+4cw32D+IO/8GSf5UVr9y+3eJcxZI2WOO/7Q=
github.com/minio/crc64nvme v1.1.0/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
github.com/minio/minio-go/v7 v7.0.98 h1:MeAVKjLVz+XJ28zFcuYyImNSAh8Mq725uNW4beRisi0=
github.com/minio/minio-go/v7 v7.0.98/go.mod h1:cY0Y+W7yozf0mdIclrttzo1Iiu7mEf9y7nk2uXqMOvM=
github.com/minio/minio-go/v7 v7.0.97 h1:lqhREPyfgHTB/ciX8k2r8k0D93WaFqxbJX36UZq5occ=
github.com/minio/minio-go/v7 v7.0.97/go.mod h1:re5VXuo0pwEtoNLsNuSr0RrLfT/MBtohwdaSmPPSRSk=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8=
github.com/montanaflynn/stats v0.7.0/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/montanaflynn/stats v0.6.6/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
github.com/pkg/browser v0.0.0-20210115035449-ce105d075bb4/go.mod h1:N6UoU20jOqggOuDwUaBQpluzLNDqif3kq9z2wpdYEfQ=
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
github.com/redis/go-redis/v9 v9.17.2 h1:P2EGsA4qVIM3Pp+aPocCJ7DguDHhqrXNhVcEp4ViluI=
github.com/redis/go-redis/v9 v9.17.2/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/remyoudompheng/bigfft v0.0.0-20230126093431-47fa9a501578 h1:VstopitMQi3hZP0fzvnsLmzXZdQGc4bEcgu24cp+d4M=
github.com/remyoudompheng/bigfft v0.0.0-20230126093431-47fa9a501578/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4=
github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI=
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
@@ -257,12 +247,11 @@ github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpE
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
@@ -274,8 +263,8 @@ github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs
github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw=
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
github.com/tinylib/msgp v1.6.3 h1:bCSxiTz386UTgyT1i0MSCvdbWjVW+8sG3PjkGsZQt4s=
github.com/tinylib/msgp v1.6.3/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww=
github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
@@ -285,74 +274,59 @@ github.com/wenlng/go-captcha-assets v1.0.7/go.mod h1:zinRACsdYcL/S6pHgI9Iv7FKTU4
github.com/wenlng/go-captcha/v2 v2.0.4 h1:5cSUF36ZyA03qeDMjKmeXGpbYJMXEexZIYK3Vga3ME0=
github.com/wenlng/go-captcha/v2 v2.0.4/go.mod h1:5hac1em3uXoyC5ipZ0xFv9umNM/waQvYAQdr0cx/h34=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/dig v1.19.0 h1:BACLhebsYdpQ7IROQ1AGPjrXcP5dF80U3gKoFzbaq/4=
go.uber.org/dig v1.19.0/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE=
go.uber.org/fx v1.24.0 h1:wE8mruvpg2kiiL1Vqd0CC+tr0/24XIB10Iwp2lLWzkg=
go.uber.org/fx v1.24.0/go.mod h1:AmDeGyS+ZARGKM4tlH4FY2Jr63VjbEDJHtqXTGP5hbo=
github.com/yuin/gopher-lua v1.1.0 h1:BojcDhfyDWgU2f2TOzYK/g5p2gxMrku8oupLDqlnSqE=
github.com/yuin/gopher-lua v1.1.0/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/arch v0.24.0 h1:qlJ3M9upxvFfwRM51tTg3Yl+8CP9vCC1E7vlFpgv99Y=
golang.org/x/arch v0.24.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg=
golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201112155050-0c6587e931a9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio=
golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw=
golang.org/x/crypto v0.0.0-20220511200225-c6db032c6c88/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0=
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/image v0.16.0/go.mod h1:ugSZItdV4nOxyqp56HmXwH0Ry0nBCpjnZdpDaIHdoPs=
golang.org/x/image v0.36.0 h1:Iknbfm1afbgtwPTmHnS2gTM/6PPZfH+z2EFuOkSbqwc=
golang.org/x/image v0.36.0/go.mod h1:YsWD2TyyGKiIX1kZlu9QfKIsQ4nAAK9bdgdrIsE7xy4=
golang.org/x/image v0.33.0 h1:LXRZRnv1+zGd5XBUVRFmYEphyyKJjQjCRiOuAP3sZfQ=
golang.org/x/image v0.33.0/go.mod h1:DD3OsTYT9chzuzTQt+zMcOlBHgfoKQb1gry8p76Y1sc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.13.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA=
golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -360,82 +334,76 @@ golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220224120231-95c6836cb0e7/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o=
golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=
golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/mail.v2 v2.3.1 h1:WYFn/oANrAGP2C0dcV6/pbkPzv8yGzqTjPmTeO7qoXk=
gopkg.in/mail.v2 v2.3.1/go.mod h1:htwXN1Qh09vZJ1NVKxQqHPBaCBbzKhp5GzuJEA4VJWw=
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/datatypes v1.2.7 h1:ww9GAhF1aGXZY3EB3cJPJ7//JiuQo7DlQA7NNlVaTdk=
@@ -446,38 +414,18 @@ gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/driver/sqlserver v1.6.3 h1:UR+nWCuphPnq7UxnL57PSrlYjuvs+sf1N59GgFX7uAI=
gorm.io/driver/sqlserver v1.6.3/go.mod h1:VZeNn7hqX1aXoN5TPAFGWvxWG90xtA8erGn2gQmpc6U=
gorm.io/driver/sqlserver v1.6.0 h1:VZOBQVsVhkHU/NzNhRJKoANt5pZGQAS1Bwc6m6dgfnc=
gorm.io/driver/sqlserver v1.6.0/go.mod h1:WQzt4IJo/WHKnckU9jXBLMJIVNMVeTu25dnOzehntWw=
gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
gorm.io/plugin/dbresolver v1.6.2 h1:F4b85TenghUeITqe3+epPSUtHH7RIk3fXr5l83DF8Pc=
gorm.io/plugin/dbresolver v1.6.2/go.mod h1:tctw63jdrOezFR9HmrKnPkmig3m5Edem9fdxk9bQSzM=
modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/ccgo/v4 v4.30.2 h1:4yPaaq9dXYXZ2V8s1UgrC3KIj580l2N4ClrLwnbv2so=
modernc.org/ccgo/v4 v4.30.2/go.mod h1:yZMnhWEdW0qw3EtCndG1+ldRrVGS+bIwyWmAWzS0XEw=
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.68.0 h1:PJ5ikFOV5pwpW+VqCK1hKJuEWsonkIJhhIXyuF/91pQ=
modernc.org/libc v1.68.0/go.mod h1:NnKCYeoYgsEqnY3PgvNgAeaJnso968ygU8Z0DxjoEc0=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.46.1 h1:eFJ2ShBLIEnUWlLy12raN0Z1plqmFX9Qe3rjQTKt6sU=
modernc.org/sqlite v1.46.1/go.mod h1:CzbrU2lSB1DKUusvwGz7rqEKIq+NUd8GWuBBZDs9/nA=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
gorm.io/plugin/dbresolver v1.6.0 h1:XvKDeOtTn1EIX6s4SrKpEH82q0gXVemhYjbYZFGFVcw=
gorm.io/plugin/dbresolver v1.6.0/go.mod h1:tctw63jdrOezFR9HmrKnPkmig3m5Edem9fdxk9bQSzM=
modernc.org/libc v1.22.2 h1:4U7v51GyhlWqQmwCHj28Rdq2Yzwk55ovjFrdPjs8Hb0=
modernc.org/libc v1.22.2/go.mod h1:uvQavJ1pZ0hIoC/jfqNoMLURIMhKzINIWypNM17puug=
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
modernc.org/sqlite v1.20.3 h1:SqGJMMxjj1PHusLxdYxeQSodg7Jxn9WWkaAQjKrntZs=
modernc.org/sqlite v1.20.3/go.mod h1:zKcGyrICaxNTMEHSr1HQ2GUraP0j+845GYw37+EyT6A=

View File

@@ -1,138 +0,0 @@
package app
import (
"context"
"net/http"
"carrotskin/internal/container"
"carrotskin/internal/handler"
"carrotskin/internal/middleware"
"carrotskin/internal/task"
"carrotskin/pkg/auth"
"carrotskin/pkg/config"
"carrotskin/pkg/database"
"carrotskin/pkg/email"
"carrotskin/pkg/redis"
"carrotskin/pkg/storage"
"github.com/gin-gonic/gin"
"go.uber.org/fx"
"go.uber.org/zap"
"gorm.io/gorm"
)
// BootstrapModule 注册 Container、路由注册、HTTP 服务器与后台任务的生命周期。
//
// 设计说明:当前所有 Handler 仍依赖 *container.Container阶段6将逐步解耦为
// 直接依赖各 Service 接口)。本 Module 由 fx 注入基础设施,聚合为 Container
// 再用它注册路由、启动服务器与后台任务。当 fx.Run() 接收到 SIGINT/SIGTERM 时,
// 会按依赖逆序执行所有 OnStop 钩子,实现优雅关闭。
var BootstrapModule = fx.Options(
// Gin 路由引擎
fx.Provide(provideRouter),
// 由 fx 注入的基础设施聚合为 ContainerContainer 内部会构造 Repository/Service
fx.Provide(provideContainer),
// 数据库迁移与种子数据infra 就绪后执行)
fx.Invoke(runMigrate),
// 注册所有 HTTP 路由
fx.Invoke(registerRoutes),
// HTTP 服务器生命周期(启动/优雅关闭)
fx.Invoke(registerServerLifecycle),
// 后台任务调度器生命周期
fx.Invoke(registerTaskLifecycle),
)
// provideRouter 创建 Gin 引擎并挂载全局中间件。
func provideRouter(cfg *config.Config, logger *zap.Logger) *gin.Engine {
if cfg.Server.Mode == "production" {
gin.SetMode(gin.ReleaseMode)
}
router := gin.New()
// 禁用自动重定向允许API路径带或不带/结尾都能正常访问
router.RedirectTrailingSlash = false
router.RedirectFixedPath = false
router.Use(middleware.Logger(logger))
router.Use(middleware.Recovery(logger))
router.Use(middleware.CORS(cfg))
return router
}
// provideContainer 将所有 fx 管理的基础设施聚合为 Container。
// Container.NewContainer 内部会基于这些 infra 构造 Repository 与 Service。
// 注意email.Service 可能为 nil当 EMAIL_ENABLED=false 时Container 会降级处理。
func provideContainer(
cfg *config.Config,
db *gorm.DB,
redisClient *redis.Client,
logger *zap.Logger,
jwt *auth.JWTService,
casbin *auth.CasbinService,
storageClient *storage.StorageClient,
emailService *email.Service,
) *container.Container {
return container.NewContainer(
cfg, db, redisClient, logger, jwt, casbin, storageClient, emailService,
)
}
// runMigrate 执行数据库迁移与种子数据初始化。
func runMigrate(db *gorm.DB, logger *zap.Logger) error {
if err := database.AutoMigrateWithDB(db, logger); err != nil {
return err
}
return database.SeedWithDB(db, logger)
}
// registerRoutes 注册所有 HTTP 路由。
func registerRoutes(router *gin.Engine, c *container.Container) {
handler.RegisterRoutesWithDI(router, c)
}
// registerServerLifecycle 注册 HTTP 服务器的启动与优雅关闭。
func registerServerLifecycle(lc fx.Lifecycle, router *gin.Engine, cfg *config.Config, logger *zap.Logger) {
srv := &http.Server{
Addr: cfg.Server.Port,
Handler: router,
ReadTimeout: cfg.Server.ReadTimeout,
WriteTimeout: cfg.Server.WriteTimeout,
}
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
logger.Info("服务器启动", zap.String("port", cfg.Server.Port))
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Fatal("服务器启动失败", zap.Error(err))
}
}()
return nil
},
OnStop: func(ctx context.Context) error {
logger.Info("正在关闭服务器...")
return srv.Shutdown(ctx)
},
})
}
// registerTaskLifecycle 注册后台任务调度器的启动与停止。
func registerTaskLifecycle(lc fx.Lifecycle, logger *zap.Logger) {
runner := task.NewRunner(logger)
ctx, cancel := context.WithCancel(context.Background())
lc.Append(fx.Hook{
OnStart: func(_ context.Context) error {
runner.Start(ctx)
return nil
},
OnStop: func(_ context.Context) error {
cancel()
runner.Wait()
return nil
},
})
}

View File

@@ -1,8 +0,0 @@
package app
// HandlerModule 已在阶段4移除。
//
// 当前阶段Handler 仍由 internal/container.Container + handler.RegisterRoutesWithDI
// 构造与注册(见 container_module.go 的 registerRoutes
//
// TODO(阶段6): Handler 将改为直接依赖各 Service 接口,由 fx 直接 Provide 与注册。

View File

@@ -1,115 +0,0 @@
package app
import (
"context"
"carrotskin/pkg/auth"
"carrotskin/pkg/config"
"carrotskin/pkg/database"
"carrotskin/pkg/email"
"carrotskin/pkg/logger"
"carrotskin/pkg/redis"
"carrotskin/pkg/storage"
"go.uber.org/fx"
"go.uber.org/zap"
"gorm.io/gorm"
)
// InfraModule 注册所有基础设施依赖Logger/DB/Redis/Storage/Email/JWT/Casbin。
// 每个需要资源释放的组件都通过 fx.Lifecycle 注册 OnStop 钩子,
// 彻底替代 main.go 里分散的 defer xxx.Close()。
var InfraModule = fx.Options(
// 顶层 Config 子结构 Provider让 pkg/* 包的构造函数按值接收细分 Config
fx.Provide(func(c *config.Config) config.DatabaseConfig { return c.Database }),
fx.Provide(func(c *config.Config) config.RedisConfig { return c.Redis }),
fx.Provide(func(c *config.Config) config.RustFSConfig { return c.RustFS }),
fx.Provide(func(c *config.Config) config.LogConfig { return c.Log }),
fx.Provide(func(c *config.Config) config.EmailConfig { return c.Email }),
// Logger
fx.Provide(logger.New),
// Database: 同时暴露 *database.DB封装带连接池统计和 *gorm.DB裸 GORM
fx.Provide(provideDatabase),
// 暴露 *gorm.DB 供 Repository/Casbin 等消费
fx.Provide(func(d *database.DB) *gorm.DB { return d.DB }),
// Redis含 miniredis 测试回退)
fx.Provide(provideRedis),
// 对象存储S3 兼容)
fx.Provide(provideStorage),
// 邮件服务
fx.Provide(email.NewService),
// JWT 服务(应用层认证)
fx.Provide(func(cfg *config.Config) *auth.JWTService {
return auth.NewJWTService(cfg.JWT.Secret, cfg.JWT.ExpireHours)
}),
// Casbin 权限服务
fx.Provide(func(db *gorm.DB, cfg *config.Config, log *zap.Logger) (*auth.CasbinService, error) {
return auth.NewCasbinService(db, cfg.Casbin.ModelPath, log)
}),
)
// provideDatabase 创建数据库连接并注册关闭钩子。
func provideDatabase(cfg *config.Config, lc fx.Lifecycle, log *zap.Logger) (*database.DB, error) {
db, err := database.New(cfg.Database)
if err != nil {
return nil, err
}
lc.Append(fx.Hook{
OnStop: func(ctx context.Context) error {
log.Info("正在关闭数据库连接")
return db.Close()
},
})
return db, nil
}
// provideRedis 创建 Redis 客户端并注册关闭钩子。
// 开发/测试环境下若连接失败会自动回退到 miniredis。
func provideRedis(cfg *config.Config, lc fx.Lifecycle, log *zap.Logger) (*redis.Client, error) {
client, err := redis.New(cfg.Redis, log)
if err != nil {
// 检查是否允许回退到 miniredis仅开发/测试环境)
if redis.AllowFallbackToMiniRedis() {
log.Warn("Redis连接失败尝试使用miniredis回退", zap.Error(err))
client, err = redis.InitMiniRedis(log)
if err != nil {
return nil, err
}
log.Info("已回退到miniredis用于开发/测试环境")
} else {
return nil, err
}
}
lc.Append(fx.Hook{
OnStop: func(ctx context.Context) error {
log.Info("正在关闭 Redis 连接")
return client.Close()
},
})
return client, nil
}
// provideStorage 创建对象存储客户端并注册关闭钩子。
// 存储服务在配置缺失时可能是可选的,失败时返回 error 让调用方决定是否降级。
func provideStorage(cfg *config.Config, lc fx.Lifecycle, log *zap.Logger) (*storage.StorageClient, error) {
client, err := storage.NewStorage(cfg.RustFS)
if err != nil {
return nil, err
}
// MinIO 客户端无需显式 Close但保留钩子以备未来扩展
lc.Append(fx.Hook{
OnStop: func(ctx context.Context) error {
log.Info("对象存储客户端已停止")
return nil
},
})
return client, nil
}

View File

@@ -1,30 +0,0 @@
// Package app 提供 uber-go/fx 应用装配层。
//
// 该包用 fx 的 Provider/Lifecycle 取代了 pkg/*/manager.go 的全局单例和
// internal/container 的手动 DI是整个应用唯一的依赖装配入口。
//
// 使用方式:
//
// cfg, err := config.Load()
// if err != nil { log.Fatal(err) }
// fx.New(app.Module(cfg)).Run()
package app
import (
"carrotskin/pkg/config"
"go.uber.org/fx"
)
// Module 返回应用的根 fx.Option聚合所有子模块。
// cfg 通过 fx.Supply 注入,供各 Provider 消费其子配置结构。
//
// 当前阶段fx 管理 infra + Container 聚合 + 路由/服务器/任务生命周期。
// Container 内部构造 Repository 与 Service阶段6后将逐步解耦为 fx 直接管理 Service
func Module(cfg *config.Config) fx.Option {
return fx.Options(
fx.Supply(cfg),
InfraModule,
BootstrapModule,
)
}

View File

@@ -1,13 +0,0 @@
package app
// RepositoryModule 已在阶段4移除。
//
// 当前阶段Repository 由 internal/container.Container 内部构造。
//
// TODO(阶段6): Container 移除后Repository 将回到此 Module 由 fx 直接管理:
//
// var RepositoryModule = fx.Options(
// fx.Provide(repository.NewUserRepository),
// fx.Provide(repository.NewProfileRepository),
// ...
// )

View File

@@ -1,7 +0,0 @@
package app
// ServerModule 已在阶段4移除。
//
// 当前阶段HTTP 服务器生命周期由 container_module.go 的 registerServerLifecycle 管理。
//
// TODO(阶段6): 此处将作为独立 Module 重新启用。

View File

@@ -1,15 +0,0 @@
package app
// ServiceModule 已在阶段4移除。
//
// 当前阶段Service 由 internal/container.Container 内部构造Container 聚合了
// 所有 fx 注入的基础设施,在其 NewContainer 方法里创建 Repository 与 Service
//
// TODO(阶段6): 当 Handler 解耦为直接依赖各 Service 接口后Container 将被移除,
// 届时 Service 将回到此 Module 由 fx 直接管理:
//
// var ServiceModule = fx.Options(
// fx.Provide(service.NewUserService),
// fx.Provide(service.NewProfileService),
// ...
// )

View File

@@ -1,7 +0,0 @@
package app
// TaskModule 已在阶段4移除。
//
// 当前阶段,后台任务生命周期由 container_module.go 的 registerTaskLifecycle 管理。
//
// TODO(阶段6): 此处将作为独立 Module 重新启用。

View File

@@ -1,17 +1,14 @@
package container
import (
"context"
"time"
"carrotskin/internal/repository"
"carrotskin/internal/service"
"carrotskin/pkg/auth"
"carrotskin/pkg/config"
"carrotskin/pkg/database"
"carrotskin/pkg/email"
"carrotskin/pkg/redis"
"carrotskin/pkg/storage"
"time"
"go.uber.org/zap"
"gorm.io/gorm"
@@ -20,9 +17,6 @@ import (
// Container 依赖注入容器
// 集中管理所有依赖,便于测试和维护
type Container struct {
// 配置
Config *config.Config
// 基础设施依赖
DB *gorm.DB
Redis *redis.Client
@@ -33,13 +27,11 @@ type Container struct {
CacheManager *database.CacheManager
// Repository层
UserRepo repository.UserRepository
ProfileRepo repository.ProfileRepository
TextureRepo repository.TextureRepository
ClientRepo repository.ClientRepository
YggdrasilRepo repository.YggdrasilRepository
FriendRepo repository.FriendRepository
PlayerAttrRepo repository.PlayerAttributeRepository
UserRepo repository.UserRepository
ProfileRepo repository.ProfileRepository
TextureRepo repository.TextureRepository
ClientRepo repository.ClientRepository
YggdrasilRepo repository.YggdrasilRepository
// Service层
UserService service.UserService
@@ -47,22 +39,21 @@ type Container struct {
TextureService service.TextureService
TokenService service.TokenService
YggdrasilService service.YggdrasilService
FriendsService service.FriendsService
VerificationService service.VerificationService
SecurityService service.SecurityService
CaptchaService service.CaptchaService
SignatureService *service.SignatureService
}
// NewContainer 创建依赖容器
func NewContainer(
cfg *config.Config,
db *gorm.DB,
redisClient *redis.Client,
logger *zap.Logger,
jwtService *auth.JWTService,
casbinService *auth.CasbinService,
storageClient *storage.StorageClient,
emailService *email.Service,
emailService interface{}, // 接受 email.Service 但使用 interface{} 避免循环依赖
) *Container {
// 创建缓存管理器
cacheManager := database.NewCacheManager(redisClient, database.CacheConfig{
@@ -80,7 +71,6 @@ func NewContainer(
})
c := &Container{
Config: cfg,
DB: db,
Redis: redisClient,
Logger: logger,
@@ -96,25 +86,20 @@ func NewContainer(
c.TextureRepo = repository.NewTextureRepository(db)
c.ClientRepo = repository.NewClientRepository(db)
c.YggdrasilRepo = repository.NewYggdrasilRepository(db)
c.FriendRepo = repository.NewFriendRepository(db)
c.PlayerAttrRepo = repository.NewPlayerAttributeRepository(db)
// 初始化SignatureService作为依赖注入避免在容器中创建并立即调用
// 将SignatureService添加到容器中供其他服务使用
c.SignatureService = service.NewSignatureService(c.ProfileRepo, redisClient, logger)
// 初始化Service注入缓存管理器
c.UserService = service.NewUserService(cfg, c.UserRepo, jwtService, redisClient, cacheManager, storageClient, logger)
c.UserService = service.NewUserService(c.UserRepo, jwtService, redisClient, cacheManager, storageClient, logger)
c.ProfileService = service.NewProfileService(c.ProfileRepo, c.UserRepo, cacheManager, logger)
c.TextureService = service.NewTextureService(c.TextureRepo, c.UserRepo, storageClient, cacheManager, logger, db)
c.TextureService = service.NewTextureService(c.TextureRepo, c.UserRepo, storageClient, cacheManager, logger)
// 获取Yggdrasil私钥并创建JWT服务TokenService需要
// 注意这里仍然需要预先初始化因为TokenService在创建时需要YggdrasilJWT
// 但SignatureService已经作为依赖注入降低了耦合度
// 使用后台 ctx启动阶段不依赖请求 ctx
initCtx, cancelInit := context.WithTimeout(context.Background(), 30*time.Second)
_, privateKey, err := c.SignatureService.GetOrCreateYggdrasilKeyPair(initCtx)
cancelInit()
_, privateKey, err := c.SignatureService.GetOrCreateYggdrasilKeyPair()
if err != nil {
logger.Fatal("获取Yggdrasil私钥失败", zap.Error(err))
}
@@ -136,18 +121,149 @@ func NewContainer(
c.TokenService = service.NewTokenServiceRedis(tokenStore, c.ClientRepo, c.ProfileRepo, yggdrasilJWT, logger)
// 使用组合服务(内部包含认证、会话、序列化、证书服务)
c.YggdrasilService = service.NewYggdrasilServiceComposite(c.UserRepo, c.ProfileRepo, c.YggdrasilRepo, c.TextureRepo, c.SignatureService, redisClient, logger, c.TokenService)
// 好友系统服务(依赖 Profile/Redis
c.FriendsService = service.NewFriendsService(c.FriendRepo, c.PlayerAttrRepo, c.ProfileRepo, redisClient, logger)
c.YggdrasilService = service.NewYggdrasilServiceComposite(db, c.UserRepo, c.ProfileRepo, c.YggdrasilRepo, c.SignatureService, redisClient, logger, c.TokenService)
// 初始化其他服务
c.CaptchaService = service.NewCaptchaService(cfg, redisClient, logger)
c.SecurityService = service.NewSecurityService(redisClient)
c.CaptchaService = service.NewCaptchaService(redisClient, logger)
// 初始化VerificationService需要email.Service
if emailService != nil {
c.VerificationService = service.NewVerificationService(cfg, redisClient, emailService)
if emailSvc, ok := emailService.(*email.Service); ok {
c.VerificationService = service.NewVerificationService(redisClient, emailSvc)
}
}
return c
}
// NewTestContainer 创建测试用容器可注入mock依赖
func NewTestContainer(opts ...Option) *Container {
c := &Container{}
for _, opt := range opts {
opt(c)
}
return c
}
// Option 容器配置选项
type Option func(*Container)
// WithDB 设置数据库连接
func WithDB(db *gorm.DB) Option {
return func(c *Container) {
c.DB = db
}
}
// WithRedis 设置Redis客户端
func WithRedis(redis *redis.Client) Option {
return func(c *Container) {
c.Redis = redis
}
}
// WithLogger 设置日志
func WithLogger(logger *zap.Logger) Option {
return func(c *Container) {
c.Logger = logger
}
}
// WithJWT 设置JWT服务
func WithJWT(jwt *auth.JWTService) Option {
return func(c *Container) {
c.JWT = jwt
}
}
// WithStorage 设置存储客户端
func WithStorage(storage *storage.StorageClient) Option {
return func(c *Container) {
c.Storage = storage
}
}
// WithUserRepo 设置用户仓储
func WithUserRepo(repo repository.UserRepository) Option {
return func(c *Container) {
c.UserRepo = repo
}
}
// WithProfileRepo 设置档案仓储
func WithProfileRepo(repo repository.ProfileRepository) Option {
return func(c *Container) {
c.ProfileRepo = repo
}
}
// WithTextureRepo 设置材质仓储
func WithTextureRepo(repo repository.TextureRepository) Option {
return func(c *Container) {
c.TextureRepo = repo
}
}
// WithUserService 设置用户服务
func WithUserService(svc service.UserService) Option {
return func(c *Container) {
c.UserService = svc
}
}
// WithProfileService 设置档案服务
func WithProfileService(svc service.ProfileService) Option {
return func(c *Container) {
c.ProfileService = svc
}
}
// WithTextureService 设置材质服务
func WithTextureService(svc service.TextureService) Option {
return func(c *Container) {
c.TextureService = svc
}
}
// WithTokenService 设置令牌服务
func WithTokenService(svc service.TokenService) Option {
return func(c *Container) {
c.TokenService = svc
}
}
// WithYggdrasilRepo 设置Yggdrasil仓储
func WithYggdrasilRepo(repo repository.YggdrasilRepository) Option {
return func(c *Container) {
c.YggdrasilRepo = repo
}
}
// WithYggdrasilService 设置Yggdrasil服务
func WithYggdrasilService(svc service.YggdrasilService) Option {
return func(c *Container) {
c.YggdrasilService = svc
}
}
// WithVerificationService 设置验证码服务
func WithVerificationService(svc service.VerificationService) Option {
return func(c *Container) {
c.VerificationService = svc
}
}
// WithSecurityService 设置安全服务
func WithSecurityService(svc service.SecurityService) Option {
return func(c *Container) {
c.SecurityService = svc
}
}
// WithCaptchaService 设置验证码服务
func WithCaptchaService(svc service.CaptchaService) Option {
return func(c *Container) {
c.CaptchaService = svc
}
}

View File

@@ -12,12 +12,14 @@ var (
ErrUserNotFound = errors.New("用户不存在")
ErrUserAlreadyExists = errors.New("用户已存在")
ErrEmailAlreadyExists = errors.New("邮箱已被注册")
ErrInvalidPassword = errors.New("密码错误")
ErrAccountDisabled = errors.New("账号已被禁用")
// 认证相关错误
ErrUnauthorized = errors.New("未授权")
ErrInvalidToken = errors.New("无效的令牌")
ErrTokenExpired = errors.New("令牌已过期")
ErrUnauthorized = errors.New("未授权")
ErrInvalidToken = errors.New("无效的令牌")
ErrTokenExpired = errors.New("令牌已过期")
ErrInvalidSignature = errors.New("签名验证失败")
// 档案相关错误
ErrProfileNotFound = errors.New("档案不存在")
@@ -30,6 +32,7 @@ var (
ErrTextureExists = errors.New("该材质已存在")
ErrTextureLimitReached = errors.New("已达材质数量上限")
ErrTextureNoPermission = errors.New("无权操作此材质")
ErrInvalidTextureType = errors.New("无效的材质类型")
// 验证码相关错误
ErrInvalidVerificationCode = errors.New("验证码错误或已过期")
@@ -51,11 +54,11 @@ var (
ErrSessionNotFound = errors.New("会话不存在或已过期")
ErrSessionMismatch = errors.New("会话验证失败")
ErrUsernameMismatch = errors.New("用户名不匹配")
ErrUsernameRequired = errors.New("用户名不能为空")
ErrIPMismatch = errors.New("IP地址不匹配")
ErrInvalidAccessToken = errors.New("访问令牌无效")
ErrProfileMismatch = errors.New("selectedProfile与Token不匹配")
ErrUUIDRequired = errors.New("UUID不能为空")
ErrCertificateGenerate = errors.New("生成证书失败")
// 通用错误
ErrBadRequest = errors.New("请求参数错误")
@@ -118,69 +121,20 @@ func NewInternalError(message string, err error) *AppError {
return NewAppError(500, message, err)
}
// 注意:原此处的 Is/As/Wrap 函数(透传标准库)已删除。
// 请直接使用标准库 errors.Is / errors.As / fmt.Errorf。
// YggdrasilErrorResponse Yggdrasil协议标准错误响应格式
type YggdrasilErrorResponse struct {
Error string `json:"error"` // 错误的简要描述(机器可读)
ErrorMessage string `json:"errorMessage"` // 错误的详细信息(人类可读)
Cause string `json:"cause,omitempty"` // 该错误的原因(可选)
// Is 检查错误是否匹配
func Is(err, target error) bool {
return errors.Is(err, target)
}
// NewYggdrasilErrorResponse 创建Yggdrasil标准错误响应
func NewYggdrasilErrorResponse(error, errorMessage, cause string) *YggdrasilErrorResponse {
return &YggdrasilErrorResponse{
Error: error,
ErrorMessage: errorMessage,
Cause: cause,
}
}
// YggdrasilErrorCodes Yggdrasil协议错误码常量
const (
// ForbiddenOperationException 错误消息
YggErrInvalidToken = "Invalid token."
YggErrInvalidCredentials = "Invalid credentials. Invalid username or password."
// IllegalArgumentException 错误消息
YggErrProfileAlreadyAssigned = "Access token already has a profile assigned."
)
// FriendsErrorStatus MinecraftServices 好友系接口业务错误码(文档 1.3.4
const (
FriendsErrUnknownProfile = "UNKNOWN_PROFILE"
FriendsErrCannotAddSelf = "CANNOT_ADD_SELF"
FriendsErrDuplicatedProfiles = "DUPLICATED_PROFILES"
)
// FriendsErrorResultCode MinecraftServices 好友系接口结果码(文档 4
const (
FriendsResultSuccess = "SUCCESS"
FriendsResultError = "ERROR"
FriendsResultServiceUnavailable = "SERVICE_NOT_AVAILABLE"
FriendsResultTooManyRequests = "TOO_MANY_REQUESTS"
FriendsResultForbidden = "FORBIDDEN"
FriendsResultUnknownProfile = "UNKNOWN_PROFILE"
FriendsResultUnauthorized = "UNAUTHORIZED"
)
// MinecraftServicesErrorResponse MinecraftServices 系接口标准错误响应(文档 0.3
// 与 YggdrasilErrorResponse 不同,本体系按 MinecraftServices 的结构返回:
// { "path": "...", "error": "...", "errorMessage": "...", "details": {} }
type MinecraftServicesErrorResponse struct {
Path string `json:"path"`
Error string `json:"error"` // 机器可读错误码
ErrorMessage string `json:"errorMessage"` // 人类可读描述
Details interface{} `json:"details,omitempty"` // 错误特定细节
}
// NewMinecraftServicesErrorResponse 创建 MinecraftServices 系标准错误响应
func NewMinecraftServicesErrorResponse(path, errorCode, errorMessage string, details interface{}) *MinecraftServicesErrorResponse {
return &MinecraftServicesErrorResponse{
Path: path,
Error: errorCode,
ErrorMessage: errorMessage,
Details: details,
// As 尝试将错误转换为指定类型
func As(err error, target interface{}) bool {
return errors.As(err, target)
}
// Wrap 包装错误
func Wrap(err error, message string) error {
if err == nil {
return nil
}
return fmt.Errorf("%s: %w", message, err)
}

View File

@@ -15,12 +15,24 @@ func TestAppErrorBasics(t *testing.T) {
if got := appErr.Error(); got != "bad: root" {
t.Fatalf("unexpected Error(): %s", got)
}
// 使用标准库 errors.Is/As包级 Is/As 已移除)
if !errors.Is(appErr, root) {
if !Is(appErr, root) {
t.Fatalf("Is should match wrapped error")
}
var target *AppError
if !errors.As(appErr, &target) {
if !As(appErr, &target) {
t.Fatalf("As should succeed")
}
}
func TestWrap(t *testing.T) {
if Wrap(nil, "msg") != nil {
t.Fatalf("Wrap nil should return nil")
}
err := errors.New("base")
wrapped := Wrap(err, "ctx")
if wrapped.Error() != "ctx: base" {
t.Fatalf("wrap message mismatch: %v", wrapped)
}
}

View File

@@ -1,12 +1,10 @@
package handler
import (
"errors"
"net/http"
"strconv"
"carrotskin/internal/container"
apperrors "carrotskin/internal/errors"
"carrotskin/internal/model"
"github.com/gin-gonic/gin"
@@ -48,16 +46,11 @@ func (h *AdminHandler) SetUserRole(c *gin.Context) {
return
}
// 获取当前操作者ID(安全类型断言,防止中间件异常时 panic
operatorIDVal, _ := c.Get("user_id")
operatorID, ok := operatorIDVal.(int64)
if !ok {
RespondServerError(c, "操作者ID类型错误", nil)
return
}
// 获取当前操作者ID
operatorID, _ := c.Get("user_id")
// 不能修改自己的角色
if req.UserID == operatorID {
if req.UserID == operatorID.(int64) {
c.JSON(http.StatusBadRequest, model.NewErrorResponse(
model.CodeBadRequest,
"不能修改自己的角色",
@@ -66,13 +59,9 @@ func (h *AdminHandler) SetUserRole(c *gin.Context) {
return
}
// 检查目标用户是否存在(区分 DB 错误与"用户不存在"
targetUser, err := h.container.UserService.GetByID(c.Request.Context(), req.UserID)
if err != nil {
RespondServerError(c, "查询用户失败", err)
return
}
if targetUser == nil {
// 检查目标用户是否存在
targetUser, err := h.container.UserRepo.FindByID(c.Request.Context(), req.UserID)
if err != nil || targetUser == nil {
c.JSON(http.StatusNotFound, model.NewErrorResponse(
model.CodeNotFound,
"用户不存在",
@@ -82,13 +71,16 @@ func (h *AdminHandler) SetUserRole(c *gin.Context) {
}
// 更新用户角色
if err := h.container.UserService.SetRole(c.Request.Context(), req.UserID, req.Role); err != nil {
err = h.container.UserRepo.UpdateFields(c.Request.Context(), req.UserID, map[string]interface{}{
"role": req.Role,
})
if err != nil {
RespondServerError(c, "更新用户角色失败", err)
return
}
h.container.Logger.Info("管理员修改用户角色",
zap.Int64("operator_id", operatorID),
zap.Int64("operator_id", operatorID.(int64)),
zap.Int64("target_user_id", req.UserID),
zap.String("new_role", req.Role),
)
@@ -122,12 +114,13 @@ func (h *AdminHandler) GetUserList(c *gin.Context) {
pageSize = 20
}
// 通过 Service 层查询用户列表
users, total, err := h.container.UserService.ListUsers(c.Request.Context(), page, pageSize)
if err != nil {
RespondServerError(c, "获取用户列表失败", err)
return
}
// 使用数据库直接查询用户列表
var users []model.User
var total int64
db := h.container.DB
db.Model(&model.User{}).Count(&total)
db.Offset((page - 1) * pageSize).Limit(pageSize).Order("id DESC").Find(&users)
// 构建响应(隐藏敏感信息)
userList := make([]gin.H, len(users))
@@ -170,7 +163,7 @@ func (h *AdminHandler) GetUserDetail(c *gin.Context) {
return
}
user, err := h.container.UserService.GetByID(c.Request.Context(), userID)
user, err := h.container.UserRepo.FindByID(c.Request.Context(), userID)
if err != nil || user == nil {
c.JSON(http.StatusNotFound, model.NewErrorResponse(
model.CodeNotFound,
@@ -219,15 +212,10 @@ func (h *AdminHandler) SetUserStatus(c *gin.Context) {
return
}
operatorIDVal, _ := c.Get("user_id")
operatorID, ok := operatorIDVal.(int64)
if !ok {
RespondServerError(c, "操作者ID类型错误", nil)
return
}
operatorID, _ := c.Get("user_id")
// 不能修改自己的状态
if req.UserID == operatorID {
if req.UserID == operatorID.(int64) {
c.JSON(http.StatusBadRequest, model.NewErrorResponse(
model.CodeBadRequest,
"不能修改自己的状态",
@@ -236,13 +224,9 @@ func (h *AdminHandler) SetUserStatus(c *gin.Context) {
return
}
// 检查目标用户是否存在(区分 DB 错误与"用户不存在"
targetUser, err := h.container.UserService.GetByID(c.Request.Context(), req.UserID)
if err != nil {
RespondServerError(c, "查询用户失败", err)
return
}
if targetUser == nil {
// 检查目标用户是否存在
targetUser, err := h.container.UserRepo.FindByID(c.Request.Context(), req.UserID)
if err != nil || targetUser == nil {
c.JSON(http.StatusNotFound, model.NewErrorResponse(
model.CodeNotFound,
"用户不存在",
@@ -252,7 +236,10 @@ func (h *AdminHandler) SetUserStatus(c *gin.Context) {
}
// 更新用户状态
if err := h.container.UserService.SetStatus(c.Request.Context(), req.UserID, req.Status); err != nil {
err = h.container.UserRepo.UpdateFields(c.Request.Context(), req.UserID, map[string]interface{}{
"status": req.Status,
})
if err != nil {
RespondServerError(c, "更新用户状态失败", err)
return
}
@@ -260,7 +247,7 @@ func (h *AdminHandler) SetUserStatus(c *gin.Context) {
statusText := map[int16]string{1: "正常", 0: "禁用", -1: "删除"}[req.Status]
h.container.Logger.Info("管理员修改用户状态",
zap.Int64("operator_id", operatorID),
zap.Int64("operator_id", operatorID.(int64)),
zap.Int64("target_user_id", req.UserID),
zap.Int16("new_status", req.Status),
)
@@ -290,30 +277,30 @@ func (h *AdminHandler) DeleteTexture(c *gin.Context) {
return
}
operatorIDVal, _ := c.Get("user_id")
operatorID, ok := operatorIDVal.(int64)
if !ok {
RespondServerError(c, "操作者ID类型错误", nil)
operatorID, _ := c.Get("user_id")
// 检查材质是否存在
var texture model.Texture
if err := h.container.DB.First(&texture, textureID).Error; err != nil {
c.JSON(http.StatusNotFound, model.NewErrorResponse(
model.CodeNotFound,
"材质不存在",
nil,
))
return
}
// 通过 Service 删除材质Service 会检查存在性)
if err := h.container.TextureService.AdminDelete(c.Request.Context(), textureID); err != nil {
if errors.Is(err, apperrors.ErrTextureNotFound) {
c.JSON(http.StatusNotFound, model.NewErrorResponse(
model.CodeNotFound,
"材质不存在",
nil,
))
return
}
// 删除材质
if err := h.container.DB.Delete(&texture).Error; err != nil {
RespondServerError(c, "删除材质失败", err)
return
}
h.container.Logger.Info("管理员删除材质",
zap.Int64("operator_id", operatorID),
zap.Int64("operator_id", operatorID.(int64)),
zap.Int64("texture_id", textureID),
zap.Int64("uploader_id", texture.UploaderID),
zap.String("texture_name", texture.Name),
)
c.JSON(http.StatusOK, model.NewSuccessResponse(gin.H{
@@ -343,12 +330,12 @@ func (h *AdminHandler) GetTextureList(c *gin.Context) {
pageSize = 20
}
// 通过 Service 层查询材质列表
textures, total, err := h.container.TextureService.ListForAdmin(c.Request.Context(), page, pageSize)
if err != nil {
RespondServerError(c, "获取材质列表失败", err)
return
}
var textures []model.Texture
var total int64
db := h.container.DB
db.Model(&model.Texture{}).Count(&total)
db.Preload("Uploader").Offset((page - 1) * pageSize).Limit(pageSize).Order("id DESC").Find(&textures)
// 构建响应
textureList := make([]gin.H, len(textures))

View File

@@ -4,6 +4,7 @@ import (
"carrotskin/internal/container"
"carrotskin/internal/service"
"carrotskin/internal/types"
"carrotskin/pkg/email"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
@@ -40,23 +41,9 @@ func (h *AuthHandler) Register(c *gin.Context) {
return
}
// 验证滑动验证码(检查是否已验证)
if ok, err := h.container.CaptchaService.CheckVerified(c.Request.Context(), req.CaptchaID); err != nil || !ok {
h.logger.Warn("滑动验证码验证失败", zap.String("captcha_id", req.CaptchaID), zap.Error(err))
RespondBadRequest(c, "滑动验证码验证失败", nil)
return
}
// 使用 defer 确保验证码在函数返回前被消耗(不管成功还是失败)
defer func() {
if err := h.container.CaptchaService.ConsumeVerified(c.Request.Context(), req.CaptchaID); err != nil {
h.logger.Warn("消耗验证码失败", zap.String("captcha_id", req.CaptchaID), zap.Error(err))
}
}()
// 验证邮箱验证码
if err := h.container.VerificationService.VerifyCode(c.Request.Context(), req.Email, req.VerificationCode, service.VerificationTypeRegister); err != nil {
h.logger.Warn("邮箱验证码验证失败", zap.String("email", req.Email), zap.Error(err))
h.logger.Warn("验证码验证失败", zap.String("email", req.Email), zap.Error(err))
RespondBadRequest(c, err.Error(), nil)
return
}
@@ -176,3 +163,8 @@ func (h *AuthHandler) ResetPassword(c *gin.Context) {
RespondSuccess(c, gin.H{"message": "密码重置成功"})
}
// getEmailService 获取邮件服务(暂时使用全局方式,后续可改为依赖注入)
func (h *AuthHandler) getEmailService() (*email.Service, error) {
return email.GetService()
}

View File

@@ -1,9 +1,8 @@
package handler
import (
"net/http"
"carrotskin/internal/container"
"net/http"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
@@ -35,7 +34,7 @@ type CaptchaVerifyRequest struct {
// @Tags captcha
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "生成成功 {code: 200, message: string, data: {masterImage, tileImage, captchaId, y}}"
// @Success 200 {object} map[string]interface{} "生成成功 {code: 200, data: {masterImage, tileImage, captchaId, y}}"
// @Failure 500 {object} map[string]interface{} "生成失败"
// @Router /api/v1/captcha/generate [get]
func (h *CaptchaHandler) Generate(c *gin.Context) {
@@ -43,15 +42,14 @@ func (h *CaptchaHandler) Generate(c *gin.Context) {
if err != nil {
h.logger.Error("生成验证码失败", zap.Error(err))
c.JSON(http.StatusInternalServerError, gin.H{
"code": 500,
"message": "生成验证码失败",
"code": 500,
"msg": "生成验证码失败",
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": 200,
"message": "操作成功",
"code": 200,
"data": gin.H{
"masterImage": masterImg,
"tileImage": tileImg,
@@ -68,15 +66,15 @@ func (h *CaptchaHandler) Generate(c *gin.Context) {
// @Accept json
// @Produce json
// @Param request body CaptchaVerifyRequest true "验证请求"
// @Success 200 {object} map[string]interface{} "验证结果 {code: 200/400, message: string}"
// @Success 200 {object} map[string]interface{} "验证结果 {code: 200/400, msg: string}"
// @Failure 400 {object} map[string]interface{} "参数错误"
// @Router /api/v1/captcha/verify [post]
func (h *CaptchaHandler) Verify(c *gin.Context) {
var req CaptchaVerifyRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "参数错误: " + err.Error(),
"code": 400,
"msg": "参数错误: " + err.Error(),
})
return
}
@@ -88,21 +86,21 @@ func (h *CaptchaHandler) Verify(c *gin.Context) {
zap.Error(err),
)
c.JSON(http.StatusInternalServerError, gin.H{
"code": 500,
"message": "验证失败",
"code": 500,
"msg": "验证失败",
})
return
}
if valid {
c.JSON(http.StatusOK, gin.H{
"code": 200,
"message": "验证成功",
"code": 200,
"msg": "验证成功",
})
} else {
c.JSON(http.StatusOK, gin.H{
"code": 400,
"message": "验证失败,请重试",
"code": 400,
"msg": "验证失败,请重试",
})
}
}

View File

@@ -1,14 +1,12 @@
package handler
import (
"context"
"carrotskin/internal/container"
"fmt"
"net/http"
"strings"
"time"
"carrotskin/internal/container"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
@@ -235,12 +233,9 @@ func (h *CustomSkinHandler) GetTexture(c *gin.Context) {
}
}
// 增加下载计数(异步,使用独立 ctx 避免请求取消时丢失计数
// 增加下载计数(异步)
go func() {
// 复制 ctx 但不传播取消,配合超时防止 Redis 永久阻塞
asyncCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
_ = h.container.TextureService.IncrementDownload(asyncCtx, texture.ID)
_ = h.container.TextureRepo.IncrementDownloadCount(ctx, texture.ID)
}()
// 流式传输文件内容

View File

@@ -1,14 +1,11 @@
package handler
import (
"errors"
"net/http"
"strconv"
"strings"
apperrors "carrotskin/internal/errors"
"carrotskin/internal/errors"
"carrotskin/internal/model"
"carrotskin/internal/types"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
@@ -22,33 +19,6 @@ func parseIntWithDefault(s string, defaultVal int) int {
return val
}
// extractBearerToken 从 Authorization 头解析 Bearer token
// 返回值: token, ok (ok=false 时已写入 401 错误响应)
func extractBearerToken(c *gin.Context) (string, bool) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, apperrors.NewMinecraftServicesErrorResponse(
c.Request.URL.Path, "UNAUTHORIZED", "Authorization header not provided", nil,
))
return "", false
}
const bearerPrefix = "Bearer "
if !strings.HasPrefix(authHeader, bearerPrefix) {
c.JSON(http.StatusUnauthorized, apperrors.NewMinecraftServicesErrorResponse(
c.Request.URL.Path, "UNAUTHORIZED", "Invalid Authorization format", nil,
))
return "", false
}
token := strings.TrimPrefix(authHeader, bearerPrefix)
if token == "" {
c.JSON(http.StatusUnauthorized, apperrors.NewMinecraftServicesErrorResponse(
c.Request.URL.Path, "UNAUTHORIZED", "Invalid Authorization format", nil,
))
return "", false
}
return token, true
}
// GetUserIDFromContext 从上下文获取用户ID如果不存在返回未授权响应
// 返回值: userID, ok (如果ok为false已经发送了错误响应)
func GetUserIDFromContext(c *gin.Context) (int64, bool) {
@@ -220,31 +190,31 @@ func RespondWithError(c *gin.Context, err error) {
return
}
// 使用标准库 errors.Is 检查预定义错误
if errors.Is(err, apperrors.ErrUserNotFound) ||
errors.Is(err, apperrors.ErrProfileNotFound) ||
errors.Is(err, apperrors.ErrTextureNotFound) ||
errors.Is(err, apperrors.ErrNotFound) {
// 使用errors.Is检查预定义错误
if errors.Is(err, errors.ErrUserNotFound) ||
errors.Is(err, errors.ErrProfileNotFound) ||
errors.Is(err, errors.ErrTextureNotFound) ||
errors.Is(err, errors.ErrNotFound) {
RespondNotFound(c, err.Error())
return
}
if errors.Is(err, apperrors.ErrProfileNoPermission) ||
errors.Is(err, apperrors.ErrTextureNoPermission) ||
errors.Is(err, apperrors.ErrForbidden) {
if errors.Is(err, errors.ErrProfileNoPermission) ||
errors.Is(err, errors.ErrTextureNoPermission) ||
errors.Is(err, errors.ErrForbidden) {
RespondForbidden(c, err.Error())
return
}
if errors.Is(err, apperrors.ErrUnauthorized) ||
errors.Is(err, apperrors.ErrInvalidToken) ||
errors.Is(err, apperrors.ErrTokenExpired) {
if errors.Is(err, errors.ErrUnauthorized) ||
errors.Is(err, errors.ErrInvalidToken) ||
errors.Is(err, errors.ErrTokenExpired) {
RespondUnauthorized(c, err.Error())
return
}
// 检查AppError类型
var appErr *apperrors.AppError
var appErr *errors.AppError
if errors.As(err, &appErr) {
c.JSON(appErr.Code, model.NewErrorResponse(
appErr.Code,

View File

@@ -4,6 +4,7 @@ import (
"carrotskin/internal/container"
"carrotskin/internal/middleware"
"carrotskin/pkg/auth"
"carrotskin/pkg/config"
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
@@ -18,7 +19,6 @@ type Handlers struct {
Profile *ProfileHandler
Captcha *CaptchaHandler
Yggdrasil *YggdrasilHandler
Friends *YggdrasilFriendsHandler
CustomSkin *CustomSkinHandler
Admin *AdminHandler
}
@@ -32,7 +32,6 @@ func NewHandlers(c *container.Container) *Handlers {
Profile: NewProfileHandler(c),
Captcha: NewCaptchaHandler(c),
Yggdrasil: NewYggdrasilHandler(c),
Friends: NewYggdrasilFriendsHandler(c),
CustomSkin: NewCustomSkinHandler(c),
Admin: NewAdminHandler(c),
}
@@ -41,10 +40,11 @@ func NewHandlers(c *container.Container) *Handlers {
// RegisterRoutesWithDI 使用依赖注入注册所有路由
func RegisterRoutesWithDI(router *gin.Engine, c *container.Container) {
// 健康检查路由
router.GET("/health", NewHealthCheck(c.DB, c.Redis))
router.GET("/health", HealthCheck)
// Swagger文档路由
if c.Config != nil && c.Config.Server.SwaggerEnabled {
cfg, _ := config.GetConfig()
if cfg != nil && cfg.Server.SwaggerEnabled {
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
}
@@ -52,8 +52,7 @@ func RegisterRoutesWithDI(router *gin.Engine, c *container.Container) {
h := NewHandlers(c)
// API路由组
apiGroup := router.Group("/api")
v1 := apiGroup.Group("/v1")
v1 := router.Group("/api/v1")
{
// 认证路由无需JWT
registerAuthRoutes(v1, h.Auth)
@@ -70,16 +69,15 @@ func RegisterRoutesWithDI(router *gin.Engine, c *container.Container) {
// 验证码路由
registerCaptchaRoutesWithDI(v1, h.Captcha)
// Yggdrasil API路由组
registerYggdrasilRoutesWithDI(v1, h.Yggdrasil)
// CustomSkinAPI 路由
registerCustomSkinRoutes(v1, h.CustomSkin)
// 管理员路由(需要管理员权限)
registerAdminRoutes(v1, c, h.Admin)
}
// Yggdrasil API路由组独立于v1路径为 /api/yggdrasil
registerYggdrasilRoutesWithDI(apiGroup, h)
}
// registerAuthRoutes 注册认证路由
@@ -171,45 +169,29 @@ func registerCaptchaRoutesWithDI(v1 *gin.RouterGroup, h *CaptchaHandler) {
}
// registerYggdrasilRoutesWithDI 注册Yggdrasil API路由依赖注入版本
func registerYggdrasilRoutesWithDI(v1 *gin.RouterGroup, h *Handlers) {
func registerYggdrasilRoutesWithDI(v1 *gin.RouterGroup, h *YggdrasilHandler) {
ygg := v1.Group("/yggdrasil")
{
ygg.GET("", h.Yggdrasil.GetMetaData)
ygg.POST("/minecraftservices/player/certificates", h.Yggdrasil.GetPlayerCertificates)
// MinecraftServices 好友系接口(文档 1.1~1.3、1.6
mcServices := ygg.Group("/minecraftservices")
{
mcServices.GET("/friends", h.Friends.GetFriends)
mcServices.PUT("/friends", h.Friends.UpdateFriends)
mcServices.GET("/player/attributes", h.Friends.GetAttributes)
mcServices.POST("/player/attributes", h.Friends.UpdateAttributes)
mcServices.POST("/presence", h.Friends.UpdatePresence)
mcServices.GET("/privacy/blocklist", h.Friends.GetBlocklist)
// MC 1.21.7 /whitelist add 查询单用户名 UUIDauthlib-injector issue #277
mcServices.GET("/minecraft/profile/lookup/name/:name", h.Yggdrasil.LookupProfileByName)
}
ygg.GET("", h.GetMetaData)
ygg.POST("/minecraftservices/player/certificates", h.GetPlayerCertificates)
authserver := ygg.Group("/authserver")
{
authserver.POST("/authenticate", h.Yggdrasil.Authenticate)
authserver.POST("/validate", h.Yggdrasil.ValidToken)
authserver.POST("/refresh", h.Yggdrasil.RefreshToken)
authserver.POST("/invalidate", h.Yggdrasil.InvalidToken)
authserver.POST("/signout", h.Yggdrasil.SignOut)
authserver.POST("/authenticate", h.Authenticate)
authserver.POST("/validate", h.ValidToken)
authserver.POST("/refresh", h.RefreshToken)
authserver.POST("/invalidate", h.InvalidToken)
authserver.POST("/signout", h.SignOut)
}
sessionServer := ygg.Group("/sessionserver")
{
sessionServer.GET("/session/minecraft/profile/:uuid", h.Yggdrasil.GetProfileByUUID)
sessionServer.POST("/session/minecraft/join", h.Yggdrasil.JoinServer)
sessionServer.GET("/session/minecraft/hasJoined", h.Yggdrasil.HasJoinedServer)
sessionServer.GET("/session/minecraft/profile/:uuid", h.GetProfileByUUID)
sessionServer.POST("/session/minecraft/join", h.JoinServer)
sessionServer.GET("/session/minecraft/hasJoined", h.HasJoinedServer)
}
api := ygg.Group("/api")
profiles := api.Group("/profiles")
{
// 对应官方 api.mojang.com/profiles/minecraft文档 2.1:批量按用户名查档)
api.POST("/profiles/minecraft", h.Yggdrasil.GetProfilesByName)
// 对应官方 api.mojang.com/users/profiles/minecraft/{name}(文档 2.2:单个用户名查档)
api.GET("/users/profiles/minecraft/:name", h.Yggdrasil.GetProfileByName)
profiles.POST("/minecraft", h.GetProfilesByName)
}
}
}

View File

@@ -6,57 +6,57 @@ import (
"net/http"
"time"
"carrotskin/pkg/database"
"carrotskin/pkg/redis"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// NewHealthCheck 构造健康检查 handler依赖通过参数注入。
func NewHealthCheck(db *gorm.DB, redisClient *redis.Client) gin.HandlerFunc {
return func(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()
// HealthCheck 健康检查,检查依赖服务状态
func HealthCheck(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()
checks := make(map[string]string)
status := "ok"
checks := make(map[string]string)
status := "ok"
// 检查数据库
if err := checkDatabase(ctx, db); err != nil {
checks["database"] = "unhealthy: " + err.Error()
status = "degraded"
} else {
checks["database"] = "healthy"
}
// 检查Redis
if err := checkRedis(ctx, redisClient); err != nil {
checks["redis"] = "unhealthy: " + err.Error()
status = "degraded"
} else {
checks["redis"] = "healthy"
}
// 根据状态返回相应的HTTP状态码
httpStatus := http.StatusOK
if status == "degraded" {
httpStatus = http.StatusServiceUnavailable
}
c.JSON(httpStatus, gin.H{
"status": status,
"message": "CarrotSkin API health check",
"checks": checks,
"timestamp": time.Now().Unix(),
})
// 检查数据库
if err := checkDatabase(ctx); err != nil {
checks["database"] = "unhealthy: " + err.Error()
status = "degraded"
} else {
checks["database"] = "healthy"
}
// 检查Redis
if err := checkRedis(ctx); err != nil {
checks["redis"] = "unhealthy: " + err.Error()
status = "degraded"
} else {
checks["redis"] = "healthy"
}
// 根据状态返回相应的HTTP状态码
httpStatus := http.StatusOK
if status == "degraded" {
httpStatus = http.StatusServiceUnavailable
}
c.JSON(httpStatus, gin.H{
"status": status,
"message": "CarrotSkin API health check",
"checks": checks,
"timestamp": time.Now().Unix(),
})
}
// checkDatabase 检查数据库连接
func checkDatabase(ctx context.Context, db *gorm.DB) error {
if db == nil {
return errors.New("数据库未初始化")
func checkDatabase(ctx context.Context) error {
db, err := database.GetDB()
if err != nil {
return err
}
sqlDB, err := db.DB()
if err != nil {
return err
@@ -77,13 +77,17 @@ func checkDatabase(ctx context.Context, db *gorm.DB) error {
}
// checkRedis 检查Redis连接
func checkRedis(ctx context.Context, client *redis.Client) error {
func checkRedis(ctx context.Context) error {
client, err := redis.GetClient()
if err != nil {
return err
}
if client == nil {
return errors.New("Redis客户端未初始化")
}
// 使用Ping检查连接封装后的方法直接返回error
if err := client.Ping(ctx); err != nil {
// 使用Ping检查连接
if err := client.Ping(ctx).Err(); err != nil {
return err
}

View File

@@ -12,8 +12,7 @@ import (
func TestHealthCheck_Degraded(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
// 传入 nil 依赖,模拟服务不可用场景
router.GET("/health", NewHealthCheck(nil, nil))
router.GET("/health", HealthCheck)
req := httptest.NewRequest(http.MethodGet, "/health", nil)
w := httptest.NewRecorder()
@@ -23,3 +22,6 @@ func TestHealthCheck_Degraded(t *testing.T) {
t.Fatalf("expected 503 when dependencies missing, got %d", w.Code)
}
}

View File

@@ -1,11 +1,10 @@
package handler
import (
"strconv"
"carrotskin/internal/container"
"carrotskin/internal/model"
"carrotskin/internal/types"
"strconv"
"github.com/gin-gonic/gin"
"go.uber.org/zap"

View File

@@ -1,243 +0,0 @@
package handler
import (
"errors"
"net/http"
apperrors "carrotskin/internal/errors"
"carrotskin/internal/container"
"carrotskin/internal/service"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// YggdrasilFriendsHandler MinecraftServices 好友系接口处理器(文档 1.1~1.3、1.6
type YggdrasilFriendsHandler struct {
container *container.Container
logger *zap.Logger
}
// NewYggdrasilFriendsHandler 创建 YggdrasilFriendsHandler 实例
func NewYggdrasilFriendsHandler(c *container.Container) *YggdrasilFriendsHandler {
return &YggdrasilFriendsHandler{
container: c,
logger: c.Logger,
}
}
// extractProfileUUID 解析 Bearer token 得到当前请求者的 Profile UUID
// 失败时已写入 401 响应
func (h *YggdrasilFriendsHandler) extractProfileUUID(c *gin.Context) (string, bool) {
token, ok := extractBearerToken(c)
if !ok {
return "", false
}
uuid, err := h.container.TokenService.GetUUIDByAccessToken(c.Request.Context(), token)
if err != nil || uuid == "" {
h.logger.Warn("好友接口鉴权失败: 无效令牌", zap.Error(err))
c.JSON(http.StatusUnauthorized, apperrors.NewMinecraftServicesErrorResponse(
c.Request.URL.Path, "UNAUTHORIZED", "Invalid token", nil,
))
return "", false
}
return uuid, true
}
// respondFriendsError 将 service 错误映射为 MinecraftServices 标准错误响应
func (h *YggdrasilFriendsHandler) respondFriendsError(c *gin.Context, err error) {
var appErr *apperrors.AppError
if errors.As(err, &appErr) {
// 未知 profile / 不能加自己 -> 400
if appErr.Code == 400 {
c.JSON(http.StatusBadRequest, apperrors.NewMinecraftServicesErrorResponse(
c.Request.URL.Path, appErr.Message, appErr.Message, nil,
))
return
}
if appErr.Code == 403 {
c.JSON(http.StatusForbidden, apperrors.NewMinecraftServicesErrorResponse(
c.Request.URL.Path, "FORBIDDEN", appErr.Message, nil,
))
return
}
}
h.logger.Error("好友接口内部错误", zap.Error(err))
c.JSON(http.StatusInternalServerError, apperrors.NewMinecraftServicesErrorResponse(
c.Request.URL.Path, "SERVICE_NOT_AVAILABLE", "Internal server error", nil,
))
}
// GetFriends 获取好友列表
// @Summary MinecraftServices 好友列表
// @Description 拉取好友列表与收到/发出的好友请求(文档 1.3.1
// @Tags Yggdrasil
// @Produce json
// @Param Authorization header string true "Bearer {accessToken}"
// @Success 200 {object} service.FriendsListResponse
// @Failure 401 {object} apperrors.MinecraftServicesErrorResponse "未授权"
// @Failure 500 {object} apperrors.MinecraftServicesErrorResponse "服务器错误"
// @Router /api/yggdrasil/minecraftservices/friends [get]
func (h *YggdrasilFriendsHandler) GetFriends(c *gin.Context) {
uuid, ok := h.extractProfileUUID(c)
if !ok {
return
}
resp, err := h.container.FriendsService.ListFriends(c.Request.Context(), uuid)
if err != nil {
h.respondFriendsError(c, err)
return
}
c.JSON(http.StatusOK, resp)
}
// UpdateFriends 添加/删除好友、接受/拒绝/撤回请求
// @Summary MinecraftServices 好友操作
// @Description 通过 updateType=ADD/REMOVE 进行好友加删、接受/拒绝/撤回请求(文档 1.3.2
// @Tags Yggdrasil
// @Accept json
// @Produce json
// @Param Authorization header string true "Bearer {accessToken}"
// @Param request body service.FriendActionRequest true "好友操作请求"
// @Success 200 {object} service.FriendsListResponse
// @Failure 400 {object} apperrors.MinecraftServicesErrorResponse "参数错误"
// @Failure 401 {object} apperrors.MinecraftServicesErrorResponse "未授权"
// @Router /api/yggdrasil/minecraftservices/friends [put]
func (h *YggdrasilFriendsHandler) UpdateFriends(c *gin.Context) {
uuid, ok := h.extractProfileUUID(c)
if !ok {
return
}
var req service.FriendActionRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, apperrors.NewMinecraftServicesErrorResponse(
c.Request.URL.Path, "UNKNOWN_PROFILE", "Invalid request body", nil,
))
return
}
resp, err := h.container.FriendsService.PerformFriendAction(c.Request.Context(), uuid, req)
if err != nil {
h.respondFriendsError(c, err)
return
}
c.JSON(http.StatusOK, resp)
}
// GetAttributes 获取玩家属性
// @Summary MinecraftServices 玩家属性
// @Description 拉取好友/脏词过滤/聊天偏好属性(文档 1.2.1
// @Tags Yggdrasil
// @Produce json
// @Param Authorization header string true "Bearer {accessToken}"
// @Success 200 {object} service.PlayerAttributesResponse
// @Failure 401 {object} apperrors.MinecraftServicesErrorResponse "未授权"
// @Router /api/yggdrasil/minecraftservices/player/attributes [get]
func (h *YggdrasilFriendsHandler) GetAttributes(c *gin.Context) {
uuid, ok := h.extractProfileUUID(c)
if !ok {
return
}
resp, err := h.container.FriendsService.GetAttributes(c.Request.Context(), uuid)
if err != nil {
h.respondFriendsError(c, err)
return
}
c.JSON(http.StatusOK, resp)
}
// UpdateAttributes 更新玩家偏好属性
// @Summary MinecraftServices 更新玩家属性
// @Description 更新好友/脏词过滤偏好(文档 1.2.2
// @Tags Yggdrasil
// @Accept json
// @Produce json
// @Param Authorization header string true "Bearer {accessToken}"
// @Param request body service.PlayerAttributesRequest true "偏好更新请求"
// @Success 200 {object} service.PlayerAttributesResponse
// @Failure 400 {object} apperrors.MinecraftServicesErrorResponse "参数错误"
// @Failure 401 {object} apperrors.MinecraftServicesErrorResponse "未授权"
// @Router /api/yggdrasil/minecraftservices/player/attributes [post]
func (h *YggdrasilFriendsHandler) UpdateAttributes(c *gin.Context) {
uuid, ok := h.extractProfileUUID(c)
if !ok {
return
}
var req service.PlayerAttributesRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, apperrors.NewMinecraftServicesErrorResponse(
c.Request.URL.Path, "UNKNOWN_PROFILE", "Invalid request body", nil,
))
return
}
if err := h.container.FriendsService.UpdateAttributes(c.Request.Context(), uuid, req); err != nil {
h.respondFriendsError(c, err)
return
}
// 返回最新属性
resp, err := h.container.FriendsService.GetAttributes(c.Request.Context(), uuid)
if err != nil {
h.respondFriendsError(c, err)
return
}
c.JSON(http.StatusOK, resp)
}
// UpdatePresence 上报在线状态
// @Summary MinecraftServices 在线状态
// @Description 上报当前在线状态并返回好友在线状态列表(文档 1.1
// @Tags Yggdrasil
// @Accept json
// @Produce json
// @Param Authorization header string true "Bearer {accessToken}"
// @Param request body service.PresenceRequest true "状态上报请求"
// @Success 200 {object} service.PresenceResponse
// @Failure 400 {object} apperrors.MinecraftServicesErrorResponse "参数错误"
// @Failure 401 {object} apperrors.MinecraftServicesErrorResponse "未授权"
// @Router /api/yggdrasil/minecraftservices/presence [post]
func (h *YggdrasilFriendsHandler) UpdatePresence(c *gin.Context) {
uuid, ok := h.extractProfileUUID(c)
if !ok {
return
}
var req service.PresenceRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, apperrors.NewMinecraftServicesErrorResponse(
c.Request.URL.Path, "INVALID_STATUS", "Invalid request body", nil,
))
return
}
if req.Status == "" {
c.JSON(http.StatusBadRequest, apperrors.NewMinecraftServicesErrorResponse(
c.Request.URL.Path, "INVALID_STATUS", "Bad status value", nil,
))
return
}
resp, err := h.container.FriendsService.UpdatePresence(c.Request.Context(), uuid, req.Status)
if err != nil {
h.respondFriendsError(c, err)
return
}
c.JSON(http.StatusOK, resp)
}
// GetBlocklist 获取玩家屏蔽列表
// @Summary MinecraftServices 屏蔽列表
// @Description 拉取被屏蔽玩家档案 UUID 列表(文档 1.6
// @Tags Yggdrasil
// @Produce json
// @Param Authorization header string true "Bearer {accessToken}"
// @Success 200 {object} service.BlockListResponse
// @Failure 401 {object} apperrors.MinecraftServicesErrorResponse "未授权"
// @Router /api/yggdrasil/minecraftservices/privacy/blocklist [get]
func (h *YggdrasilFriendsHandler) GetBlocklist(c *gin.Context) {
uuid, ok := h.extractProfileUUID(c)
if !ok {
return
}
resp, err := h.container.FriendsService.GetBlocklist(c.Request.Context(), uuid)
if err != nil {
h.respondFriendsError(c, err)
return
}
c.JSON(http.StatusOK, resp)
}

View File

@@ -1,44 +0,0 @@
package handler
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
// TestExtractBearerToken 校验 Bearer token 解析
func TestExtractBearerToken(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name string
auth string
wantToken string
wantOK bool
}{
{name: "缺失 header", auth: "", wantOK: false},
{name: "错误前缀", auth: "Token abc", wantOK: false},
{name: "Bearer 空", auth: "Bearer ", wantOK: false},
{name: "有效 Bearer", auth: "Bearer mytoken123", wantToken: "mytoken123", wantOK: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/friends", nil)
if tt.auth != "" {
c.Request.Header.Set("Authorization", tt.auth)
}
got, ok := extractBearerToken(c)
if ok != tt.wantOK {
t.Fatalf("ok = %v, want %v", ok, tt.wantOK)
}
if ok && got != tt.wantToken {
t.Errorf("token = %q, want %q", got, tt.wantToken)
}
})
}
}

View File

@@ -1,13 +1,13 @@
package handler
import (
"net/http"
"regexp"
"bytes"
"carrotskin/internal/container"
"carrotskin/internal/errors"
"carrotskin/internal/model"
"carrotskin/pkg/utils"
"io"
"net/http"
"regexp"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
@@ -15,18 +15,66 @@ import (
// 常量定义
const (
ErrInternalServer = "服务器内部错误"
// 错误类型
ErrInvalidEmailFormat = "邮箱格式不正确"
ErrInvalidPassword = "密码必须至少包含8个字符只能包含字母、数字和特殊字符"
ErrWrongPassword = "密码错误"
ErrUserNotMatch = "用户不匹配"
// 错误消息
ErrInvalidRequest = "请求格式无效"
ErrJoinServerFailed = "加入服务器失败"
ErrServerIDRequired = "服务器ID不能为空"
ErrUsernameRequired = "用户名不能为空"
ErrSessionVerifyFailed = "会话验证失败"
ErrProfileNotFound = "未找到用户配置文件"
ErrInvalidParams = "无效的请求参数"
ErrEmptyUserID = "用户ID为空"
ErrUnauthorized = "无权操作此配置文件"
ErrGetProfileService = "获取配置文件服务失败"
// 成功信息
SuccessProfileCreated = "创建成功"
MsgRegisterSuccess = "注册成功"
// 错误消息
ErrGetProfile = "获取配置文件失败"
ErrGetTextureService = "获取材质服务失败"
ErrInvalidContentType = "无效的请求内容类型"
ErrParseMultipartForm = "解析多部分表单失败"
ErrGetFileFromForm = "从表单获取文件失败"
ErrInvalidFileType = "无效的文件类型仅支持PNG图片"
ErrSaveTexture = "保存材质失败"
ErrSetTexture = "设置材质失败"
ErrGetTexture = "获取材质失败"
// 内存限制
MaxMultipartMemory = 32 << 20 // 32 MB
// 材质类型
TextureTypeSkin = "SKIN"
TextureTypeCape = "CAPE"
// 内容类型
ContentTypePNG = "image/png"
ContentTypeMultipart = "multipart/form-data"
// 表单参数
FormKeyModel = "model"
FormKeyFile = "file"
// 元数据键
MetaKeyModel = "model"
)
// 正则表达式
var (
// 邮箱正则表达式
emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$`)
// 密码强度正则表达式最少8位只允许字母、数字和特定特殊字符
passwordRegex = regexp.MustCompile(`^[a-zA-Z0-9!@#$%^&*]{8,}$`)
)
// 请求结构体
@@ -81,14 +129,29 @@ type (
// RefreshResponse 刷新令牌响应
RefreshResponse struct {
AccessToken string `json:"accessToken"`
ClientToken string `json:"clientToken"`
SelectedProfile map[string]interface{} `json:"selectedProfile,omitempty"`
AvailableProfiles []map[string]interface{} `json:"availableProfiles"`
User map[string]interface{} `json:"user,omitempty"`
AccessToken string `json:"accessToken"`
ClientToken string `json:"clientToken"`
SelectedProfile map[string]interface{} `json:"selectedProfile,omitempty"`
User map[string]interface{} `json:"user,omitempty"`
}
)
// APIResponse API响应
type APIResponse struct {
Status int `json:"status"`
Data interface{} `json:"data"`
Error interface{} `json:"error"`
}
// standardResponse 生成标准响应
func standardResponse(c *gin.Context, status int, data interface{}, err interface{}) {
c.JSON(status, APIResponse{
Status: status,
Data: data,
Error: err,
})
}
// YggdrasilHandler Yggdrasil API处理器
type YggdrasilHandler struct {
container *container.Container
@@ -112,10 +175,18 @@ func NewYggdrasilHandler(c *container.Container) *YggdrasilHandler {
// @Param request body AuthenticateRequest true "认证请求"
// @Success 200 {object} AuthenticateResponse
// @Failure 403 {object} map[string]string "认证失败"
// @Router /api/yggdrasil/authserver/authenticate [post]
// @Router /api/v1/yggdrasil/authserver/authenticate [post]
func (h *YggdrasilHandler) Authenticate(c *gin.Context) {
rawData, err := io.ReadAll(c.Request.Body)
if err != nil {
h.logger.Error("读取请求体失败", zap.Error(err))
c.JSON(http.StatusBadRequest, gin.H{"error": "读取请求体失败"})
return
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(rawData))
var request AuthenticateRequest
if err := c.ShouldBindJSON(&request); err != nil {
if err = c.ShouldBindJSON(&request); err != nil {
h.logger.Error("解析认证请求失败", zap.Error(err))
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
@@ -124,20 +195,14 @@ func (h *YggdrasilHandler) Authenticate(c *gin.Context) {
var userId int64
var profile *model.Profile
var UUID string
var err error
if emailRegex.MatchString(request.Identifier) {
// 邮箱登录UUID 留空,后续 TokenService.Create 会自动选择该用户的角色
userId, err = h.container.YggdrasilService.GetUserIDByEmail(c.Request.Context(), request.Identifier)
} else {
profile, err = h.container.ProfileService.GetByProfileName(c.Request.Context(), request.Identifier)
profile, err = h.container.ProfileRepo.FindByName(c.Request.Context(), request.Identifier)
if err != nil {
h.logger.Error("用户名不存在", zap.String("identifier", request.Identifier), zap.Error(err))
c.JSON(http.StatusForbidden, errors.NewYggdrasilErrorResponse(
"ForbiddenOperationException",
errors.YggErrInvalidCredentials,
"",
))
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
return
}
userId = profile.UserID
@@ -146,21 +211,13 @@ func (h *YggdrasilHandler) Authenticate(c *gin.Context) {
if err != nil {
h.logger.Warn("认证失败: 用户不存在", zap.String("identifier", request.Identifier), zap.Error(err))
c.JSON(http.StatusForbidden, errors.NewYggdrasilErrorResponse(
"ForbiddenOperationException",
errors.YggErrInvalidCredentials,
"",
))
c.JSON(http.StatusForbidden, gin.H{"error": "用户不存在"})
return
}
if err := h.container.YggdrasilService.VerifyPassword(c.Request.Context(), request.Password, userId); err != nil {
h.logger.Warn("认证失败: 密码错误", zap.Error(err))
c.JSON(http.StatusForbidden, errors.NewYggdrasilErrorResponse(
"ForbiddenOperationException",
errors.YggErrInvalidCredentials,
"",
))
c.JSON(http.StatusForbidden, gin.H{"error": ErrWrongPassword})
return
}
@@ -207,8 +264,8 @@ func (h *YggdrasilHandler) Authenticate(c *gin.Context) {
// @Produce json
// @Param request body ValidTokenRequest true "验证请求"
// @Success 204 "令牌有效"
// @Failure 403 {object} errors.YggdrasilErrorResponse "令牌无效"
// @Router /api/yggdrasil/authserver/validate [post]
// @Failure 403 {object} map[string]bool "令牌无效"
// @Router /api/v1/yggdrasil/authserver/validate [post]
func (h *YggdrasilHandler) ValidToken(c *gin.Context) {
var request ValidTokenRequest
if err := c.ShouldBindJSON(&request); err != nil {
@@ -219,14 +276,10 @@ func (h *YggdrasilHandler) ValidToken(c *gin.Context) {
if h.container.TokenService.Validate(c.Request.Context(), request.AccessToken, request.ClientToken) {
h.logger.Info("令牌验证成功", zap.String("accessToken", request.AccessToken))
c.JSON(http.StatusNoContent, gin.H{})
c.JSON(http.StatusNoContent, gin.H{"valid": true})
} else {
h.logger.Warn("令牌验证失败", zap.String("accessToken", request.AccessToken))
c.JSON(http.StatusForbidden, errors.NewYggdrasilErrorResponse(
"ForbiddenOperationException",
errors.YggErrInvalidToken,
"",
))
c.JSON(http.StatusForbidden, gin.H{"valid": false})
}
}
@@ -239,7 +292,7 @@ func (h *YggdrasilHandler) ValidToken(c *gin.Context) {
// @Param request body RefreshRequest true "刷新请求"
// @Success 200 {object} RefreshResponse
// @Failure 400 {object} map[string]string "刷新失败"
// @Router /api/yggdrasil/authserver/refresh [post]
// @Router /api/v1/yggdrasil/authserver/refresh [post]
func (h *YggdrasilHandler) RefreshToken(c *gin.Context) {
var request RefreshRequest
if err := c.ShouldBindJSON(&request); err != nil {
@@ -248,33 +301,19 @@ func (h *YggdrasilHandler) RefreshToken(c *gin.Context) {
return
}
// 获取用户ID和当前绑定的Profile UUID
userID, err := h.container.TokenService.GetUserIDByAccessToken(c.Request.Context(), request.AccessToken)
UUID, err := h.container.TokenService.GetUUIDByAccessToken(c.Request.Context(), request.AccessToken)
if err != nil {
h.logger.Warn("刷新令牌失败: 无效的访问令牌", zap.String("token", request.AccessToken), zap.Error(err))
c.JSON(http.StatusForbidden, errors.NewYggdrasilErrorResponse(
"ForbiddenOperationException",
errors.YggErrInvalidToken,
"",
))
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
currentUUID, err := h.container.TokenService.GetUUIDByAccessToken(c.Request.Context(), request.AccessToken)
if err != nil {
h.logger.Warn("刷新令牌失败: 无法获取当前Profile", zap.String("token", request.AccessToken), zap.Error(err))
c.JSON(http.StatusForbidden, errors.NewYggdrasilErrorResponse(
"ForbiddenOperationException",
errors.YggErrInvalidToken,
"",
))
return
}
userID, _ := h.container.TokenService.GetUserIDByAccessToken(c.Request.Context(), request.AccessToken)
UUID = utils.FormatUUID(UUID)
// 获取用户的所有可用profiles
availableProfiles, err := h.container.ProfileService.GetByUserID(c.Request.Context(), userID)
profile, err := h.container.ProfileService.GetByUUID(c.Request.Context(), UUID)
if err != nil {
h.logger.Error("刷新令牌失败: 无法获取用户profiles", zap.Error(err), zap.Int64("userId", userID))
h.logger.Error("刷新令牌失败: 无法获取用户信息", zap.Error(err))
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
@@ -283,7 +322,6 @@ func (h *YggdrasilHandler) RefreshToken(c *gin.Context) {
var userData map[string]interface{}
var profileID string
// 处理selectedProfile
if request.SelectedProfile != nil {
profileIDValue, ok := request.SelectedProfile["id"]
if !ok {
@@ -299,69 +337,25 @@ func (h *YggdrasilHandler) RefreshToken(c *gin.Context) {
return
}
// 确保profileID是32位无符号格式用于向后兼容
profileID = utils.FormatUUIDToNoDash(profileID)
// 根据Yggdrasil规范当指定selectedProfile时原令牌所绑定的角色必须为空
// 如果原令牌已绑定角色,则不允许更换角色,但允许选择相同的角色以兼容部分启动器
if currentUUID != "" && currentUUID != profileID {
h.logger.Warn("刷新令牌失败: 令牌已绑定其他角色,不允许更换",
zap.Int64("userId", userID),
zap.String("currentUUID", currentUUID),
zap.String("requestedUUID", profileID),
)
c.JSON(http.StatusBadRequest, errors.NewYggdrasilErrorResponse(
"IllegalArgumentException",
errors.YggErrProfileAlreadyAssigned,
"",
))
return
}
// 验证profile是否属于该用户
profile, err := h.container.ProfileService.GetByUUID(c.Request.Context(), profileID)
if err != nil {
h.logger.Warn("刷新令牌失败: Profile不存在", zap.String("profileId", profileID), zap.Error(err))
c.JSON(http.StatusForbidden, errors.NewYggdrasilErrorResponse(
"ForbiddenOperationException",
errors.YggErrInvalidToken,
"",
))
return
}
profileID = utils.FormatUUID(profileID)
if profile.UserID != userID {
h.logger.Warn("刷新令牌失败: 用户不匹配",
zap.Int64("userId", userID),
zap.Int64("profileUserId", profile.UserID),
)
c.JSON(http.StatusForbidden, errors.NewYggdrasilErrorResponse(
"ForbiddenOperationException",
errors.YggErrInvalidToken,
"",
))
c.JSON(http.StatusBadRequest, gin.H{"error": ErrUserNotMatch})
return
}
profileData = h.container.YggdrasilService.SerializeProfile(c.Request.Context(), *profile)
} else {
// 如果未指定selectedProfile使用当前token绑定的profile如果存在
if currentUUID != "" {
profile, err := h.container.ProfileService.GetByUUID(c.Request.Context(), currentUUID)
if err == nil && profile != nil {
profileID = currentUUID
profileData = h.container.YggdrasilService.SerializeProfile(c.Request.Context(), *profile)
}
}
}
// 获取用户信息(如果请求)
user, _ := h.container.UserService.GetByID(c.Request.Context(), userID)
if request.RequestUser && user != nil {
userData = h.container.YggdrasilService.SerializeUser(c.Request.Context(), user, currentUUID)
userData = h.container.YggdrasilService.SerializeUser(c.Request.Context(), user, UUID)
}
// 刷新token
newAccessToken, newClientToken, err := h.container.TokenService.Refresh(c.Request.Context(),
request.AccessToken,
request.ClientToken,
@@ -369,27 +363,16 @@ func (h *YggdrasilHandler) RefreshToken(c *gin.Context) {
)
if err != nil {
h.logger.Error("刷新令牌失败", zap.Error(err), zap.Int64("userId", userID))
c.JSON(http.StatusForbidden, errors.NewYggdrasilErrorResponse(
"ForbiddenOperationException",
errors.YggErrInvalidToken,
"",
))
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// 序列化可用profiles
availableProfilesData := make([]map[string]interface{}, 0, len(availableProfiles))
for _, p := range availableProfiles {
availableProfilesData = append(availableProfilesData, h.container.YggdrasilService.SerializeProfile(c.Request.Context(), *p))
}
h.logger.Info("刷新令牌成功", zap.Int64("userId", userID))
c.JSON(http.StatusOK, RefreshResponse{
AccessToken: newAccessToken,
ClientToken: newClientToken,
SelectedProfile: profileData,
AvailableProfiles: availableProfilesData,
User: userData,
AccessToken: newAccessToken,
ClientToken: newClientToken,
SelectedProfile: profileData,
User: userData,
})
}
@@ -401,7 +384,7 @@ func (h *YggdrasilHandler) RefreshToken(c *gin.Context) {
// @Produce json
// @Param request body ValidTokenRequest true "失效请求"
// @Success 204 "操作成功"
// @Router /api/yggdrasil/authserver/invalidate [post]
// @Router /api/v1/yggdrasil/authserver/invalidate [post]
func (h *YggdrasilHandler) InvalidToken(c *gin.Context) {
var request ValidTokenRequest
if err := c.ShouldBindJSON(&request); err != nil {
@@ -424,7 +407,7 @@ func (h *YggdrasilHandler) InvalidToken(c *gin.Context) {
// @Param request body SignOutRequest true "登出请求"
// @Success 204 "操作成功"
// @Failure 400 {object} map[string]string "参数错误"
// @Router /api/yggdrasil/authserver/signout [post]
// @Router /api/v1/yggdrasil/authserver/signout [post]
func (h *YggdrasilHandler) SignOut(c *gin.Context) {
var request SignOutRequest
if err := c.ShouldBindJSON(&request); err != nil {
@@ -435,7 +418,7 @@ func (h *YggdrasilHandler) SignOut(c *gin.Context) {
if !emailRegex.MatchString(request.Email) {
h.logger.Warn("登出失败: 邮箱格式不正确", zap.String("email", request.Email))
c.JSON(http.StatusBadRequest, gin.H{"error": "邮箱格式不正确"})
c.JSON(http.StatusBadRequest, gin.H{"error": ErrInvalidEmailFormat})
return
}
@@ -448,11 +431,7 @@ func (h *YggdrasilHandler) SignOut(c *gin.Context) {
if err := h.container.YggdrasilService.VerifyPassword(c.Request.Context(), request.Password, user.ID); err != nil {
h.logger.Warn("登出失败: 密码错误", zap.Int64("userId", user.ID))
c.JSON(http.StatusForbidden, errors.NewYggdrasilErrorResponse(
"ForbiddenOperationException",
errors.YggErrInvalidCredentials,
"",
))
c.JSON(http.StatusBadRequest, gin.H{"error": ErrWrongPassword})
return
}
@@ -468,35 +447,22 @@ func (h *YggdrasilHandler) SignOut(c *gin.Context) {
// @Accept json
// @Produce json
// @Param uuid path string true "用户UUID"
// @Param unsigned query string false "是否不返回签名true/false默认false"
// @Success 200 {object} map[string]interface{} "档案信息"
// @Failure 404 {object} errors.YggdrasilErrorResponse "档案不存在"
// @Router /api/yggdrasil/sessionserver/session/minecraft/profile/{uuid} [get]
// @Failure 500 {object} APIResponse "服务器错误"
// @Router /api/v1/yggdrasil/sessionserver/session/minecraft/profile/{uuid} [get]
func (h *YggdrasilHandler) GetProfileByUUID(c *gin.Context) {
uuid := c.Param("uuid")
uuid := utils.FormatUUID(c.Param("uuid"))
h.logger.Info("获取配置文件请求", zap.String("uuid", uuid))
profile, err := h.container.ProfileService.GetByUUID(c.Request.Context(), uuid)
if err != nil {
h.logger.Error("获取配置文件失败", zap.Error(err), zap.String("uuid", uuid))
c.JSON(http.StatusNotFound, errors.NewYggdrasilErrorResponse(
"Not Found",
"Profile not found",
"",
))
standardResponse(c, http.StatusInternalServerError, nil, err.Error())
return
}
// 读取 unsigned 查询参数
unsignedParam := c.DefaultQuery("unsigned", "false")
unsigned := unsignedParam == "true"
h.logger.Info("成功获取配置文件",
zap.String("uuid", uuid),
zap.String("name", profile.Name),
zap.Bool("unsigned", unsigned))
c.JSON(http.StatusOK, h.container.YggdrasilService.SerializeProfileWithUnsigned(c.Request.Context(), *profile, unsigned))
h.logger.Info("成功获取配置文件", zap.String("uuid", uuid), zap.String("name", profile.Name))
c.JSON(http.StatusOK, h.container.YggdrasilService.SerializeProfile(c.Request.Context(), *profile))
}
// JoinServer 加入服务器
@@ -507,20 +473,16 @@ func (h *YggdrasilHandler) GetProfileByUUID(c *gin.Context) {
// @Produce json
// @Param request body JoinServerRequest true "加入请求"
// @Success 204 "加入成功"
// @Failure 400 {object} map[string]string "参数错误"
// @Failure 500 {object} map[string]string "服务器错误"
// @Router /api/yggdrasil/sessionserver/session/minecraft/join [post]
// @Failure 400 {object} APIResponse "参数错误"
// @Failure 500 {object} APIResponse "服务器错误"
// @Router /api/v1/yggdrasil/sessionserver/session/minecraft/join [post]
func (h *YggdrasilHandler) JoinServer(c *gin.Context) {
var request JoinServerRequest
clientIP := c.ClientIP()
if err := c.ShouldBindJSON(&request); err != nil {
h.logger.Error("解析加入服务器请求失败", zap.Error(err), zap.String("ip", clientIP))
c.JSON(http.StatusBadRequest, errors.NewYggdrasilErrorResponse(
"Bad Request",
"Invalid request format",
"",
))
standardResponse(c, http.StatusBadRequest, nil, ErrInvalidRequest)
return
}
@@ -537,11 +499,7 @@ func (h *YggdrasilHandler) JoinServer(c *gin.Context) {
zap.String("userUUID", request.SelectedProfile),
zap.String("ip", clientIP),
)
c.JSON(http.StatusForbidden, errors.NewYggdrasilErrorResponse(
"ForbiddenOperationException",
errors.YggErrInvalidToken,
"",
))
standardResponse(c, http.StatusInternalServerError, nil, ErrJoinServerFailed)
return
}
@@ -564,21 +522,21 @@ func (h *YggdrasilHandler) JoinServer(c *gin.Context) {
// @Param ip query string false "客户端IP"
// @Success 200 {object} map[string]interface{} "验证成功,返回档案"
// @Failure 204 "验证失败"
// @Router /api/yggdrasil/sessionserver/session/minecraft/hasJoined [get]
// @Router /api/v1/yggdrasil/sessionserver/session/minecraft/hasJoined [get]
func (h *YggdrasilHandler) HasJoinedServer(c *gin.Context) {
clientIP, _ := c.GetQuery("ip")
serverID, exists := c.GetQuery("serverId")
if !exists || serverID == "" {
h.logger.Warn("缺少服务器ID参数", zap.String("ip", clientIP))
c.Status(http.StatusNoContent)
standardResponse(c, http.StatusNoContent, nil, ErrServerIDRequired)
return
}
username, exists := c.GetQuery("username")
if !exists || username == "" {
h.logger.Warn("缺少用户名参数", zap.String("serverId", serverID), zap.String("ip", clientIP))
c.Status(http.StatusNoContent)
standardResponse(c, http.StatusNoContent, nil, ErrUsernameRequired)
return
}
@@ -595,14 +553,14 @@ func (h *YggdrasilHandler) HasJoinedServer(c *gin.Context) {
zap.String("username", username),
zap.String("ip", clientIP),
)
c.Status(http.StatusNoContent)
standardResponse(c, http.StatusNoContent, nil, ErrSessionVerifyFailed)
return
}
profile, err := h.container.ProfileService.GetByProfileName(c.Request.Context(), username)
profile, err := h.container.ProfileService.GetByUUID(c.Request.Context(), username)
if err != nil {
h.logger.Error("获取用户配置文件失败", zap.Error(err), zap.String("username", username))
c.Status(http.StatusNoContent)
standardResponse(c, http.StatusNoContent, nil, ErrProfileNotFound)
return
}
@@ -611,110 +569,37 @@ func (h *YggdrasilHandler) HasJoinedServer(c *gin.Context) {
zap.String("username", username),
zap.String("uuid", profile.UUID),
)
c.JSON(http.StatusOK, h.container.YggdrasilService.SerializeProfile(c.Request.Context(), *profile))
c.JSON(200, h.container.YggdrasilService.SerializeProfile(c.Request.Context(), *profile))
}
// GetProfilesByName 批量获取配置文件
// @Summary Yggdrasil批量获取档案
// @Description Yggdrasil协议: 根据名称批量获取用户档案(文档 2.1,每页最多 10 个,返回 [{id,name}]
// @Description Yggdrasil协议: 根据名称批量获取用户档案
// @Tags Yggdrasil
// @Accept json
// @Produce json
// @Param request body []string true "用户名列表"
// @Success 200 {array} model.NameAndId "档案标识列表"
// @Failure 400 {object} map[string]string "参数错误"
// @Router /api/yggdrasil/api/profiles/minecraft [post]
// @Success 200 {array} model.Profile "档案列表"
// @Failure 400 {object} APIResponse "参数错误"
// @Router /api/v1/yggdrasil/api/profiles/minecraft [post]
func (h *YggdrasilHandler) GetProfilesByName(c *gin.Context) {
var names []string
if err := c.ShouldBindJSON(&names); err != nil {
h.logger.Error("解析名称数组请求失败", zap.Error(err))
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
standardResponse(c, http.StatusBadRequest, nil, ErrInvalidParams)
return
}
h.logger.Info("接收到批量获取配置文件请求", zap.Int("count", len(names)))
// 文档 2.1:每页最多 10 个用户名
const maxBatch = 10
results, err := h.container.ProfileService.ProfileSearchByName(c.Request.Context(), names, maxBatch)
profiles, err := h.container.ProfileService.GetByNames(c.Request.Context(), names)
if err != nil {
h.logger.Warn("批量获取配置文件失败", zap.Error(err), zap.Int("count", len(names)))
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
h.logger.Error("获取配置文件失败", zap.Error(err))
}
h.logger.Info("成功获取配置文件", zap.Int("requested", len(names)), zap.Int("returned", len(results)))
c.JSON(http.StatusOK, results)
}
// GetProfileByName 单个用户名查档案
// @Summary Yggdrasil按用户名查档案
// @Description Yggdrasil协议: 根据单个用户名查询用户档案(文档 2.2,返回 {id,name}
// @Tags Yggdrasil
// @Produce json
// @Param name path string true "用户名"
// @Success 200 {object} model.NameAndId "档案标识"
// @Failure 404 {object} map[string]string "档案不存在"
// @Router /api/yggdrasil/api/users/profiles/minecraft/{name} [get]
func (h *YggdrasilHandler) GetProfileByName(c *gin.Context) {
name := c.Param("name")
if name == "" {
h.logger.Warn("缺少用户名参数")
c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
return
}
result, err := h.container.ProfileService.ProfileSearchByNameSingle(c.Request.Context(), name)
if err != nil {
// 按文档契约:任意错误视为未找到
h.logger.Warn("按用户名查档失败", zap.String("name", name), zap.Error(err))
c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
return
}
if result == nil {
h.logger.Info("用户名未找到", zap.String("name", name))
c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
return
}
h.logger.Info("成功获取档案", zap.String("name", name), zap.String("uuid", result.ID))
c.JSON(http.StatusOK, result)
}
// LookupProfileByName 单用户名查 UUIDauthlib-injector issue #277 / MC 1.21.7
// @Summary MinecraftServices 按用户名查 UUID
// @Description 对应官方 api.minecraftservices.com/minecraft/profile/lookup/name/{name}
// @Description 1.21.7 的 /whitelist add 等命令会请求该接口。authlib-injector 把
// @Description api.minecraftservices.com override 到 {apiRoot}/minecraftservices。
// @Description 返回 {id,name},未找到返回 404。
// @Tags Yggdrasil
// @Produce json
// @Param name path string true "用户名"
// @Success 200 {object} model.NameAndId "档案标识"
// @Failure 404 {object} map[string]string "档案不存在"
// @Router /api/yggdrasil/minecraftservices/minecraft/profile/lookup/name/{name} [get]
func (h *YggdrasilHandler) LookupProfileByName(c *gin.Context) {
name := c.Param("name")
if name == "" {
c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
return
}
result, err := h.container.ProfileService.ProfileSearchByNameSingle(c.Request.Context(), name)
if err != nil {
h.logger.Warn("按用户名查档失败", zap.String("name", name), zap.Error(err))
c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
return
}
if result == nil {
h.logger.Info("用户名未找到", zap.String("name", name))
c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
return
}
h.logger.Info("成功获取档案", zap.String("name", name), zap.String("uuid", result.ID))
c.JSON(http.StatusOK, result)
h.logger.Info("成功获取配置文件", zap.Int("requested", len(names)), zap.Int("returned", len(profiles)))
c.JSON(http.StatusOK, profiles)
}
// GetMetaData 获取Yggdrasil元数据
@@ -724,8 +609,8 @@ func (h *YggdrasilHandler) LookupProfileByName(c *gin.Context) {
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "元数据"
// @Failure 500 {object} map[string]string "服务器错误"
// @Router /api/yggdrasil [get]
// @Failure 500 {object} APIResponse "服务器错误"
// @Router /api/v1/yggdrasil [get]
func (h *YggdrasilHandler) GetMetaData(c *gin.Context) {
meta := gin.H{
"implementationName": "CellAuth",
@@ -743,11 +628,7 @@ func (h *YggdrasilHandler) GetMetaData(c *gin.Context) {
signature, err := h.container.YggdrasilService.GetPublicKey(c.Request.Context())
if err != nil {
h.logger.Error("获取公钥失败", zap.Error(err))
c.JSON(http.StatusInternalServerError, errors.NewYggdrasilErrorResponse(
"Internal Server Error",
"Failed to get public key",
"",
))
standardResponse(c, http.StatusInternalServerError, nil, ErrInternalServer)
return
}
@@ -766,66 +647,45 @@ func (h *YggdrasilHandler) GetMetaData(c *gin.Context) {
// @Accept json
// @Produce json
// @Param Authorization header string true "Bearer {token}"
// @Success 200 {object} service.PlayerCertificate "证书信息"
// @Failure 401 {object} errors.YggdrasilErrorResponse "未授权"
// @Failure 403 {object} errors.YggdrasilErrorResponse "令牌无效"
// @Failure 500 {object} errors.YggdrasilErrorResponse "服务器错误"
// @Router /api/yggdrasil/minecraftservices/player/certificates [post]
// @Success 200 {object} map[string]interface{} "证书信息"
// @Failure 401 {object} map[string]string "未授权"
// @Failure 500 {object} APIResponse "服务器错误"
// @Router /api/v1/yggdrasil/minecraftservices/player/certificates [post]
func (h *YggdrasilHandler) GetPlayerCertificates(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, errors.NewYggdrasilErrorResponse(
"Unauthorized",
"Authorization header not provided",
"",
))
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header not provided"})
c.Abort()
return
}
bearerPrefix := "Bearer "
if len(authHeader) < len(bearerPrefix) || authHeader[:len(bearerPrefix)] != bearerPrefix {
c.JSON(http.StatusUnauthorized, errors.NewYggdrasilErrorResponse(
"Unauthorized",
"Invalid Authorization format",
"",
))
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid Authorization format"})
c.Abort()
return
}
tokenID := authHeader[len(bearerPrefix):]
if tokenID == "" {
c.JSON(http.StatusUnauthorized, errors.NewYggdrasilErrorResponse(
"Unauthorized",
"Invalid Authorization format",
"",
))
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid Authorization format"})
c.Abort()
return
}
uuid, err := h.container.TokenService.GetUUIDByAccessToken(c.Request.Context(), tokenID)
if err != nil || uuid == "" {
if uuid == "" {
h.logger.Error("获取玩家UUID失败", zap.Error(err))
c.JSON(http.StatusUnauthorized, errors.NewYggdrasilErrorResponse(
"Unauthorized",
errors.YggErrInvalidToken,
"",
))
standardResponse(c, http.StatusInternalServerError, nil, ErrInternalServer)
return
}
// UUID已经是32位无符号格式无需转换
uuid = utils.FormatUUID(uuid)
certificate, err := h.container.YggdrasilService.GeneratePlayerCertificate(c.Request.Context(), uuid)
if err != nil {
h.logger.Error("生成玩家证书失败", zap.Error(err))
c.JSON(http.StatusInternalServerError, errors.NewYggdrasilErrorResponse(
"Internal Server Error",
"Failed to generate player certificate",
"",
))
standardResponse(c, http.StatusInternalServerError, nil, ErrInternalServer)
return
}

View File

@@ -1,11 +1,10 @@
package middleware
import (
"carrotskin/internal/model"
"net/http"
"strings"
"carrotskin/internal/model"
"carrotskin/pkg/auth"
"github.com/gin-gonic/gin"

View File

@@ -3,7 +3,6 @@ package middleware
import (
"net/http"
"carrotskin/internal/model"
"carrotskin/pkg/auth"
"github.com/gin-gonic/gin"
@@ -16,11 +15,10 @@ func CasbinMiddleware(casbinService *auth.CasbinService, resource, action string
// 从上下文获取用户角色由AuthMiddleware设置
role, exists := c.Get("user_role")
if !exists {
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
model.CodeUnauthorized,
model.MsgUnauthorized,
nil,
))
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"message": "未授权访问",
})
c.Abort()
return
}
@@ -32,11 +30,10 @@ func CasbinMiddleware(casbinService *auth.CasbinService, resource, action string
// 检查权限
if !casbinService.CheckPermission(roleStr, resource, action) {
c.JSON(http.StatusForbidden, model.NewErrorResponse(
model.CodeForbidden,
model.MsgForbidden,
nil,
))
c.JSON(http.StatusForbidden, gin.H{
"success": false,
"message": "权限不足",
})
c.Abort()
return
}
@@ -50,22 +47,20 @@ func RequireAdmin() gin.HandlerFunc {
return func(c *gin.Context) {
role, exists := c.Get("user_role")
if !exists {
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
model.CodeUnauthorized,
model.MsgUnauthorized,
nil,
))
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"message": "未授权访问",
})
c.Abort()
return
}
roleStr, ok := role.(string)
if !ok || roleStr != "admin" {
c.JSON(http.StatusForbidden, model.NewErrorResponse(
model.CodeForbidden,
"需要管理员权限",
nil,
))
c.JSON(http.StatusForbidden, gin.H{
"success": false,
"message": "需要管理员权限",
})
c.Abort()
return
}
@@ -79,22 +74,20 @@ func RequireRole(allowedRoles ...string) gin.HandlerFunc {
return func(c *gin.Context) {
role, exists := c.Get("user_role")
if !exists {
c.JSON(http.StatusUnauthorized, model.NewErrorResponse(
model.CodeUnauthorized,
model.MsgUnauthorized,
nil,
))
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"message": "未授权访问",
})
c.Abort()
return
}
roleStr, ok := role.(string)
if !ok {
c.JSON(http.StatusForbidden, model.NewErrorResponse(
model.CodeForbidden,
model.MsgForbidden,
nil,
))
c.JSON(http.StatusForbidden, gin.H{
"success": false,
"message": "权限不足",
})
c.Abort()
return
}
@@ -107,11 +100,10 @@ func RequireRole(allowedRoles ...string) gin.HandlerFunc {
}
}
c.JSON(http.StatusForbidden, model.NewErrorResponse(
model.CodeForbidden,
model.MsgForbidden,
nil,
))
c.JSON(http.StatusForbidden, gin.H{
"success": false,
"message": "权限不足",
})
c.Abort()
}
}

View File

@@ -7,14 +7,18 @@ import (
)
// CORS 跨域中间件
func CORS(cfg *config.Config) gin.HandlerFunc {
// 从注入的配置读取 CORS 设置
allowedOrigins := cfg.Security.AllowedOrigins
if len(allowedOrigins) == 0 {
// 默认允许所有来源
func CORS() gin.HandlerFunc {
// 获取配置,如果配置未初始化则使用默认值
var allowedOrigins []string
var isTestEnv bool
if cfg, err := config.GetConfig(); err == nil {
allowedOrigins = cfg.Security.AllowedOrigins
isTestEnv = cfg.IsTestEnvironment()
} else {
// 默认允许所有来源(向后兼容)
allowedOrigins = []string{"*"}
isTestEnv = false
}
isTestEnv := cfg.IsTestEnvironment()
return gin.HandlerFunc(func(c *gin.Context) {
origin := c.GetHeader("Origin")

View File

@@ -5,26 +5,15 @@ import (
"net/http/httptest"
"testing"
"carrotskin/pkg/config"
"github.com/gin-gonic/gin"
)
// testCORSConfig 返回测试用的 CORS 配置(通配符模式)
func testCORSConfig() *config.Config {
return &config.Config{
Security: config.SecurityConfig{
AllowedOrigins: []string{"*"},
},
}
}
// TestCORS_Headers 测试CORS中间件设置的响应头
func TestCORS_Headers(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(CORS(testCORSConfig()))
router.Use(CORS())
router.GET("/test", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "success"})
})
@@ -66,7 +55,7 @@ func TestCORS_OPTIONS(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(CORS(testCORSConfig()))
router.Use(CORS())
router.GET("/test", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "success"})
})
@@ -87,7 +76,7 @@ func TestCORS_AllowMethods(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(CORS(testCORSConfig()))
router.Use(CORS())
router.GET("/test", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "success"})
})
@@ -114,7 +103,7 @@ func TestCORS_AllowHeaders(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(CORS(testCORSConfig()))
router.Use(CORS())
router.GET("/test", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "success"})
})
@@ -141,7 +130,7 @@ func TestCORS_WithSpecificOrigin(t *testing.T) {
// 注意此测试验证的是在配置了具体allowed origins时的行为
// 在没有配置初始化的情况下,默认使用通配符模式
router := gin.New()
router.Use(CORS(testCORSConfig()))
router.Use(CORS())
router.GET("/test", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "success"})
})

View File

@@ -5,10 +5,10 @@ import "time"
// Client 客户端实体用于管理Token版本
// @Description Yggdrasil客户端Token管理数据
type Client struct {
UUID string `gorm:"column:uuid;type:varchar(32);primaryKey" json:"uuid"` // Client UUID
UUID string `gorm:"column:uuid;type:varchar(36);primaryKey" json:"uuid"` // Client UUID
ClientToken string `gorm:"column:client_token;type:varchar(64);not null;uniqueIndex" json:"client_token"` // 客户端Token
UserID int64 `gorm:"column:user_id;not null;index:idx_clients_user_id" json:"user_id"` // 用户ID
ProfileID string `gorm:"column:profile_id;type:varchar(32);index:idx_clients_profile_id" json:"profile_id,omitempty"` // 选中的Profile
ProfileID string `gorm:"column:profile_id;type:varchar(36);index:idx_clients_profile_id" json:"profile_id,omitempty"` // 选中的Profile
Version int `gorm:"column:version;not null;default:0;index:idx_clients_version" json:"version"` // 版本号
CreatedAt time.Time `gorm:"column:created_at;type:timestamp;not null;default:CURRENT_TIMESTAMP" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;not null;default:CURRENT_TIMESTAMP" json:"updated_at"`

View File

@@ -1,64 +0,0 @@
package model
import "time"
// FriendsStatus 好友关系状态
// @Description 好友关系状态枚举
type FriendsStatus string
const (
// FriendsStatusPending 待处理(已发出请求,对方尚未接受)
FriendsStatusPending FriendsStatus = "pending"
// FriendsStatusAccepted 已互相成为好友
FriendsStatusAccepted FriendsStatus = "accepted"
// FriendsStatusBlocked 屏蔽requester 屏蔽 target单向
FriendsStatusBlocked FriendsStatus = "blocked"
)
// Friend 好友/屏蔽关系记录
// @Description 玩家好友与屏蔽关系数据模型
//
// 设计说明:
// - 采用状态枚举+单条记录模型,区分 pending/accepted/blocked。
// - 屏蔽blocked复用本表requester 为屏蔽发起者target 为被屏蔽者。
// - 好友关系在 accepted 状态下,仍以 requester->target 单条记录表示;
// 当 B 接受 A 的请求时,若不存在 B->A 记录则补建一条 accepted 记录,
// 从而双方在 ListFriends 中都能看到对方。
type Friend struct {
ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"`
RequesterUUID string `gorm:"column:requester_uuid;type:varchar(32);not null;uniqueIndex:uk_friend_pair,priority:1;index:idx_friend_requester_status,priority:1" json:"requester_uuid"`
TargetUUID string `gorm:"column:target_uuid;type:varchar(32);not null;uniqueIndex:uk_friend_pair,priority:2;index:idx_friend_target_status,priority:1" json:"target_uuid"`
Status FriendsStatus `gorm:"column:status;type:varchar(16);not null;default:'pending';index:idx_friend_requester_status,priority:2;index:idx_friend_target_status,priority:2" json:"status"`
CreatedAt time.Time `gorm:"column:created_at;type:timestamp;not null;default:CURRENT_TIMESTAMP" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;not null;default:CURRENT_TIMESTAMP" json:"updated_at"`
}
// TableName 指定表名
func (Friend) TableName() string { return "friends" }
// PlayerAttributes 玩家好友/聊天偏好属性
// @Description 玩家偏好属性数据模型(对应文档 friendsPreferences / profanityFilterPreferences / chatPreferences
type PlayerAttributes struct {
ProfileUUID string `gorm:"column:profile_uuid;type:varchar(32);primaryKey" json:"profile_uuid"`
FriendsEnabled bool `gorm:"column:friends_enabled;not null;default:true" json:"friends_enabled"`
AcceptInvites bool `gorm:"column:accept_invites;not null;default:true" json:"accept_invites"`
ProfanityFilterOn bool `gorm:"column:profanity_filter_on;not null;default:true" json:"profanity_filter_on"`
// TextCommunication 聊天文本通信偏好ENABLED / FRIENDS_ONLY / DISABLED
TextCommunication string `gorm:"column:text_communication;type:varchar(16);not null;default:'ENABLED'" json:"text_communication"`
CreatedAt time.Time `gorm:"column:created_at;type:timestamp;not null;default:CURRENT_TIMESTAMP" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;not null;default:CURRENT_TIMESTAMP" json:"updated_at"`
}
// TableName 指定表名
func (PlayerAttributes) TableName() string { return "player_attributes" }
// DefaultPlayerAttributes 返回某 profile 的默认属性(数据库无记录时使用)
func DefaultPlayerAttributes(profileUUID string) PlayerAttributes {
return PlayerAttributes{
ProfileUUID: profileUUID,
FriendsEnabled: true,
AcceptInvites: true,
ProfanityFilterOn: true,
TextCommunication: "ENABLED",
}
}

View File

@@ -1,49 +0,0 @@
package model
import (
"testing"
)
// TestFriend_TableName 校验 Friend 表名
func TestFriend_TableName(t *testing.T) {
if got := (Friend{}).TableName(); got != "friends" {
t.Errorf("Friend.TableName() = %q, want %q", got, "friends")
}
}
// TestPlayerAttributes_TableName 校验 PlayerAttributes 表名
func TestPlayerAttributes_TableName(t *testing.T) {
if got := (PlayerAttributes{}).TableName(); got != "player_attributes" {
t.Errorf("PlayerAttributes.TableName() = %q, want %q", got, "player_attributes")
}
}
// TestFriendsStatus_Values 校验好友状态枚举值
func TestFriendsStatus_Values(t *testing.T) {
tests := []struct {
got, want FriendsStatus
}{
{FriendsStatusPending, FriendsStatus("pending")},
{FriendsStatusAccepted, FriendsStatus("accepted")},
{FriendsStatusBlocked, FriendsStatus("blocked")},
}
for _, tt := range tests {
if tt.got != tt.want {
t.Errorf("got %q, want %q", tt.got, tt.want)
}
}
}
// TestDefaultPlayerAttributes 校验默认偏好
func TestDefaultPlayerAttributes(t *testing.T) {
d := DefaultPlayerAttributes("abc")
if d.ProfileUUID != "abc" {
t.Errorf("ProfileUUID = %q, want %q", d.ProfileUUID, "abc")
}
if !d.FriendsEnabled || !d.AcceptInvites || !d.ProfanityFilterOn {
t.Errorf("默认偏好应为全部启用: %+v", d)
}
if d.TextCommunication != "ENABLED" {
t.Errorf("TextCommunication = %q, want ENABLED", d.TextCommunication)
}
}

View File

@@ -7,22 +7,15 @@ import (
// Profile Minecraft 档案模型
// @Description Minecraft角色档案数据模型
type Profile struct {
UUID string `gorm:"column:uuid;type:varchar(32);primaryKey" json:"uuid"`
UserID int64 `gorm:"column:user_id;not null;index:idx_profiles_user_created,priority:1" json:"user_id"`
Name string `gorm:"column:name;type:varchar(16);not null;uniqueIndex:idx_profiles_name" json:"name"` // Minecraft 角色名
SkinID *int64 `gorm:"column:skin_id;type:bigint;index:idx_profiles_skin_id" json:"skin_id,omitempty"`
CapeID *int64 `gorm:"column:cape_id;type:bigint;index:idx_profiles_cape_id" json:"cape_id,omitempty"`
// RSA 私钥不返回给前端
RSAPrivateKey string `gorm:"column:rsa_private_key;type:text;not null" json:"-"`
// 玩家证书完整密钥对(持久化以避免每次请求都重新生成 RSA 4096 密钥)
RSAPublicKey string `gorm:"column:rsa_public_key;type:text" json:"-"`
PublicKeySignature string `gorm:"column:public_key_signature;type:text" json:"-"`
PublicKeySignatureV2 string `gorm:"column:public_key_signature_v2;type:text" json:"-"`
KeyExpiresAt *time.Time `gorm:"column:key_expires_at;type:timestamp" json:"-"`
KeyRefreshAt *time.Time `gorm:"column:key_refresh_at;type:timestamp" json:"-"`
LastUsedAt *time.Time `gorm:"column:last_used_at;type:timestamp;index:idx_profiles_last_used,sort:desc" json:"last_used_at,omitempty"`
CreatedAt time.Time `gorm:"column:created_at;type:timestamp;not null;default:CURRENT_TIMESTAMP;index:idx_profiles_user_created,priority:2,sort:desc" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;not null;default:CURRENT_TIMESTAMP" json:"updated_at"`
UUID string `gorm:"column:uuid;type:varchar(36);primaryKey" json:"uuid"`
UserID int64 `gorm:"column:user_id;not null;index:idx_profiles_user_created,priority:1" json:"user_id"`
Name string `gorm:"column:name;type:varchar(16);not null;uniqueIndex:idx_profiles_name" json:"name"` // Minecraft 角色名
SkinID *int64 `gorm:"column:skin_id;type:bigint;index:idx_profiles_skin_id" json:"skin_id,omitempty"`
CapeID *int64 `gorm:"column:cape_id;type:bigint;index:idx_profiles_cape_id" json:"cape_id,omitempty"`
RSAPrivateKey string `gorm:"column:rsa_private_key;type:text;not null" json:"-"` // RSA 私钥不返回给前端
LastUsedAt *time.Time `gorm:"column:last_used_at;type:timestamp;index:idx_profiles_last_used,sort:desc" json:"last_used_at,omitempty"`
CreatedAt time.Time `gorm:"column:created_at;type:timestamp;not null;default:CURRENT_TIMESTAMP;index:idx_profiles_user_created,priority:2,sort:desc" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;not null;default:CURRENT_TIMESTAMP" json:"updated_at"`
// 关联
User *User `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"user,omitempty"`
@@ -76,14 +69,3 @@ type KeyPair struct {
Expiration time.Time `json:"expiration" bson:"expiration"`
Refresh time.Time `json:"refresh" bson:"refresh"`
}
// NameAndId 简化的档案标识响应(文档 2.1 / 2.2 ProfileSearchResultsResponse / NameAndId
// @Description 仅包含档案 UUID 与用户名的最小响应结构
//
// 用于 profiles.getManyByName / profiles.getByName 接口:
// - id档案 UUID32 位无连字符十六进制)
// - name用户名保持存储的大小写
type NameAndId struct {
ID string `json:"id"`
Name string `json:"name"`
}

View File

@@ -1,9 +1,8 @@
package repository
import (
"context"
"carrotskin/internal/model"
"context"
"gorm.io/gorm"
)

View File

@@ -1,212 +0,0 @@
package repository
import (
"context"
"time"
"carrotskin/internal/model"
"gorm.io/gorm"
)
// FriendRepository 好友/屏蔽关系仓储接口
type FriendRepository interface {
// Create 创建好友/屏蔽关系记录
Create(ctx context.Context, friend *model.Friend) error
// FindRelation 查询 requester->target 方向的关系记录
FindRelation(ctx context.Context, requesterUUID, targetUUID string) (*model.Friend, error)
// ListAccepted 返回与 uuid 已互为好友的对端 UUID 集合
// (合并 requester 与 target 两个方向 status=accepted 的记录)
ListAccepted(ctx context.Context, uuid string) ([]string, error)
// ListIncoming 返回收到的 pending 请求发起者 UUID 列表
ListIncoming(ctx context.Context, uuid string) ([]string, error)
// ListOutgoing 返回已发出的 pending 请求目标 UUID 列表
ListOutgoing(ctx context.Context, uuid string) ([]string, error)
// UpdateStatus 更新某条记录的状态
UpdateStatus(ctx context.Context, id int64, status model.FriendsStatus) error
// Delete 删除记录(物理删除,用于 remove/decline/revoke/unblock
Delete(ctx context.Context, id int64) error
// ListBlocked 返回 blocker 屏蔽的 target UUID 列表
ListBlocked(ctx context.Context, blockerUUID string) ([]string, error)
}
// PlayerAttributeRepository 玩家偏好属性仓储接口
type PlayerAttributeRepository interface {
// Get 读取玩家偏好;不存在时返回 model.DefaultPlayerAttributes 的零值结构,错误为 nil
Get(ctx context.Context, profileUUID string) (*model.PlayerAttributes, error)
// Upsert 插入或更新玩家偏好
Upsert(ctx context.Context, attr *model.PlayerAttributes) error
}
// friendRepository FriendRepository 的 GORM 实现
type friendRepository struct {
db *gorm.DB
}
// NewFriendRepository 创建 FriendRepository 实例
func NewFriendRepository(db *gorm.DB) FriendRepository {
return &friendRepository{db: db}
}
func (r *friendRepository) Create(ctx context.Context, friend *model.Friend) error {
return r.db.WithContext(ctx).Create(friend).Error
}
func (r *friendRepository) FindRelation(ctx context.Context, requesterUUID, targetUUID string) (*model.Friend, error) {
var f model.Friend
err := r.db.WithContext(ctx).
Where("requester_uuid = ? AND target_uuid = ?", requesterUUID, targetUUID).
First(&f).Error
return handleNotFoundResult(&f, err)
}
func (r *friendRepository) ListAccepted(ctx context.Context, uuid string) ([]string, error) {
var records []model.Friend
// requester 方向
if err := r.db.WithContext(ctx).
Select("target_uuid").
Where("requester_uuid = ? AND status = ?", uuid, model.FriendsStatusAccepted).
Find(&records).Error; err != nil {
return nil, err
}
result := make([]string, 0, len(records))
for _, r := range records {
result = append(result, r.TargetUUID)
}
// target 方向
records = records[:0]
if err := r.db.WithContext(ctx).
Select("requester_uuid").
Where("target_uuid = ? AND status = ?", uuid, model.FriendsStatusAccepted).
Find(&records).Error; err != nil {
return nil, err
}
for _, r := range records {
result = append(result, r.RequesterUUID)
}
return result, nil
}
func (r *friendRepository) ListIncoming(ctx context.Context, uuid string) ([]string, error) {
var records []model.Friend
err := r.db.WithContext(ctx).
Select("requester_uuid").
Where("target_uuid = ? AND status = ?", uuid, model.FriendsStatusPending).
Find(&records).Error
if err != nil {
return nil, err
}
result := make([]string, 0, len(records))
for _, r := range records {
result = append(result, r.RequesterUUID)
}
return result, nil
}
func (r *friendRepository) ListOutgoing(ctx context.Context, uuid string) ([]string, error) {
var records []model.Friend
err := r.db.WithContext(ctx).
Select("target_uuid").
Where("requester_uuid = ? AND status = ?", uuid, model.FriendsStatusPending).
Find(&records).Error
if err != nil {
return nil, err
}
result := make([]string, 0, len(records))
for _, r := range records {
result = append(result, r.TargetUUID)
}
return result, nil
}
func (r *friendRepository) UpdateStatus(ctx context.Context, id int64, status model.FriendsStatus) error {
return r.db.WithContext(ctx).Model(&model.Friend{}).
Where("id = ?", id).
Update("status", status).Error
}
func (r *friendRepository) Delete(ctx context.Context, id int64) error {
return r.db.WithContext(ctx).Delete(&model.Friend{}, id).Error
}
func (r *friendRepository) ListBlocked(ctx context.Context, blockerUUID string) ([]string, error) {
var records []model.Friend
err := r.db.WithContext(ctx).
Select("target_uuid").
Where("requester_uuid = ? AND status = ?", blockerUUID, model.FriendsStatusBlocked).
Find(&records).Error
if err != nil {
return nil, err
}
result := make([]string, 0, len(records))
for _, r := range records {
result = append(result, r.TargetUUID)
}
return result, nil
}
// playerAttributeRepository PlayerAttributeRepository 的 GORM 实现
type playerAttributeRepository struct {
db *gorm.DB
}
// NewPlayerAttributeRepository 创建 PlayerAttributeRepository 实例
func NewPlayerAttributeRepository(db *gorm.DB) PlayerAttributeRepository {
return &playerAttributeRepository{db: db}
}
func (r *playerAttributeRepository) Get(ctx context.Context, profileUUID string) (*model.PlayerAttributes, error) {
var attr model.PlayerAttributes
err := r.db.WithContext(ctx).
Where("profile_uuid = ?", profileUUID).
First(&attr).Error
if err != nil {
if IsNotFound(err) {
// 不存在时返回默认值
d := model.DefaultPlayerAttributes(profileUUID)
return &d, nil
}
return nil, err
}
return &attr, nil
}
func (r *playerAttributeRepository) Upsert(ctx context.Context, attr *model.PlayerAttributes) error {
now := time.Now()
attr.UpdatedAt = now
// 用 map 显式写出所有字段,规避 gorm 对带 default 标签的零值布尔字段在 Create 时被忽略的问题
fields := map[string]interface{}{
"friends_enabled": attr.FriendsEnabled,
"accept_invites": attr.AcceptInvites,
"profanity_filter_on": attr.ProfanityFilterOn,
"text_communication": attr.TextCommunication,
"updated_at": now,
}
// 优先 UPDATE若影响行数为 0记录不存在再 INSERT
res := r.db.WithContext(ctx).Model(&model.PlayerAttributes{}).
Where("profile_uuid = ?", attr.ProfileUUID).
Updates(fields)
if res.Error != nil {
return res.Error
}
if res.RowsAffected > 0 {
return nil
}
// 不存在 -> 插入;用 map 写入避免零值布尔被 default 覆盖
createFields := map[string]interface{}{
"profile_uuid": attr.ProfileUUID,
"friends_enabled": attr.FriendsEnabled,
"accept_invites": attr.AcceptInvites,
"profanity_filter_on": attr.ProfanityFilterOn,
"text_communication": attr.TextCommunication,
"updated_at": now,
"created_at": now,
}
if err := r.db.WithContext(ctx).Model(&model.PlayerAttributes{}).Create(createFields).Error; err != nil {
// 并发情况下可能唯一键冲突,回退为更新一次
return r.db.WithContext(ctx).Model(&model.PlayerAttributes{}).
Where("profile_uuid = ?", attr.ProfileUUID).
Updates(fields).Error
}
return nil
}

View File

@@ -1,9 +1,8 @@
package repository
import (
"context"
"carrotskin/internal/model"
"context"
)
// UserRepository 用户仓储接口
@@ -12,8 +11,7 @@ type UserRepository interface {
FindByID(ctx context.Context, id int64) (*model.User, error)
FindByUsername(ctx context.Context, username string) (*model.User, error)
FindByEmail(ctx context.Context, email string) (*model.User, error)
FindByIDs(ctx context.Context, ids []int64) ([]*model.User, error) // 批量查询
List(ctx context.Context, page, pageSize int) ([]*model.User, int64, error) // 分页列表(管理员)
FindByIDs(ctx context.Context, ids []int64) ([]*model.User, error) // 批量查询
Update(ctx context.Context, user *model.User) error
UpdateFields(ctx context.Context, id int64, fields map[string]interface{}) error
BatchUpdate(ctx context.Context, ids []int64, fields map[string]interface{}) (int64, error) // 批量更新
@@ -58,24 +56,16 @@ type TextureRepository interface {
Delete(ctx context.Context, id int64) error
BatchDelete(ctx context.Context, ids []int64) (int64, error) // 批量删除
IncrementDownloadCount(ctx context.Context, id int64) error
IncrementFavoriteCount(ctx context.Context, id int64) error
DecrementFavoriteCount(ctx context.Context, id int64) error
CreateDownloadLog(ctx context.Context, log *model.TextureDownloadLog) error
IsFavorited(ctx context.Context, userID, textureID int64) (bool, error)
AddFavorite(ctx context.Context, userID, textureID int64) error
RemoveFavorite(ctx context.Context, userID, textureID int64) error
ToggleFavorite(ctx context.Context, userID, textureID int64) (bool, error)
GetUserFavorites(ctx context.Context, userID int64, page, pageSize int) ([]*model.Texture, int64, error)
CountByUploaderID(ctx context.Context, uploaderID int64) (int64, error)
ListForAdmin(ctx context.Context, page, pageSize int) ([]*model.Texture, int64, error) // 管理员列表(含 Uploader 预加载)
FindByIDForAdmin(ctx context.Context, id int64) (*model.Texture, error) // 管理员查询(无权限过滤)
}
// YggdrasilRepository Yggdrasil仓储接口
type YggdrasilRepository interface {
GetPasswordByID(ctx context.Context, id int64) (string, error)
ResetPassword(ctx context.Context, id int64, password string) error
// Create 创建Yggdrasil密码记录用于首次设置密码
Create(ctx context.Context, yggdrasil *model.Yggdrasil) error
}
// ClientRepository Client仓储接口

View File

@@ -1,12 +1,11 @@
package repository
import (
"carrotskin/internal/model"
"context"
"errors"
"fmt"
"carrotskin/internal/model"
"gorm.io/gorm"
)
@@ -117,13 +116,8 @@ func (r *profileRepository) UpdateLastUsedAt(ctx context.Context, uuid string) e
}
func (r *profileRepository) GetByNames(ctx context.Context, names []string) ([]*model.Profile, error) {
if len(names) == 0 {
return []*model.Profile{}, nil
}
var profiles []*model.Profile
// 与 FindByName 保持一致:使用 LOWER() 做大小写不敏感匹配,
// 客户端按文档会 toLowerCase 规范化用户名后发送。
err := r.db.WithContext(ctx).Where("LOWER(name) IN (?)", names).
err := r.db.WithContext(ctx).Where("name in (?)", names).
Preload("Skin").
Preload("Cape").
Find(&profiles).Error
@@ -137,8 +131,8 @@ func (r *profileRepository) GetKeyPair(ctx context.Context, profileId string) (*
var profile model.Profile
result := r.db.WithContext(ctx).
Select("rsa_private_key", "rsa_public_key", "public_key_signature", "public_key_signature_v2", "key_expires_at", "key_refresh_at").
Where("uuid = ?", profileId).
Select("key_pair").
Where("id = ?", profileId).
First(&profile)
if result.Error != nil {
@@ -148,19 +142,7 @@ func (r *profileRepository) GetKeyPair(ctx context.Context, profileId string) (*
return nil, fmt.Errorf("获取key pair失败: %w", result.Error)
}
keyPair := &model.KeyPair{
PrivateKey: profile.RSAPrivateKey,
PublicKey: profile.RSAPublicKey,
PublicKeySignature: profile.PublicKeySignature,
PublicKeySignatureV2: profile.PublicKeySignatureV2,
}
if profile.KeyExpiresAt != nil {
keyPair.Expiration = *profile.KeyExpiresAt
}
if profile.KeyRefreshAt != nil {
keyPair.Refresh = *profile.KeyRefreshAt
}
return keyPair, nil
return &model.KeyPair{}, nil
}
func (r *profileRepository) UpdateKeyPair(ctx context.Context, profileId string, keyPair *model.KeyPair) error {
@@ -172,15 +154,11 @@ func (r *profileRepository) UpdateKeyPair(ctx context.Context, profileId string,
}
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
result := tx.Model(&model.Profile{}).
Where("uuid = ?", profileId).
Updates(map[string]interface{}{
"rsa_private_key": keyPair.PrivateKey,
"rsa_public_key": keyPair.PublicKey,
"public_key_signature": keyPair.PublicKeySignature,
"public_key_signature_v2": keyPair.PublicKeySignatureV2,
"key_expires_at": keyPair.Expiration,
"key_refresh_at": keyPair.Refresh,
result := tx.Table("profiles").
Where("id = ?", profileId).
UpdateColumns(map[string]interface{}{
"private_key": keyPair.PrivateKey,
"public_key": keyPair.PublicKey,
})
if result.Error != nil {

View File

@@ -98,7 +98,6 @@ func TestProfileRepository_Basic(t *testing.T) {
t.Fatalf("CountByUserID mismatch: %d err=%v", count, err)
}
if err := profileRepo.UpdateLastUsedAt(ctx, "p-uuid"); err != nil {
t.Fatalf("UpdateLastUsedAt err: %v", err)
}
@@ -150,22 +149,20 @@ func TestTextureRepository_Basic(t *testing.T) {
t.Fatalf("FindByHashAndUploaderID mismatch")
}
_ = textureRepo.IncrementFavoriteCount(ctx, tex.ID)
_ = textureRepo.DecrementFavoriteCount(ctx, tex.ID)
_, _ = textureRepo.ToggleFavorite(ctx, u.ID, tex.ID)
favList, _, _ := textureRepo.GetUserFavorites(ctx, u.ID, 1, 10)
if len(favList) == 0 {
t.Fatalf("GetUserFavorites expected at least 1 favorite")
}
_, _ = textureRepo.ToggleFavorite(ctx, u.ID, tex.ID)
favList, _, _ = textureRepo.GetUserFavorites(ctx, u.ID, 1, 10)
if len(favList) != 0 {
t.Fatalf("GetUserFavorites expected 0 favorites after toggle off")
}
_ = textureRepo.IncrementDownloadCount(ctx, tex.ID)
_ = textureRepo.CreateDownloadLog(ctx, &model.TextureDownloadLog{TextureID: tex.ID, UserID: &u.ID, IPAddress: "127.0.0.1"})
// 收藏
_ = textureRepo.AddFavorite(ctx, u.ID, tex.ID)
if fav, err := textureRepo.IsFavorited(ctx, u.ID, tex.ID); err == nil {
if !fav {
t.Fatalf("IsFavorited expected true")
}
} else {
t.Skipf("IsFavorited not supported by sqlite: %v", err)
}
_ = textureRepo.RemoveFavorite(ctx, u.ID, tex.ID)
// 批量更新与删除
if affected, err := textureRepo.BatchUpdate(ctx, []int64{tex.ID}, map[string]interface{}{"name": "tex-new"}); err != nil || affected != 1 {
t.Fatalf("BatchUpdate mismatch, affected=%d err=%v", affected, err)
@@ -187,7 +184,7 @@ func TestTextureRepository_Basic(t *testing.T) {
if list, total, err := textureRepo.Search(ctx, "search", model.TextureTypeCape, true, 1, 10); err != nil || total == 0 || len(list) == 0 {
t.Fatalf("Search mismatch, total=%d len=%d err=%v", total, len(list), err)
}
_ = textureRepo.AddFavorite(ctx, u.ID, tex.ID+1)
_, _ = textureRepo.ToggleFavorite(ctx, u.ID, tex.ID+1)
if favList, total, err := textureRepo.GetUserFavorites(ctx, u.ID, 1, 10); err != nil || total == 0 || len(favList) == 0 {
t.Fatalf("GetUserFavorites mismatch, total=%d len=%d err=%v", total, len(favList), err)
}
@@ -206,7 +203,6 @@ func TestTextureRepository_Basic(t *testing.T) {
_ = textureRepo.Delete(ctx, tex.ID)
}
func TestClientRepository_Basic(t *testing.T) {
db := testutil.NewTestDB(t)
repo := NewClientRepository(db)

View File

@@ -1,9 +1,8 @@
package repository
import (
"context"
"carrotskin/internal/model"
"context"
"gorm.io/gorm"
)
@@ -139,42 +138,52 @@ func (r *textureRepository) IncrementDownloadCount(ctx context.Context, id int64
UpdateColumn("download_count", gorm.Expr("download_count + ?", 1)).Error
}
func (r *textureRepository) IncrementFavoriteCount(ctx context.Context, id int64) error {
return r.db.WithContext(ctx).Model(&model.Texture{}).Where("id = ?", id).
UpdateColumn("favorite_count", gorm.Expr("favorite_count + ?", 1)).Error
}
func (r *textureRepository) DecrementFavoriteCount(ctx context.Context, id int64) error {
return r.db.WithContext(ctx).Model(&model.Texture{}).Where("id = ?", id).
UpdateColumn("favorite_count", gorm.Expr("favorite_count - ?", 1)).Error
}
func (r *textureRepository) CreateDownloadLog(ctx context.Context, log *model.TextureDownloadLog) error {
return r.db.WithContext(ctx).Create(log).Error
}
func (r *textureRepository) IsFavorited(ctx context.Context, userID, textureID int64) (bool, error) {
var count int64
// 使用 Select("1") 优化,只查询是否存在,不需要查询所有字段
err := r.db.WithContext(ctx).Model(&model.UserTextureFavorite{}).
Select("1").
Where("user_id = ? AND texture_id = ?", userID, textureID).
Limit(1).
Count(&count).Error
return count > 0, err
}
func (r *textureRepository) ToggleFavorite(ctx context.Context, userID, textureID int64) (bool, error) {
var isAdded bool
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var count int64
err := tx.Model(&model.UserTextureFavorite{}).
Where("user_id = ? AND texture_id = ?", userID, textureID).
Count(&count).Error
if err != nil {
return err
}
func (r *textureRepository) AddFavorite(ctx context.Context, userID, textureID int64) error {
favorite := &model.UserTextureFavorite{
UserID: userID,
TextureID: textureID,
}
return r.db.WithContext(ctx).Create(favorite).Error
}
if count > 0 {
result := tx.Where("user_id = ? AND texture_id = ?", userID, textureID).
Delete(&model.UserTextureFavorite{})
if result.Error != nil {
return result.Error
}
if result.RowsAffected > 0 {
if err := tx.Model(&model.Texture{}).Where("id = ?", textureID).
UpdateColumn("favorite_count", gorm.Expr("GREATEST(favorite_count - 1, 0)")).Error; err != nil {
return err
}
}
isAdded = false
return nil
}
func (r *textureRepository) RemoveFavorite(ctx context.Context, userID, textureID int64) error {
return r.db.WithContext(ctx).Where("user_id = ? AND texture_id = ?", userID, textureID).
Delete(&model.UserTextureFavorite{}).Error
favorite := &model.UserTextureFavorite{
UserID: userID,
TextureID: textureID,
}
if err := tx.Create(favorite).Error; err != nil {
return err
}
if err := tx.Model(&model.Texture{}).Where("id = ?", textureID).
UpdateColumn("favorite_count", gorm.Expr("favorite_count + 1")).Error; err != nil {
return err
}
isAdded = true
return nil
})
return isAdded, err
}
func (r *textureRepository) GetUserFavorites(ctx context.Context, userID int64, page, pageSize int) ([]*model.Texture, int64, error) {
@@ -211,27 +220,3 @@ func (r *textureRepository) CountByUploaderID(ctx context.Context, uploaderID in
Count(&count).Error
return count, err
}
// ListForAdmin 管理员分页查询材质列表(含 Uploader 预加载,无权限过滤)
func (r *textureRepository) ListForAdmin(ctx context.Context, page, pageSize int) ([]*model.Texture, int64, error) {
var textures []*model.Texture
var total int64
db := r.db.WithContext(ctx).Model(&model.Texture{})
if err := db.Count(&total).Error; err != nil {
return nil, 0, err
}
offset := (page - 1) * pageSize
if err := db.Preload("Uploader").Order("id DESC").Offset(offset).Limit(pageSize).Find(&textures).Error; err != nil {
return nil, 0, err
}
return textures, total, nil
}
// FindByIDForAdmin 管理员查询材质(无权限过滤,用于管理员删除前检查存在性)
func (r *textureRepository) FindByIDForAdmin(ctx context.Context, id int64) (*model.Texture, error) {
var texture model.Texture
err := r.db.WithContext(ctx).Where("id = ?", id).First(&texture).Error
return handleNotFoundResult(&texture, err)
}

View File

@@ -1,11 +1,10 @@
package repository
import (
"carrotskin/internal/model"
"context"
"errors"
"carrotskin/internal/model"
"gorm.io/gorm"
)
@@ -51,23 +50,6 @@ func (r *userRepository) FindByIDs(ctx context.Context, ids []int64) ([]*model.U
return users, err
}
// List 分页查询用户列表(管理员,不过滤状态)
func (r *userRepository) List(ctx context.Context, page, pageSize int) ([]*model.User, int64, error) {
var users []*model.User
var total int64
db := r.db.WithContext(ctx).Model(&model.User{})
if err := db.Count(&total).Error; err != nil {
return nil, 0, err
}
offset := (page - 1) * pageSize
if err := db.Order("id DESC").Offset(offset).Limit(pageSize).Find(&users).Error; err != nil {
return nil, 0, err
}
return users, total, nil
}
func (r *userRepository) Update(ctx context.Context, user *model.User) error {
return r.db.WithContext(ctx).Save(user).Error
}

View File

@@ -1,9 +1,8 @@
package repository
import (
"context"
"carrotskin/internal/model"
"context"
"gorm.io/gorm"
)
@@ -31,7 +30,8 @@ func (r *yggdrasilRepository) ResetPassword(ctx context.Context, id int64, passw
return r.db.WithContext(ctx).Model(&model.Yggdrasil{}).Where("id = ?", id).Update("password", password).Error
}
// Create 创建Yggdrasil密码记录
func (r *yggdrasilRepository) Create(ctx context.Context, yggdrasil *model.Yggdrasil) error {
return r.db.WithContext(ctx).Create(yggdrasil).Error
}

View File

@@ -1,16 +1,15 @@
package service
import (
"carrotskin/pkg/config"
"carrotskin/pkg/redis"
"context"
"errors"
"fmt"
"log"
"time"
"carrotskin/pkg/config"
"carrotskin/pkg/redis"
"carrotskin/pkg/utils"
"github.com/google/uuid"
"github.com/wenlng/go-captcha-assets/resources/imagesv2"
"github.com/wenlng/go-captcha-assets/resources/tiles"
"github.com/wenlng/go-captcha/v2/slide"
@@ -73,15 +72,13 @@ type RedisData struct {
// captchaService CaptchaService的实现
type captchaService struct {
cfg *config.Config
redis *redis.Client
logger *zap.Logger
}
// NewCaptchaService 创建CaptchaService实例
func NewCaptchaService(cfg *config.Config, redisClient *redis.Client, logger *zap.Logger) CaptchaService {
func NewCaptchaService(redisClient *redis.Client, logger *zap.Logger) CaptchaService {
return &captchaService{
cfg: cfg,
redis: redisClient,
logger: logger,
}
@@ -90,7 +87,7 @@ func NewCaptchaService(cfg *config.Config, redisClient *redis.Client, logger *za
// Generate 生成验证码
func (s *captchaService) Generate(ctx context.Context) (masterImg, tileImg, captchaID string, y int, err error) {
// 生成uuid作为验证码进程唯一标识
captchaID = utils.GenerateUUID()
captchaID = uuid.NewString()
if captchaID == "" {
err = errors.New("生成验证码唯一标识失败")
return
@@ -160,7 +157,8 @@ func (s *captchaService) Generate(ctx context.Context) (masterImg, tileImg, capt
// Verify 验证验证码
func (s *captchaService) Verify(ctx context.Context, dx int, captchaID string) (bool, error) {
// 测试环境下直接通过验证
if s.cfg.IsTestEnvironment() {
cfg, err := config.GetConfig()
if err == nil && cfg.IsTestEnvironment() {
return true, nil
}
@@ -182,48 +180,12 @@ func (s *captchaService) Verify(ctx context.Context, dx int, captchaID string) (
ty := redisData.Ty
ok := slide.Validate(dx, ty, tx, ty, paddingValue)
// 验证成功后标记为已验证状态设置5分钟有效期
// 验证后立即删除Redis记录防止重复使用
if ok {
verifiedKey := redisKeyPrefix + "verified:" + captchaID
if err := s.redis.Set(ctx, verifiedKey, "1", 5*time.Minute); err != nil {
s.logger.Warn("设置验证码已验证标记失败", zap.Error(err))
}
// 删除原始验证码记录(防止重复验证)
if err := s.redis.Del(ctx, redisKey); err != nil {
// 记录警告但不影响验证结果
s.logger.Warn("删除验证码Redis记录失败", zap.Error(err))
}
}
return ok, nil
}
// CheckVerified 检查验证码是否已验证仅检查captcha_id
func (s *captchaService) CheckVerified(ctx context.Context, captchaID string) (bool, error) {
// 测试环境下直接通过验证
if s.cfg.IsTestEnvironment() {
return true, nil
}
verifiedKey := redisKeyPrefix + "verified:" + captchaID
exists, err := s.redis.Exists(ctx, verifiedKey)
if err != nil {
return false, fmt.Errorf("检查验证状态失败: %w", err)
}
if exists == 0 {
return false, errors.New("验证码未验证或已过期")
}
return true, nil
}
// ConsumeVerified 消耗已验证的验证码(注册成功后调用)
func (s *captchaService) ConsumeVerified(ctx context.Context, captchaID string) error {
// 测试环境下直接返回成功
if s.cfg.IsTestEnvironment() {
return nil
}
verifiedKey := redisKeyPrefix + "verified:" + captchaID
if err := s.redis.Del(ctx, verifiedKey); err != nil {
s.logger.Warn("删除验证码已验证标记失败", zap.Error(err))
}
return nil
}

View File

@@ -1,11 +1,18 @@
package service
// 通用辅助函数。
//
// 注意:错误定义已统一到 internal/errors 包。
// 原先在此文件重复定义的 ErrProfileNotFound/ErrProfileNoPermission/
// ErrTextureNotFound/ErrTextureNoPermission/ErrUserNotFound 已删除,
// 请使用 internal/errors别名 apperrors中的对应定义。
import (
"errors"
"fmt"
)
// 通用错误
var (
ErrProfileNotFound = errors.New("档案不存在")
ErrProfileNoPermission = errors.New("无权操作此档案")
ErrTextureNotFound = errors.New("材质不存在")
ErrTextureNoPermission = errors.New("无权操作此材质")
ErrUserNotFound = errors.New("用户不存在")
)
// NormalizePagination 规范化分页参数
func NormalizePagination(page, pageSize int) (int, int) {
@@ -20,3 +27,11 @@ func NormalizePagination(page, pageSize int) (int, int) {
}
return page, pageSize
}
// WrapError 包装错误,添加上下文信息
func WrapError(err error, message string) error {
if err == nil {
return nil
}
return fmt.Errorf("%s: %w", message, err)
}

View File

@@ -1,6 +1,7 @@
package service
import (
"errors"
"testing"
)
@@ -29,3 +30,21 @@ func TestNormalizePagination_Basic(t *testing.T) {
})
}
}
// TestWrapError 覆盖 WrapError 的 nil 与非 nil 分支
func TestWrapError(t *testing.T) {
if err := WrapError(nil, "msg"); err != nil {
t.Fatalf("WrapError(nil, ...) 应返回 nil, got=%v", err)
}
orig := errors.New("orig")
wrapped := WrapError(orig, "context")
if wrapped == nil {
t.Fatalf("WrapError 应返回非 nil 错误")
}
if wrapped.Error() == orig.Error() {
t.Fatalf("WrapError 应添加上下文信息, got=%v", wrapped)
}
}

View File

@@ -2,11 +2,10 @@
package service
import (
"context"
"time"
"carrotskin/internal/model"
"carrotskin/pkg/storage"
"context"
"time"
"go.uber.org/zap"
)
@@ -38,11 +37,6 @@ type UserService interface {
// 配置获取
GetMaxProfilesPerUser() int
GetMaxTexturesPerUser() int
// 管理员操作
ListUsers(ctx context.Context, page, pageSize int) ([]*model.User, int64, error)
SetRole(ctx context.Context, userID int64, role string) error
SetStatus(ctx context.Context, userID int64, status int16) error
}
// ProfileService 档案服务接口
@@ -60,14 +54,6 @@ type ProfileService interface {
// 批量查询
GetByNames(ctx context.Context, names []string) ([]*model.Profile, error)
GetByProfileName(ctx context.Context, name string) (*model.Profile, error)
// ProfileSearchByName 按用户名批量查询档案,返回简化的 NameAndId 列表(文档 2.1
// 规范化toLowerCase、空名过滤、每页最多 maxBatch 个限制由本方法在服务端兜底处理。
ProfileSearchByName(ctx context.Context, names []string, maxBatch int) ([]model.NameAndId, error)
// ProfileSearchByNameSingle 按单个用户名查询档案,返回简化的 NameAndId文档 2.2
// 未找到时返回 (nil, nil),符合文档中"客户端返回 Optional.empty()"的契约。
ProfileSearchByNameSingle(ctx context.Context, name string) (*model.NameAndId, error)
}
// TextureService 材质服务接口
@@ -87,18 +73,12 @@ type TextureService interface {
// 限制检查
CheckUploadLimit(ctx context.Context, uploaderID int64, maxTextures int) error
// 管理员操作
ListForAdmin(ctx context.Context, page, pageSize int) ([]*model.Texture, int64, error)
AdminDelete(ctx context.Context, textureID int64) error
IncrementDownload(ctx context.Context, textureID int64) error
}
// TokenService 令牌服务接口
type TokenService interface {
// 令牌管理
Create(ctx context.Context, userID int64, uuid, clientToken string) (*model.Profile, []*model.Profile, string, string, error)
CreateWithProfile(ctx context.Context, userID int64, profileUUID string, clientToken string) (*model.Profile, []*model.Profile, string, string, error)
Validate(ctx context.Context, accessToken, clientToken string) bool
Refresh(ctx context.Context, accessToken, clientToken, selectedProfileID string) (string, string, error)
Invalidate(ctx context.Context, accessToken string)
@@ -119,8 +99,6 @@ type VerificationService interface {
type CaptchaService interface {
Generate(ctx context.Context) (masterImg, tileImg, captchaID string, y int, err error)
Verify(ctx context.Context, dx int, captchaID string) (bool, error)
CheckVerified(ctx context.Context, captchaID string) (bool, error)
ConsumeVerified(ctx context.Context, captchaID string) error
}
// YggdrasilService Yggdrasil服务接口
@@ -138,123 +116,13 @@ type YggdrasilService interface {
// 序列化
SerializeProfile(ctx context.Context, profile model.Profile) map[string]interface{}
SerializeProfileWithUnsigned(ctx context.Context, profile model.Profile, unsigned bool) map[string]interface{}
SerializeUser(ctx context.Context, user *model.User, uuid string) map[string]interface{}
// 证书
GeneratePlayerCertificate(ctx context.Context, uuid string) (*PlayerCertificate, error)
GeneratePlayerCertificate(ctx context.Context, uuid string) (map[string]interface{}, error)
GetPublicKey(ctx context.Context) (string, error)
}
// FriendActionType 好友操作类型(文档 1.3.2
type FriendActionType string
const (
FriendActionAdd FriendActionType = "ADD"
FriendActionRemove FriendActionType = "REMOVE"
)
// FriendActionRequest 好友操作请求(文档 1.3.2
type FriendActionRequest struct {
Name string `json:"name,omitempty"`
ProfileID string `json:"profileId,omitempty"`
UpdateType FriendActionType `json:"updateType"`
}
// FriendDTO 好友条目(文档 1.3.1 FriendDto
type FriendDTO struct {
ProfileID string `json:"profileId"`
Name string `json:"name"`
}
// FriendsListResponse 好友列表响应(文档 1.3.1
type FriendsListResponse struct {
Friends []FriendDTO `json:"friends"`
IncomingRequests []FriendDTO `json:"incomingRequests"`
OutgoingRequests []FriendDTO `json:"outgoingRequests"`
}
// PlayerAttributesRequest 玩家偏好更新请求(文档 1.2.2
type PlayerAttributesRequest struct {
ProfanityFilterPreferences *ProfanityFilterPreferences `json:"profanityFilterPreferences,omitempty"`
FriendsPreferences *FriendsPreferences `json:"friendsPreferences,omitempty"`
}
// ProfanityFilterPreferences 脏词过滤偏好
type ProfanityFilterPreferences struct {
ProfanityFilterOn *bool `json:"profanityFilterOn,omitempty"`
}
// FriendsPreferences 好友偏好
type FriendsPreferences struct {
Friends *string `json:"friends,omitempty"` // ENABLED / DISABLED
AcceptInvites *string `json:"acceptInvites,omitempty"` // ENABLED / DISABLED
}
// PlayerAttributesResponse 玩家属性响应(文档 1.2.1
// 仅实现好友相关字段其它privileges/banStatus 等)不在好友系统范围
type PlayerAttributesResponse struct {
ProfanityFilterPreferences ProfanityFilterPreferencesResp `json:"profanityFilterPreferences"`
FriendsPreferences FriendsPreferencesResp `json:"friendsPreferences"`
ChatPreferences ChatPreferencesResp `json:"chatPreferences"`
}
// ProfanityFilterPreferencesResp 脏词过滤偏好响应
type ProfanityFilterPreferencesResp struct {
ProfanityFilterOn bool `json:"profanityFilterOn"`
}
// FriendsPreferencesResp 好友偏好响应
type FriendsPreferencesResp struct {
Friends string `json:"friends"`
AcceptInvites string `json:"acceptInvites"`
}
// ChatPreferencesResp 聊天偏好响应
type ChatPreferencesResp struct {
TextCommunication string `json:"textCommunication"`
}
// PresenceRequest 在线状态上报请求(文档 1.1
type PresenceRequest struct {
Status string `json:"status"`
}
// PresenceEntry 单个在线玩家状态(文档 1.1
type PresenceEntry struct {
ProfileID string `json:"profileId"`
PMID string `json:"pmid,omitempty"`
Status string `json:"status"`
LastUpdated string `json:"lastUpdated"`
}
// PresenceResponse 在线状态响应(文档 1.1
type PresenceResponse struct {
Presence []PresenceEntry `json:"presence"`
}
// BlockListResponse 屏蔽列表响应(文档 1.6
type BlockListResponse struct {
BlockedProfiles []string `json:"blockedProfiles"`
}
// FriendsService 好友系统服务接口(文档 1.1 / 1.2 / 1.3 / 1.6
type FriendsService interface {
// 好友列表与操作
ListFriends(ctx context.Context, requesterUUID string) (*FriendsListResponse, error)
PerformFriendAction(ctx context.Context, requesterUUID string, req FriendActionRequest) (*FriendsListResponse, error)
// 玩家偏好属性
GetAttributes(ctx context.Context, profileUUID string) (*PlayerAttributesResponse, error)
UpdateAttributes(ctx context.Context, profileUUID string, req PlayerAttributesRequest) error
// 在线状态
UpdatePresence(ctx context.Context, requesterUUID string, status string) (*PresenceResponse, error)
// 屏蔽列表
GetBlocklist(ctx context.Context, blockerUUID string) (*BlockListResponse, error)
}
// SecurityService 安全服务接口
type SecurityService interface {
// 登录安全
@@ -279,7 +147,6 @@ type Services struct {
Captcha CaptchaService
Yggdrasil YggdrasilService
Security SecurityService
Friends FriendsService
}
// ServiceDeps 服务依赖

View File

@@ -5,7 +5,6 @@ import (
"carrotskin/pkg/database"
"context"
"errors"
"strings"
"time"
)
@@ -131,24 +130,6 @@ func (m *MockUserRepository) FindByIDs(ctx context.Context, ids []int64) ([]*mod
return result, nil
}
// List 分页查询用户列表管理员mock 实现)
func (m *MockUserRepository) List(ctx context.Context, page, pageSize int) ([]*model.User, int64, error) {
var all []*model.User
for _, u := range m.users {
all = append(all, u)
}
total := int64(len(all))
offset := (page - 1) * pageSize
if offset >= len(all) {
return []*model.User{}, total, nil
}
end := offset + pageSize
if end > len(all) {
end = len(all)
}
return all[offset:end], total, nil
}
// MockProfileRepository 模拟ProfileRepository
type MockProfileRepository struct {
profiles map[string]*model.Profile
@@ -191,10 +172,8 @@ func (m *MockProfileRepository) FindByName(ctx context.Context, name string) (*m
if m.FailFind {
return nil, errors.New("mock find error")
}
// 与真实仓储一致:大小写不敏感匹配
ln := strings.ToLower(name)
for _, profile := range m.profiles {
if strings.ToLower(profile.Name) == ln {
if profile.Name == name {
return profile, nil
}
}
@@ -246,10 +225,8 @@ func (m *MockProfileRepository) UpdateLastUsedAt(ctx context.Context, uuid strin
func (m *MockProfileRepository) GetByNames(ctx context.Context, names []string) ([]*model.Profile, error) {
var result []*model.Profile
for _, name := range names {
// 与真实仓储一致:大小写不敏感匹配
ln := strings.ToLower(name)
for _, profile := range m.profiles {
if strings.ToLower(profile.Name) == ln {
if profile.Name == name {
result = append(result, profile)
}
}
@@ -414,37 +391,24 @@ func (m *MockTextureRepository) IncrementFavoriteCount(ctx context.Context, id i
return nil
}
func (m *MockTextureRepository) DecrementFavoriteCount(ctx context.Context, id int64) error {
if texture, ok := m.textures[id]; ok && texture.FavoriteCount > 0 {
texture.FavoriteCount--
}
return nil
}
func (m *MockTextureRepository) CreateDownloadLog(ctx context.Context, log *model.TextureDownloadLog) error {
return nil
}
func (m *MockTextureRepository) IsFavorited(ctx context.Context, userID, textureID int64) (bool, error) {
if userFavs, ok := m.favorites[userID]; ok {
return userFavs[textureID], nil
}
return false, nil
}
func (m *MockTextureRepository) AddFavorite(ctx context.Context, userID, textureID int64) error {
func (m *MockTextureRepository) ToggleFavorite(ctx context.Context, userID, textureID int64) (bool, error) {
if m.favorites[userID] == nil {
m.favorites[userID] = make(map[int64]bool)
}
m.favorites[userID][textureID] = true
return nil
}
func (m *MockTextureRepository) RemoveFavorite(ctx context.Context, userID, textureID int64) error {
if userFavs, ok := m.favorites[userID]; ok {
delete(userFavs, textureID)
isFavorited := m.favorites[userID][textureID]
m.favorites[userID][textureID] = !isFavorited
if texture, ok := m.textures[textureID]; ok {
if !isFavorited {
texture.FavoriteCount++
} else if texture.FavoriteCount > 0 {
texture.FavoriteCount--
}
}
return nil
return !isFavorited, nil
}
func (m *MockTextureRepository) GetUserFavorites(ctx context.Context, userID int64, page, pageSize int) ([]*model.Texture, int64, error) {
@@ -497,33 +461,6 @@ func (m *MockTextureRepository) BatchDelete(ctx context.Context, ids []int64) (i
return deleted, nil
}
// ListForAdmin 管理员列表mock 实现)
func (m *MockTextureRepository) ListForAdmin(ctx context.Context, page, pageSize int) ([]*model.Texture, int64, error) {
var all []*model.Texture
for _, t := range m.textures {
all = append(all, t)
}
total := int64(len(all))
offset := (page - 1) * pageSize
if offset >= len(all) {
return []*model.Texture{}, total, nil
}
end := offset + pageSize
if end > len(all) {
end = len(all)
}
return all[offset:end], total, nil
}
// FindByIDForAdmin 管理员查询mock 实现,无权限过滤)
func (m *MockTextureRepository) FindByIDForAdmin(ctx context.Context, id int64) (*model.Texture, error) {
if t, ok := m.textures[id]; ok {
return t, nil
}
return nil, nil
}
// ============================================================================
// Service Mocks
// ============================================================================

View File

@@ -1,6 +1,9 @@
package service
import (
"carrotskin/internal/model"
"carrotskin/internal/repository"
"carrotskin/pkg/database"
"context"
"crypto/rand"
"crypto/rsa"
@@ -8,14 +11,8 @@ import (
"encoding/pem"
"errors"
"fmt"
"strings"
apperrors "carrotskin/internal/errors"
"carrotskin/internal/model"
"carrotskin/internal/repository"
"carrotskin/pkg/database"
"carrotskin/pkg/utils"
"github.com/google/uuid"
"go.uber.org/zap"
"gorm.io/gorm"
)
@@ -67,7 +64,7 @@ func (s *profileService) Create(ctx context.Context, userID int64, name string)
}
// 生成UUID和RSA密钥
profileUUID := utils.GenerateUUID()
profileUUID := uuid.New().String()
privateKey, err := generateRSAPrivateKeyInternal()
if err != nil {
return nil, fmt.Errorf("生成RSA密钥失败: %w", err)
@@ -103,7 +100,7 @@ func (s *profileService) GetByUUID(ctx context.Context, uuid string) (*model.Pro
profile2, err := s.profileRepo.FindByUUID(ctx, uuid)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, apperrors.ErrProfileNotFound
return nil, ErrProfileNotFound
}
return nil, fmt.Errorf("查询档案失败: %w", err)
}
@@ -143,13 +140,13 @@ func (s *profileService) Update(ctx context.Context, uuid string, userID int64,
profile, err := s.profileRepo.FindByUUID(ctx, uuid)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, apperrors.ErrProfileNotFound
return nil, ErrProfileNotFound
}
return nil, fmt.Errorf("查询档案失败: %w", err)
}
if profile.UserID != userID {
return nil, apperrors.ErrProfileNoPermission
return nil, ErrProfileNoPermission
}
// 检查角色名是否重复
@@ -190,13 +187,13 @@ func (s *profileService) Delete(ctx context.Context, uuid string, userID int64)
profile, err := s.profileRepo.FindByUUID(ctx, uuid)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return apperrors.ErrProfileNotFound
return ErrProfileNotFound
}
return fmt.Errorf("查询档案失败: %w", err)
}
if profile.UserID != userID {
return apperrors.ErrProfileNoPermission
return ErrProfileNoPermission
}
if err := s.profileRepo.Delete(ctx, uuid); err != nil {
@@ -241,80 +238,6 @@ func (s *profileService) GetByProfileName(ctx context.Context, name string) (*mo
return profile, nil
}
// ProfileSearchByName 按用户名批量查询档案,返回 NameAndId 列表(文档 2.1
// 实现要点:
// - 客户端会 toLowerCase 规范化用户名,服务端也做一次兜底(结合仓储大小写不敏感查询);
// - 过滤掉空名与重复名;
// - 当 maxBatch > 0 且入参个数超过 maxBatch 时按文档契约返回错误(避免超大查询)。
func (s *profileService) ProfileSearchByName(ctx context.Context, names []string, maxBatch int) ([]model.NameAndId, error) {
// 规范化 + 去重 + 过滤空名
normalized := make([]string, 0, len(names))
seen := make(map[string]struct{}, len(names))
for _, n := range names {
// toLowerCase 兜底,与客户端行为一致
ln := strings.ToLower(strings.TrimSpace(n))
if ln == "" {
continue
}
if _, ok := seen[ln]; ok {
continue
}
seen[ln] = struct{}{}
normalized = append(normalized, ln)
}
if maxBatch > 0 && len(normalized) > maxBatch {
return nil, fmt.Errorf("单次最多查询 %d 个用户名", maxBatch)
}
if len(normalized) == 0 {
return []model.NameAndId{}, nil
}
profiles, err := s.profileRepo.GetByNames(ctx, normalized)
if err != nil {
return nil, fmt.Errorf("查找失败: %w", err)
}
// 映射为 NameAndId仅 id + name保持存储的大小写
result := make([]model.NameAndId, 0, len(profiles))
for _, p := range profiles {
if p == nil {
continue
}
result = append(result, model.NameAndId{
ID: p.UUID,
Name: p.Name,
})
}
return result, nil
}
// ProfileSearchByNameSingle 按单个用户名查询档案,返回 NameAndId文档 2.2
// 实现要点:
// - name 经 toLowerCase + trim 兜底规范化,配合仓储大小写不敏感查询;
// - 空名直接返回 (nil, nil),符合文档"客户端返回 Optional.empty()"的契约;
// - 查询错误或未命中均返回 (nil, nil),仅记日志,不上抛错误(与文档行为一致)。
func (s *profileService) ProfileSearchByNameSingle(ctx context.Context, name string) (*model.NameAndId, error) {
ln := strings.ToLower(strings.TrimSpace(name))
if ln == "" {
return nil, nil
}
profile, err := s.profileRepo.FindByName(ctx, ln)
if err != nil {
// 记录非致命错误但不返回,与文档"任意错误返回 Optional.empty()"保持一致
s.logger.Warn("按用户名查档失败", zap.String("name", name), zap.Error(err))
return nil, nil
}
if profile == nil {
return nil, nil
}
return &model.NameAndId{
ID: profile.UUID,
Name: profile.Name,
}, nil
}
// generateRSAPrivateKeyInternal 生成RSA-2048私钥PEM格式
func generateRSAPrivateKeyInternal() (string, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)

View File

@@ -686,46 +686,4 @@ func TestProfileServiceImpl_CheckLimit_And_GetByNames(t *testing.T) {
if err != nil || p == nil || p.Name != "A" {
t.Fatalf("GetByProfileName 返回错误, profile=%+v, err=%v", p, err)
}
// ProfileSearchByName小写名查询、去重、过滤空名、超限拒单
got, err := svc.ProfileSearchByName(ctx, []string{"a", "A", "b", "", " "}, 10)
if err != nil {
t.Fatalf("ProfileSearchByName 失败: %v", err)
}
if len(got) != 2 {
t.Fatalf("ProfileSearchByName 应去重返回 2 项, got=%d: %+v", len(got), got)
}
byName := make(map[string]string, len(got))
for _, n := range got {
byName[n.Name] = n.ID
}
if byName["A"] != "a" || byName["B"] != "b" {
t.Fatalf("返回的 id/name 映射错误: %+v", byName)
}
// 超过 maxBatch 应报错
if _, err := svc.ProfileSearchByName(ctx, []string{"a", "b", "c"}, 2); err == nil {
t.Fatalf("ProfileSearchByName 超过 maxBatch 应返回错误")
}
// ProfileSearchByNameSingle存在 / 不存在 / 空名
single, err := svc.ProfileSearchByNameSingle(ctx, "a")
if err != nil || single == nil || single.ID != "a" || single.Name != "A" {
t.Fatalf("ProfileSearchByNameSingle 存在用例失败, got=%+v err=%v", single, err)
}
// 小写名应能命中大小写不敏感查询
singleLower, err := svc.ProfileSearchByNameSingle(ctx, "a")
if err != nil || singleLower == nil {
t.Fatalf("ProfileSearchByNameSingle 小写名匹配失败, got=%+v err=%v", singleLower, err)
}
// 不存在
missing, err := svc.ProfileSearchByNameSingle(ctx, "nope")
if err != nil || missing != nil {
t.Fatalf("ProfileSearchByNameSingle 不存在应返回 (nil,nil), got=%+v err=%v", missing, err)
}
// 空名
emptyName, err := svc.ProfileSearchByNameSingle(ctx, " ")
if err != nil || emptyName != nil {
t.Fatalf("ProfileSearchByNameSingle 空名应返回 (nil,nil), got=%+v err=%v", emptyName, err)
}
}

View File

@@ -1,6 +1,9 @@
package service
import (
"carrotskin/internal/model"
"carrotskin/internal/repository"
"carrotskin/pkg/redis"
"context"
"crypto"
"crypto/rand"
@@ -12,13 +15,9 @@ import (
"encoding/pem"
"fmt"
"strconv"
"sync"
"strings"
"time"
"carrotskin/internal/model"
"carrotskin/internal/repository"
"carrotskin/pkg/redis"
"go.uber.org/zap"
)
@@ -38,11 +37,6 @@ type SignatureService struct {
profileRepo repository.ProfileRepository
redis *redis.Client
logger *zap.Logger
// 缓存已解析的根密钥对,避免每次签名都重复 PEM 解析PKCS1 解析开销较大)
rootKeyMu sync.RWMutex
rootPrivateKey *rsa.PrivateKey
rootPublicKeyPEM string
}
// NewSignatureService 创建SignatureService实例
@@ -59,7 +53,7 @@ func NewSignatureService(
}
// NewKeyPair 生成新的RSA密钥对
func (s *SignatureService) NewKeyPair(ctx context.Context) (*model.KeyPair, error) {
func (s *SignatureService) NewKeyPair() (*model.KeyPair, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, KeySize)
if err != nil {
return nil, fmt.Errorf("生成RSA密钥对失败: %w", err)
@@ -91,82 +85,81 @@ func (s *SignatureService) NewKeyPair(ctx context.Context) (*model.KeyPair, erro
refresh := now.AddDate(0, 0, RefreshDays)
// 获取Yggdrasil根密钥并签名公钥
yggPublicKey, yggPrivateKey, err := s.GetOrCreateYggdrasilKeyPair(ctx)
yggPublicKey, yggPrivateKey, err := s.GetOrCreateYggdrasilKeyPair()
if err != nil {
return nil, fmt.Errorf("获取Yggdrasil根密钥失败: %w", err)
}
// 构造签名消息PEM 公钥 + 过期时间戳)
// 构造签名消息
expiresAtMillis := expiration.UnixMilli()
message := make([]byte, 0, len(publicKeyPEM)+20)
message = append(message, publicKeyPEM...)
message = strconv.AppendInt(message, expiresAtMillis, 10)
message := []byte(string(publicKeyPEM) + strconv.FormatInt(expiresAtMillis, 10))
// 使用SHA1withRSA签名
publicKeySignature, err := signWithRootKey(yggPrivateKey, message)
hashed := sha1.Sum(message)
signature, err := rsa.SignPKCS1v15(rand.Reader, yggPrivateKey, crypto.SHA1, hashed[:])
if err != nil {
return nil, fmt.Errorf("签名失败: %w", err)
}
publicKeySignature := base64.StdEncoding.EncodeToString(signature)
// 构造V2签名消息DER编码
publicKeyDER, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return nil, fmt.Errorf("DER编码公钥失败: %w", err)
}
// V2签名timestamp (8 bytes, big endian) + publicKey (DER)
messageV2 := make([]byte, 8+len(publicKeyBytes))
messageV2 := make([]byte, 8+len(publicKeyDER))
binary.BigEndian.PutUint64(messageV2[0:8], uint64(expiresAtMillis))
copy(messageV2[8:], publicKeyBytes)
copy(messageV2[8:], publicKeyDER)
publicKeySignatureV2, err := signWithRootKey(yggPrivateKey, messageV2)
hashedV2 := sha1.Sum(messageV2)
signatureV2, err := rsa.SignPKCS1v15(rand.Reader, yggPrivateKey, crypto.SHA1, hashedV2[:])
if err != nil {
return nil, fmt.Errorf("V2签名失败: %w", err)
}
publicKeySignatureV2 := base64.StdEncoding.EncodeToString(signatureV2)
return &model.KeyPair{
PrivateKey: string(privateKeyPEM),
PublicKey: string(publicKeyPEM),
PublicKeySignature: base64.StdEncoding.EncodeToString(publicKeySignature),
PublicKeySignatureV2: base64.StdEncoding.EncodeToString(publicKeySignatureV2),
PublicKeySignature: publicKeySignature,
PublicKeySignatureV2: publicKeySignatureV2,
YggdrasilPublicKey: yggPublicKey,
Expiration: expiration,
Refresh: refresh,
}, nil
}
// signWithRootKey 使用根密钥对消息做 SHA1withRSA 签名
func signWithRootKey(privateKey *rsa.PrivateKey, message []byte) ([]byte, error) {
hashed := sha1.Sum(message)
return rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA1, hashed[:])
}
// GetOrCreateYggdrasilKeyPair 获取或创建Yggdrasil根密钥对
// 优先使用进程内缓存的已解析私钥缓存未命中时从Redis加载并解析再缓存。
func (s *SignatureService) GetOrCreateYggdrasilKeyPair(ctx context.Context) (string, *rsa.PrivateKey, error) {
// 1. 读缓存(快路径)
s.rootKeyMu.RLock()
if s.rootPrivateKey != nil && s.isRootKeyValid() {
pub := s.rootPublicKeyPEM
priv := s.rootPrivateKey
s.rootKeyMu.RUnlock()
return pub, priv, nil
}
s.rootKeyMu.RUnlock()
func (s *SignatureService) GetOrCreateYggdrasilKeyPair() (string, *rsa.PrivateKey, error) {
ctx := context.Background()
// 2. 缓存未命中,加锁准备从 Redis 加载/生成
s.rootKeyMu.Lock()
defer s.rootKeyMu.Unlock()
// 双重检查:可能在等待锁期间已被其他 goroutine 填充
if s.rootPrivateKey != nil && s.isRootKeyValidLocked() {
return s.rootPublicKeyPEM, s.rootPrivateKey, nil
// 尝试从Redis获取密钥
publicKeyPEM, err := s.redis.Get(ctx, PublicKeyRedisKey)
if err == nil && publicKeyPEM != "" {
privateKeyPEM, err := s.redis.Get(ctx, PrivateKeyRedisKey)
if err == nil && privateKeyPEM != "" {
// 检查密钥是否过期
expStr, err := s.redis.Get(ctx, KeyExpirationRedisKey)
if err == nil && expStr != "" {
expTime, err := time.Parse(time.RFC3339, expStr)
if err == nil && time.Now().Before(expTime) {
// 密钥有效,解析私钥
block, _ := pem.Decode([]byte(privateKeyPEM))
if block != nil {
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err == nil {
s.logger.Info("从Redis加载Yggdrasil根密钥")
return publicKeyPEM, privateKey, nil
}
}
}
}
}
}
// 尝试从Redis获取密钥MGet 一次往返拿三个字段,减少网络往返)
pub, priv, err := s.loadRootKeyFromRedis(ctx)
if err == nil && priv != nil {
s.rootPrivateKey = priv
s.rootPublicKeyPEM = pub
s.logger.Info("从Redis加载Yggdrasil根密钥")
return pub, priv, nil
}
// Redis 没有,生成新的根密钥对
// 生成新的根密钥对
s.logger.Info("生成新的Yggdrasil根密钥对")
privateKey, err := rsa.GenerateKey(rand.Reader, KeySize)
if err != nil {
@@ -185,7 +178,7 @@ func (s *SignatureService) GetOrCreateYggdrasilKeyPair(ctx context.Context) (str
if err != nil {
return "", nil, fmt.Errorf("编码公钥失败: %w", err)
}
publicKeyPEM := string(pem.EncodeToMemory(&pem.Block{
publicKeyPEM = string(pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyBytes,
}))
@@ -204,66 +197,19 @@ func (s *SignatureService) GetOrCreateYggdrasilKeyPair(ctx context.Context) (str
s.logger.Warn("保存密钥过期时间到Redis失败", zap.Error(err))
}
// 缓存已解析的私钥与公钥PEM
s.rootPrivateKey = privateKey
s.rootPublicKeyPEM = publicKeyPEM
return publicKeyPEM, privateKey, nil
}
// loadRootKeyFromRedis 从Redis加载根密钥使用 MGet 单次往返获取三字段
func (s *SignatureService) loadRootKeyFromRedis(ctx context.Context) (string, *rsa.PrivateKey, error) {
results, err := s.redis.MGet(ctx, PublicKeyRedisKey, PrivateKeyRedisKey, KeyExpirationRedisKey).Result()
if err != nil {
return "", nil, err
}
if len(results) < 3 {
return "", nil, fmt.Errorf("MGet 返回字段数不足")
}
publicKeyPEM, _ := results[0].(string)
privateKeyPEM, _ := results[1].(string)
expStr, _ := results[2].(string)
if publicKeyPEM == "" || privateKeyPEM == "" || expStr == "" {
return "", nil, fmt.Errorf("Redis中密钥字段不完整")
}
expTime, err := time.Parse(time.RFC3339, expStr)
if err != nil || !time.Now().Before(expTime) {
return "", nil, fmt.Errorf("密钥已过期或过期时间解析失败")
}
block, _ := pem.Decode([]byte(privateKeyPEM))
if block == nil {
return "", nil, fmt.Errorf("解析PEM私钥失败")
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return "", nil, fmt.Errorf("解析RSA私钥失败: %w", err)
}
return publicKeyPEM, privateKey, nil
}
// isRootKeyValid 在持有读锁时判断缓存密钥是否过期。
// 注意:缓存的私钥本身不带过期时间,过期信息存于 Redis由 loadRootKeyFromRedis 校验)。
// 一旦加载成功即认为在进程生命周期内有效,由 Redis 过期触发重新生成。
func (s *SignatureService) isRootKeyValid() bool {
return s.isRootKeyValidLocked()
}
func (s *SignatureService) isRootKeyValidLocked() bool {
return s.rootPrivateKey != nil && s.rootPublicKeyPEM != ""
}
// GetPublicKeyFromRedis 从Redis获取公钥
func (s *SignatureService) GetPublicKeyFromRedis(ctx context.Context) (string, error) {
func (s *SignatureService) GetPublicKeyFromRedis() (string, error) {
ctx := context.Background()
publicKey, err := s.redis.Get(ctx, PublicKeyRedisKey)
if err != nil {
return "", fmt.Errorf("从Redis获取公钥失败: %w", err)
}
if publicKey == "" {
// 如果Redis中没有创建新的密钥对
publicKey, _, err = s.GetOrCreateYggdrasilKeyPair(ctx)
publicKey, _, err = s.GetOrCreateYggdrasilKeyPair()
if err != nil {
return "", fmt.Errorf("创建新密钥对失败: %w", err)
}
@@ -272,16 +218,59 @@ func (s *SignatureService) GetPublicKeyFromRedis(ctx context.Context) (string, e
}
// SignStringWithSHA1withRSA 使用SHA1withRSA签名字符串
// 使用缓存的已解析根私钥;若缓存为空则触发加载/生成。
func (s *SignatureService) SignStringWithSHA1withRSA(ctx context.Context, data string) (string, error) {
_, privateKey, err := s.GetOrCreateYggdrasilKeyPair(ctx)
if err != nil {
return "", fmt.Errorf("获取签名私钥失败: %w", err)
func (s *SignatureService) SignStringWithSHA1withRSA(data string) (string, error) {
ctx := context.Background()
// 从Redis获取私钥
privateKeyPEM, err := s.redis.Get(ctx, PrivateKeyRedisKey)
if err != nil || privateKeyPEM == "" {
// 如果没有私钥,创建新的密钥对
_, privateKey, err := s.GetOrCreateYggdrasilKeyPair()
if err != nil {
return "", fmt.Errorf("获取私钥失败: %w", err)
}
// 使用新生成的私钥签名
hashed := sha1.Sum([]byte(data))
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA1, hashed[:])
if err != nil {
return "", fmt.Errorf("签名失败: %w", err)
}
return base64.StdEncoding.EncodeToString(signature), nil
}
signature, err := signWithRootKey(privateKey, []byte(data))
// 解析PEM格式的私钥
block, _ := pem.Decode([]byte(privateKeyPEM))
if block == nil {
return "", fmt.Errorf("解析PEM私钥失败")
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return "", fmt.Errorf("解析RSA私钥失败: %w", err)
}
// 签名
hashed := sha1.Sum([]byte(data))
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA1, hashed[:])
if err != nil {
return "", fmt.Errorf("签名失败: %w", err)
}
return base64.StdEncoding.EncodeToString(signature), nil
}
// FormatPublicKey 格式化公钥为单行格式去除PEM头尾和换行符
func FormatPublicKey(publicKeyPEM string) string {
// 移除PEM格式的头尾
lines := strings.Split(publicKeyPEM, "\n")
var keyLines []string
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if trimmed != "" &&
!strings.HasPrefix(trimmed, "-----BEGIN") &&
!strings.HasPrefix(trimmed, "-----END") {
keyLines = append(keyLines, trimmed)
}
}
return strings.Join(keyLines, "")
}

View File

@@ -1,403 +0,0 @@
package service
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/base64"
"encoding/binary"
"encoding/pem"
"fmt"
"strconv"
"strings"
"sync"
"testing"
pkgRedis "carrotskin/pkg/redis"
miniredis "github.com/alicebob/miniredis/v2"
goRedis "github.com/redis/go-redis/v9"
"go.uber.org/zap"
)
// newTestSignatureService 构造一个基于 miniredis 的 SignatureService用于测试。
// 返回服务实例与清理函数。
func newTestSignatureService(t *testing.T) (*SignatureService, *miniredis.Miniredis, func()) {
t.Helper()
mr, err := miniredis.Run()
if err != nil {
t.Fatalf("启动 miniredis 失败: %v", err)
}
rdb := goRedis.NewClient(&goRedis.Options{Addr: mr.Addr()})
client := &pkgRedis.Client{Client: rdb}
svc := NewSignatureService(nil, client, zap.NewNop())
cleanup := func() {
_ = rdb.Close()
mr.Close()
}
return svc, mr, cleanup
}
// TestSignatureService_SignString_Deterministic 验证 SHA1withRSA 签名的确定性:
// 相同 data + 相同根密钥应产生完全相同的签名PKCS#1v1.5 非随机化)。
// 这也是本次重构(缓存已解析私钥)后输出与重构前一致的核心保证。
func TestSignatureService_SignString_Deterministic(t *testing.T) {
svc, _, cleanup := newTestSignatureService(t)
defer cleanup()
ctx := context.Background()
// 首次签名会生成并缓存根密钥
sig1, err := svc.SignStringWithSHA1withRSA(ctx, "test-data-123")
if err != nil {
t.Fatalf("首次签名失败: %v", err)
}
// 第二次签名应命中缓存的已解析私钥,输出必须与首次完全一致
sig2, err := svc.SignStringWithSHA1withRSA(ctx, "test-data-123")
if err != nil {
t.Fatalf("第二次签名失败: %v", err)
}
if sig1 != sig2 {
t.Fatalf("签名不确定sig1=%q sig2=%q", sig1, sig2)
}
// 不同数据应产生不同签名
sig3, err := svc.SignStringWithSHA1withRSA(ctx, "different-data")
if err != nil {
t.Fatalf("不同数据签名失败: %v", err)
}
if sig1 == sig3 {
t.Fatal("不同数据的签名不应相同")
}
}
// TestSignatureService_SignString_MatchesReference 验证重构后的签名与
// 重构前的参考实现(直接从 Redis 读取私钥 PEM 并解析、逐次签名)产生相同字节序列。
// 这是签名一致性的回归测试:只要 data 与根私钥相同,新旧实现输出一致。
func TestSignatureService_SignString_MatchesReference(t *testing.T) {
svc, mr, cleanup := newTestSignatureService(t)
defer cleanup()
ctx := context.Background()
// 触发根密钥生成并写入 miniredis
if _, err := svc.SignStringWithSHA1withRSA(ctx, "consistency-check"); err != nil {
t.Fatalf("触发根密钥生成失败: %v", err)
}
// 从 miniredis 读取根私钥 PEM模拟重构前每次签名都重新解析的逻辑
privPEM, err := mr.Get(PrivateKeyRedisKey)
if err != nil {
t.Fatalf("读取根私钥失败: %v", err)
}
cases := []string{
"",
"a",
strings.Repeat("x", 1024),
"eyJ0aW1lc3RhbXAiOjE3MDAwMDAwMDAwMDAsInByb2ZpbGVJZCI6ImFiYzEyIiwicHJvZmlsZU5hbWUiOiJUZXN0In0=",
}
for _, data := range cases {
// 重构后实现
got, err := svc.SignStringWithSHA1withRSA(ctx, data)
if err != nil {
t.Fatalf("SignStringWithSHA1withRSA(%q) 失败: %v", data, err)
}
// 参考实现重构前逻辑pem.Decode + ParsePKCS1PrivateKey + SignPKCS1v15
block, _ := pem.Decode([]byte(privPEM))
if block == nil {
t.Fatalf("参考实现解析 PEM 失败")
}
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
t.Fatalf("参考实现解析 RSA 私钥失败: %v", err)
}
hashed := sha1.Sum([]byte(data))
sig, err := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA1, hashed[:])
if err != nil {
t.Fatalf("参考实现签名失败: %v", err)
}
want := base64.StdEncoding.EncodeToString(sig)
if got != want {
t.Fatalf("签名与参考实现不一致 data=%q\n got=%q\nwant=%q", data, got, want)
}
}
}
// TestSignatureService_RootKeyCachedAcrossReloads 验证:
// 同一进程内多次 GetOrCreateYggdrasilKeyPair 返回同一已解析私钥实例(缓存生效),
// 且不重复访问 Redis。
func TestSignatureService_RootKeyCachedAcrossReloads(t *testing.T) {
svc, mr, cleanup := newTestSignatureService(t)
defer cleanup()
ctx := context.Background()
// 首次生成
pub1, priv1, err := svc.GetOrCreateYggdrasilKeyPair(ctx)
if err != nil {
t.Fatalf("首次 GetOrCreate 失败: %v", err)
}
// 第二次应命中缓存,返回同一私钥指针
pub2, priv2, err := svc.GetOrCreateYggdrasilKeyPair(ctx)
if err != nil {
t.Fatalf("第二次 GetOrCreate 失败: %v", err)
}
if priv1 != priv2 {
t.Fatal("缓存未命中:返回了不同的私钥实例")
}
if pub1 != pub2 {
t.Fatal("公钥 PEM 不一致")
}
// Redis 仅应被写入一次(首次生成);记录当前 key 数量,再次调用不应增加
keysBefore := len(mr.Keys())
_, _, _ = svc.GetOrCreateYggdrasilKeyPair(ctx)
if got := len(mr.Keys()); got != keysBefore {
t.Fatalf("缓存命中后仍写入 Rediskeys before=%d after=%d", keysBefore, got)
}
}
// TestSignatureService_NewKeyPair_SignatureVerifies 验证 NewKeyPair 生成的
// publicKeySignature / publicKeySignatureV2 能用根公钥正确验签,
// 且消息构造与重构前格式一致PEM公钥+时间戳DER公钥+时间戳)。
func TestSignatureService_NewKeyPair_SignatureVerifies(t *testing.T) {
svc, mr, cleanup := newTestSignatureService(t)
defer cleanup()
ctx := context.Background()
kp, err := svc.NewKeyPair(ctx)
if err != nil {
t.Fatalf("NewKeyPair 失败: %v", err)
}
// 取根公钥用于验签
rootPubPEM, err := mr.Get(PublicKeyRedisKey)
if err != nil {
t.Fatalf("读取根公钥失败: %v", err)
}
block, _ := pem.Decode([]byte(rootPubPEM))
if block == nil {
t.Fatal("解析根公钥 PEM 失败")
}
rootPub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
t.Fatalf("解析根公钥失败: %v", err)
}
rsaRootPub, ok := rootPub.(*rsa.PublicKey)
if !ok {
t.Fatal("根公钥不是 RSA 公钥")
}
expiresAtMillis := kp.Expiration.UnixMilli()
// V1 消息:重构前为 string(publicKeyPEM) + strconv.FormatInt(expiresAtMillis, 10)
// 重构后用 append 拼接,字节序列应完全一致
pubPEM := []byte(kp.PublicKey)
v1Message := make([]byte, 0, len(pubPEM)+20)
v1Message = append(v1Message, pubPEM...)
v1Message = strconv.AppendInt(v1Message, expiresAtMillis, 10)
sig1, err := base64.StdEncoding.DecodeString(kp.PublicKeySignature)
if err != nil {
t.Fatalf("解码 publicKeySignature 失败: %v", err)
}
hashed1 := sha1.Sum(v1Message)
if err := rsa.VerifyPKCS1v15(rsaRootPub, crypto.SHA1, hashed1[:], sig1); err != nil {
t.Fatalf("V1 签名验签失败: %v", err)
}
// V2 消息:重构前为 timestamp(8 BE) + 玩家公钥 DER
// 玩家公钥 DER 来自 kp.PublicKey 的 PEM 解码
playerBlock, _ := pem.Decode([]byte(kp.PublicKey))
if playerBlock == nil {
t.Fatal("解析玩家公钥 PEM 失败")
}
playerDER := playerBlock.Bytes // PKIX 编码的 SubjectPublicKeyInfo DER
v2Message := make([]byte, 8+len(playerDER))
binary.BigEndian.PutUint64(v2Message[0:8], uint64(expiresAtMillis))
copy(v2Message[8:], playerDER)
sig2, err := base64.StdEncoding.DecodeString(kp.PublicKeySignatureV2)
if err != nil {
t.Fatalf("解码 publicKeySignatureV2 失败: %v", err)
}
hashed2 := sha1.Sum(v2Message)
if err := rsa.VerifyPKCS1v15(rsaRootPub, crypto.SHA1, hashed2[:], sig2); err != nil {
t.Fatalf("V2 签名验签失败: %v", err)
}
}
// TestSignatureService_NewKeyPair_V1MessageBytes 验证 V1 消息字节构造与重构前完全一致。
// 重构前:[]byte(string(publicKeyPEM) + strconv.FormatInt(expiresAtMillis, 10))
// 重构后append(publicKeyPEM...); strconv.AppendInt(msg, expiresAtMillis, 10)
func TestSignatureService_NewKeyPair_V1MessageBytes(t *testing.T) {
// 构造一个固定的 PEM 公钥与时间戳,对比两种构造方式的字节
pubPEM := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: []byte("dummy-der-bytes"),
})
expiresAtMillis := int64(1700000000000)
oldStyle := []byte(string(pubPEM) + strconv.FormatInt(expiresAtMillis, 10))
newStyle := make([]byte, 0, len(pubPEM)+20)
newStyle = append(newStyle, pubPEM...)
newStyle = strconv.AppendInt(newStyle, expiresAtMillis, 10)
if string(oldStyle) != string(newStyle) {
t.Fatalf("V1 消息字节不一致\n old=%q\n new=%q", oldStyle, newStyle)
}
}
// TestSignatureService_GetOrCreateYggdrasilKeyPair_LoadsFromRedis 验证:
// 当进程内缓存为空(新实例)但 Redis 中已有有效密钥时,能正确加载而非重新生成。
// 使用同一 miniredis 实例,避免新旧实例切换时数据丢失。
func TestSignatureService_GetOrCreateYggdrasilKeyPair_LoadsFromRedis(t *testing.T) {
mr, err := miniredis.Run()
if err != nil {
t.Fatalf("启动 miniredis 失败: %v", err)
}
t.Cleanup(mr.Close)
rdb := goRedis.NewClient(&goRedis.Options{Addr: mr.Addr()})
t.Cleanup(func() { _ = rdb.Close() })
client := &pkgRedis.Client{Client: rdb}
ctx := context.Background()
// 实例1 生成根密钥(写入 miniredis
svc1 := NewSignatureService(nil, client, zap.NewNop())
pub1, priv1, err := svc1.GetOrCreateYggdrasilKeyPair(ctx)
if err != nil {
t.Fatalf("实例1生成失败: %v", err)
}
// 新建实例2缓存为空但 Redis 中已有密钥
svc2 := NewSignatureService(nil, client, zap.NewNop())
pub2, priv2, err := svc2.GetOrCreateYggdrasilKeyPair(ctx)
if err != nil {
t.Fatalf("实例2加载失败: %v", err)
}
if pub1 != pub2 {
t.Fatal("从 Redis 加载的公钥 PEM 不一致")
}
// 加载的私钥应与原始私钥在数学上等价N 相同)
if priv1.N.Cmp(priv2.N) != 0 {
t.Fatal("从 Redis 加载的私钥与原始私钥不匹配")
}
}
// TestSignatureService_SignConcurrent 验证签名缓存层在并发下的正确性(无数据竞争)。
func TestSignatureService_SignConcurrent(t *testing.T) {
svc, _, cleanup := newTestSignatureService(t)
defer cleanup()
ctx := context.Background()
// 先生成根密钥
seed, err := svc.SignStringWithSHA1withRSA(ctx, "seed")
if err != nil {
t.Fatalf("种子签名失败: %v", err)
}
const n = 32
var wg sync.WaitGroup
errs := make(chan error, n)
sigs := make(chan string, n)
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
defer wg.Done()
sig, err := svc.SignStringWithSHA1withRSA(ctx, "seed")
if err != nil {
errs <- err
return
}
sigs <- sig
}()
}
wg.Wait()
close(errs)
close(sigs)
for err := range errs {
t.Fatalf("并发签名出错: %v", err)
}
for sig := range sigs {
if sig != seed {
t.Fatalf("并发签名结果与预期不一致got=%q want=%q", sig, seed)
}
}
}
// TestSignatureService_KeyPairFieldsPopulated 验证 NewKeyPair 返回的 KeyPair 字段完整。
func TestSignatureService_KeyPairFieldsPopulated(t *testing.T) {
svc, _, cleanup := newTestSignatureService(t)
defer cleanup()
ctx := context.Background()
kp, err := svc.NewKeyPair(ctx)
if err != nil {
t.Fatalf("NewKeyPair 失败: %v", err)
}
checks := []struct {
name string
got string
}{
{"PrivateKey", kp.PrivateKey},
{"PublicKey", kp.PublicKey},
{"PublicKeySignature", kp.PublicKeySignature},
{"PublicKeySignatureV2", kp.PublicKeySignatureV2},
{"YggdrasilPublicKey", kp.YggdrasilPublicKey},
}
for _, c := range checks {
if c.got == "" {
t.Errorf("KeyPair.%s 为空", c.name)
}
}
if kp.Expiration.IsZero() || kp.Refresh.IsZero() {
t.Error("KeyPair.Expiration/Refresh 未设置")
}
if !kp.Refresh.Before(kp.Expiration) {
t.Error("Refresh 应早于 Expiration")
}
}
// 确保引用的包被使用(避免未使用导入在编辑后报错)
var _ = fmt.Sprintf
// BenchmarkSignStringWithSHA1withRSA 衡量缓存命中路径的签名性能(无 PEM 解析、无 Redis 往返)。
func BenchmarkSignStringWithSHA1withRSA(b *testing.B) {
mr, err := miniredis.Run()
if err != nil {
b.Fatalf("启动 miniredis 失败: %v", err)
}
defer mr.Close()
rdb := goRedis.NewClient(&goRedis.Options{Addr: mr.Addr()})
defer func() { _ = rdb.Close() }()
client := &pkgRedis.Client{Client: rdb}
ctx := context.Background()
svc := NewSignatureService(nil, client, zap.NewNop())
// 预热:生成根密钥并填充缓存
if _, err := svc.SignStringWithSHA1withRSA(ctx, "warmup"); err != nil {
b.Fatalf("预热失败: %v", err)
}
data := strings.Repeat("x", 256)
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err := svc.SignStringWithSHA1withRSA(ctx, data); err != nil {
b.Fatalf("签名失败: %v", err)
}
}
}

View File

@@ -2,6 +2,10 @@ package service
import (
"bytes"
"carrotskin/internal/model"
"carrotskin/internal/repository"
"carrotskin/pkg/database"
"carrotskin/pkg/storage"
"context"
"crypto/sha256"
"encoding/hex"
@@ -9,16 +13,8 @@ import (
"fmt"
"path/filepath"
"strings"
"time"
apperrors "carrotskin/internal/errors"
"carrotskin/internal/model"
"carrotskin/internal/repository"
"carrotskin/pkg/database"
"carrotskin/pkg/storage"
"go.uber.org/zap"
"gorm.io/gorm"
)
// textureService TextureService的实现
@@ -30,7 +26,6 @@ type textureService struct {
cacheKeys *database.CacheKeyBuilder
cacheInv *database.CacheInvalidator
logger *zap.Logger
db *gorm.DB
}
// NewTextureService 创建TextureService实例
@@ -40,7 +35,6 @@ func NewTextureService(
storageClient *storage.StorageClient,
cacheManager *database.CacheManager,
logger *zap.Logger,
db *gorm.DB,
) TextureService {
return &textureService{
textureRepo: textureRepo,
@@ -50,7 +44,6 @@ func NewTextureService(
cacheKeys: database.NewCacheKeyBuilder(""),
cacheInv: database.NewCacheInvalidator(cacheManager),
logger: logger,
db: db,
}
}
@@ -69,7 +62,7 @@ func (s *textureService) GetByID(ctx context.Context, id int64) (*model.Texture,
return nil, err
}
if texture2 == nil {
return nil, apperrors.ErrTextureNotFound
return nil, ErrTextureNotFound
}
if texture2.Status == -1 {
return nil, errors.New("材质已删除")
@@ -87,7 +80,7 @@ func (s *textureService) GetByID(ctx context.Context, id int64) (*model.Texture,
return nil, err
}
if texture2 == nil {
return nil, apperrors.ErrTextureNotFound
return nil, ErrTextureNotFound
}
if texture2.Status == -1 {
return nil, errors.New("材质已删除")
@@ -116,7 +109,7 @@ func (s *textureService) GetByHash(ctx context.Context, hash string) (*model.Tex
return nil, err
}
if texture2 == nil {
return nil, apperrors.ErrTextureNotFound
return nil, ErrTextureNotFound
}
if texture2.Status == -1 {
return nil, errors.New("材质已删除")
@@ -169,10 +162,10 @@ func (s *textureService) Update(ctx context.Context, textureID, uploaderID int64
return nil, err
}
if texture == nil {
return nil, apperrors.ErrTextureNotFound
return nil, ErrTextureNotFound
}
if texture.UploaderID != uploaderID {
return nil, apperrors.ErrTextureNoPermission
return nil, ErrTextureNoPermission
}
// 更新字段
@@ -207,10 +200,10 @@ func (s *textureService) Delete(ctx context.Context, textureID, uploaderID int64
return err
}
if texture == nil {
return apperrors.ErrTextureNotFound
return ErrTextureNotFound
}
if texture.UploaderID != uploaderID {
return apperrors.ErrTextureNoPermission
return ErrTextureNoPermission
}
err = s.textureRepo.Delete(ctx, textureID)
@@ -226,57 +219,22 @@ func (s *textureService) Delete(ctx context.Context, textureID, uploaderID int64
}
func (s *textureService) ToggleFavorite(ctx context.Context, userID, textureID int64) (bool, error) {
// 确保材质存在
texture, err := s.textureRepo.FindByID(ctx, textureID)
if err != nil {
return false, err
}
if texture == nil {
return false, apperrors.ErrTextureNotFound
if texture == nil || texture.Status != 1 || !texture.IsPublic {
return false, ErrTextureNotFound
}
// 在事务中执行"切换收藏 + 增减计数"两步,保证数据一致性
// 注意s.db 在部分单元测试中可能为 nil此时跳过事务直接执行
// (生产环境 db 永远非空mock repo 本就不是真事务,降级不影响一致性)
var favorited bool
toggle := func() error {
isFav, err := s.textureRepo.IsFavorited(ctx, userID, textureID)
if err != nil {
return err
}
if isFav {
// 已收藏 -> 取消收藏
if err := s.textureRepo.RemoveFavorite(ctx, userID, textureID); err != nil {
return err
}
if err := s.textureRepo.DecrementFavoriteCount(ctx, textureID); err != nil {
return err
}
favorited = false
return nil
}
// 未收藏 -> 添加收藏
if err := s.textureRepo.AddFavorite(ctx, userID, textureID); err != nil {
return err
}
if err := s.textureRepo.IncrementFavoriteCount(ctx, textureID); err != nil {
return err
}
favorited = true
return nil
}
if s.db != nil {
err = database.TransactionWithTimeout(ctx, s.db, 5*time.Second, func(tx *gorm.DB) error {
return toggle()
})
} else {
err = toggle()
}
isAdded, err := s.textureRepo.ToggleFavorite(ctx, userID, textureID)
if err != nil {
return false, err
}
return favorited, nil
s.cacheInv.BatchInvalidate(ctx, s.cacheKeys.UserFavoritesPattern(userID))
return isAdded, nil
}
func (s *textureService) GetUserFavorites(ctx context.Context, userID int64, page, pageSize int) ([]*model.Texture, int64, error) {
@@ -302,7 +260,7 @@ func (s *textureService) UploadTexture(ctx context.Context, uploaderID int64, na
// 验证用户存在
user, err := s.userRepo.FindByID(ctx, uploaderID)
if err != nil || user == nil {
return nil, apperrors.ErrUserNotFound
return nil, ErrUserNotFound
}
// 验证文件大小和扩展名
@@ -355,10 +313,10 @@ func (s *textureService) UploadTexture(ctx context.Context, uploaderID int64, na
}
// 生成对象名称(路径)
// 格式: type/hash[:2]/hash
// 使用哈希值作为文件名,不带扩展名
// 格式: hash/{hash[:2]}/{hash[2:4]}/{hash}.png
// 使用哈希值作为路径,避免重复存储相同文件
textureTypeFolder := strings.ToLower(textureType)
objectName := fmt.Sprintf("%s/%s", textureTypeFolder, hash)
objectName := fmt.Sprintf("%s/%s/%s/%s/%s%s", textureTypeFolder, hash[:2], hash[2:4], hash, hash, ext)
// 上传文件
reader := bytes.NewReader(fileData)
@@ -428,28 +386,3 @@ func parseTextureTypeInternal(textureType string) (model.TextureType, error) {
return "", errors.New("无效的材质类型")
}
}
// ==================== 管理员操作 ====================
// ListForAdmin 分页查询材质列表(管理员,含 Uploader 预加载)
func (s *textureService) ListForAdmin(ctx context.Context, page, pageSize int) ([]*model.Texture, int64, error) {
page, pageSize = NormalizePagination(page, pageSize)
return s.textureRepo.ListForAdmin(ctx, page, pageSize)
}
// AdminDelete 管理员删除材质(无权限校验)
func (s *textureService) AdminDelete(ctx context.Context, textureID int64) error {
texture, err := s.textureRepo.FindByIDForAdmin(ctx, textureID)
if err != nil {
return err
}
if texture == nil {
return apperrors.ErrTextureNotFound
}
return s.textureRepo.Delete(ctx, textureID)
}
// IncrementDownload 增加下载计数CustomSkinAPI 等场景使用)
func (s *textureService) IncrementDownload(ctx context.Context, textureID int64) error {
return s.textureRepo.IncrementDownloadCount(ctx, textureID)
}

View File

@@ -3,19 +3,12 @@ package service
import (
"carrotskin/internal/model"
"context"
"crypto/sha256"
"encoding/hex"
"strings"
"testing"
"go.uber.org/zap"
)
// sha256Hex 计算给定数据的 SHA-256 十六进制字符串
func sha256Hex(data []byte) string {
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:])
}
// TestTextureService_TypeValidation 测试材质类型验证
func TestTextureService_TypeValidation(t *testing.T) {
tests := []struct {
@@ -502,87 +495,84 @@ func TestTextureServiceImpl_Create(t *testing.T) {
_ = userRepo.Create(context.Background(), testUser)
cacheManager := NewMockCacheManager()
textureService := NewTextureService(textureRepo, userRepo, nil, cacheManager, logger, nil)
// 构造一份符合 service 大小校验(>=512B的 PNG 文件数据
pngFileData := make([]byte, 1024)
for i := range pngFileData {
pngFileData[i] = byte(i % 256)
}
// 计算其真实 SHA-256用于 mock 预置与命中分支测试
existingHash := sha256Hex(pngFileData)
_ = textureRepo.Create(context.Background(), &model.Texture{
ID: 100,
UploaderID: 1,
Name: "ExistingTexture",
Hash: existingHash,
URL: "https://example.com/existing.png",
})
textureService := NewTextureService(textureRepo, userRepo, nil, cacheManager, logger)
tests := []struct {
name string
uploaderID int64
textureName string
textureType string
fileData []byte
hash string
wantErr bool
errContains string
setupMocks func()
}{
{
name: " Hash 已存在 -> 复用 URL",
name: "正常创建SKIN材质",
uploaderID: 1,
textureName: "TestSkin",
textureType: "SKIN",
fileData: pngFileData, // hash 命中预置记录
hash: "unique-hash-1",
wantErr: false,
},
{
name: "Hash 不存在且 storage 为 nil -> 存储不可用",
name: "正常创建CAPE材质",
uploaderID: 1,
textureName: "NewCape",
textureName: "TestCape",
textureType: "CAPE",
fileData: make([]byte, 1024), // 不同内容hash 不会命中
wantErr: true,
errContains: "存储服务不可用",
hash: "unique-hash-2",
wantErr: false,
},
{
name: "用户不存在",
uploaderID: 999,
textureName: "TestTexture",
textureType: "SKIN",
fileData: pngFileData,
hash: "unique-hash-3",
wantErr: true,
},
{
name: "材质Hash已存在",
uploaderID: 1,
textureName: "DuplicateTexture",
textureType: "SKIN",
hash: "existing-hash",
wantErr: false,
setupMocks: func() {
_ = textureRepo.Create(context.Background(), &model.Texture{
ID: 100,
UploaderID: 1,
Name: "ExistingTexture",
Hash: "existing-hash",
})
},
},
{
name: "无效的材质类型",
uploaderID: 1,
textureName: "InvalidTypeTexture",
textureType: "INVALID",
fileData: pngFileData,
hash: "unique-hash-4",
wantErr: true,
errContains: "无效的材质类型",
},
{
name: "文件过小",
uploaderID: 1,
textureName: "TooSmall",
textureType: "SKIN",
fileData: []byte("tiny"),
wantErr: true,
errContains: "文件大小必须在",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.setupMocks != nil {
tt.setupMocks()
}
ctx := context.Background()
// UploadTexture需要文件数据这里创建一个简单的测试数据
fileData := []byte(strings.Repeat("x", 512))
texture, err := textureService.UploadTexture(
ctx,
tt.uploaderID,
tt.textureName,
"Test description",
tt.textureType,
tt.fileData,
fileData,
"test.png",
true,
false,
@@ -596,17 +586,17 @@ func TestTextureServiceImpl_Create(t *testing.T) {
if tt.errContains != "" && !containsString(err.Error(), tt.errContains) {
t.Errorf("错误信息应包含 %q, 实际为: %v", tt.errContains, err.Error())
}
return
}
if err != nil {
t.Errorf("不期望返回错误: %v", err)
return
}
if texture == nil {
t.Fatal("返回的Texture不应为nil")
}
if texture.Name != tt.textureName {
t.Errorf("Texture名称不匹配: got %v, want %v", texture.Name, tt.textureName)
} else {
if err != nil {
t.Errorf("不期望返回错误: %v", err)
return
}
if texture == nil {
t.Error("返回的Texture不应为nil")
}
if texture.Name != tt.textureName {
t.Errorf("Texture名称不匹配: got %v, want %v", texture.Name, tt.textureName)
}
}
})
}
@@ -628,7 +618,7 @@ func TestTextureServiceImpl_GetByID(t *testing.T) {
_ = textureRepo.Create(context.Background(), testTexture)
cacheManager := NewMockCacheManager()
textureService := NewTextureService(textureRepo, userRepo, nil, cacheManager, logger, nil)
textureService := NewTextureService(textureRepo, userRepo, nil, cacheManager, logger)
tests := []struct {
name string
@@ -686,7 +676,7 @@ func TestTextureServiceImpl_GetByUserID_And_Search(t *testing.T) {
}
cacheManager := NewMockCacheManager()
textureService := NewTextureService(textureRepo, userRepo, nil, cacheManager, logger, nil)
textureService := NewTextureService(textureRepo, userRepo, nil, cacheManager, logger)
ctx := context.Background()
@@ -725,7 +715,7 @@ func TestTextureServiceImpl_Update_And_Delete(t *testing.T) {
_ = textureRepo.Create(context.Background(), texture)
cacheManager := NewMockCacheManager()
textureService := NewTextureService(textureRepo, userRepo, nil, cacheManager, logger, nil)
textureService := NewTextureService(textureRepo, userRepo, nil, cacheManager, logger)
ctx := context.Background()
@@ -771,11 +761,11 @@ func TestTextureServiceImpl_FavoritesAndLimit(t *testing.T) {
UploaderID: 1,
Name: "T",
})
_ = textureRepo.AddFavorite(context.Background(), 1, i)
_, _ = textureRepo.ToggleFavorite(context.Background(), 1, i)
}
cacheManager := NewMockCacheManager()
textureService := NewTextureService(textureRepo, userRepo, nil, cacheManager, logger, nil)
textureService := NewTextureService(textureRepo, userRepo, nil, cacheManager, logger)
ctx := context.Background()
@@ -818,7 +808,7 @@ func TestTextureServiceImpl_ToggleFavorite(t *testing.T) {
_ = textureRepo.Create(context.Background(), testTexture)
cacheManager := NewMockCacheManager()
textureService := NewTextureService(textureRepo, userRepo, nil, cacheManager, logger, nil)
textureService := NewTextureService(textureRepo, userRepo, nil, cacheManager, logger)
ctx := context.Background()

View File

@@ -1,16 +1,16 @@
package service
import (
"carrotskin/internal/model"
"carrotskin/internal/repository"
"carrotskin/pkg/auth"
"context"
"errors"
"fmt"
"time"
"carrotskin/internal/model"
"carrotskin/internal/repository"
"carrotskin/pkg/auth"
"carrotskin/pkg/utils"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"go.uber.org/zap"
)
@@ -63,13 +63,9 @@ func (s *tokenServiceRedis) Create(ctx context.Context, userID int64, UUID strin
}
}
// 生成ClientToken使用32字符十六进制字符串
// 生成ClientToken
if clientToken == "" {
var err error
clientToken, err = utils.RandomHex(16) // 16字节 = 32字符十六进制
if err != nil {
return selectedProfileID, availableProfiles, "", "", fmt.Errorf("生成ClientToken失败: %w", err)
}
clientToken = uuid.New().String()
}
// 获取或创建Client
@@ -77,10 +73,7 @@ func (s *tokenServiceRedis) Create(ctx context.Context, userID int64, UUID strin
existingClient, err := s.clientRepo.FindByClientToken(ctx, clientToken)
if err != nil {
// Client不存在创建新的
clientUUID, err := utils.RandomHex(16) // 16字节 = 32字符十六进制
if err != nil {
return selectedProfileID, availableProfiles, "", "", fmt.Errorf("生成ClientUUID失败: %w", err)
}
clientUUID := uuid.New().String()
client = &model.Client{
UUID: clientUUID,
ClientToken: clientToken,
@@ -173,19 +166,13 @@ func (s *tokenServiceRedis) Create(ctx context.Context, userID int64, UUID strin
}
if err := s.tokenStore.Store(ctx, accessToken, metadata, ttl); err != nil {
// Redis 存储失败必须返回错误:否则 Validate 拿不到元数据Token 立即失效
s.logger.Error("存储Token到Redis失败", zap.Error(err))
return nil, nil, "", "", fmt.Errorf("存储Token失败: %w", err)
s.logger.Warn("存储Token到Redis失败", zap.Error(err))
// 不返回错误因为JWT本身已经生成成功
}
return selectedProfileID, availableProfiles, accessToken, clientToken, nil
}
// CreateWithProfile 创建Token并绑定指定Profile使用JWT + Redis存储
func (s *tokenServiceRedis) CreateWithProfile(ctx context.Context, userID int64, profileUUID string, clientToken string) (*model.Profile, []*model.Profile, string, string, error) {
return s.Create(ctx, userID, profileUUID, clientToken)
}
// Validate 验证Token使用JWT验证 + Redis存储验证
func (s *tokenServiceRedis) Validate(ctx context.Context, accessToken, clientToken string) bool {
// 设置超时上下文
@@ -474,7 +461,7 @@ func (s *tokenServiceRedis) validateProfileByUserID(ctx context.Context, userID
profile, err := s.profileRepo.FindByUUID(ctx, UUID)
if err != nil {
if repository.IsNotFound(err) {
if errors.Is(err, pgx.ErrNoRows) {
return false, errors.New("配置文件不存在")
}
return false, fmt.Errorf("验证配置文件失败: %w", err)

View File

@@ -26,7 +26,6 @@ import (
// userService UserService的实现
type userService struct {
cfg *config.Config
userRepo repository.UserRepository
jwtService *auth.JWTService
redis *redis.Client
@@ -39,7 +38,6 @@ type userService struct {
// NewUserService 创建UserService实例
func NewUserService(
cfg *config.Config,
userRepo repository.UserRepository,
jwtService *auth.JWTService,
redisClient *redis.Client,
@@ -50,7 +48,6 @@ func NewUserService(
// CacheKeyBuilder 使用空前缀,因为 CacheManager 已经处理了前缀
// 这样缓存键的格式为: CacheManager前缀 + CacheKeyBuilder生成的键
return &userService{
cfg: cfg,
userRepo: userRepo,
jwtService: jwtService,
redis: redisClient,
@@ -84,7 +81,7 @@ func (s *userService) Register(ctx context.Context, username, password, email, a
// 加密密码
hashedPassword, err := auth.HashPassword(password)
if err != nil {
return nil, "", fmt.Errorf("密码加密失败: %w", err)
return nil, "", errors.New("密码加密失败")
}
// 确定头像URL
@@ -115,7 +112,7 @@ func (s *userService) Register(ctx context.Context, username, password, email, a
// 生成JWT Token
token, err := s.jwtService.GenerateToken(user.ID, user.Username, user.Role)
if err != nil {
return nil, "", fmt.Errorf("生成Token失败: %w", err)
return nil, "", errors.New("生成Token失败")
}
return user, token, nil
@@ -170,20 +167,15 @@ func (s *userService) Login(ctx context.Context, usernameOrEmail, password, ipAd
// 生成JWT Token
token, err := s.jwtService.GenerateToken(user.ID, user.Username, user.Role)
if err != nil {
return nil, "", fmt.Errorf("生成Token失败: %w", err)
return nil, "", errors.New("生成Token失败")
}
// 更新最后登录时间(非关键路径,错误降级为 Warn
// 更新最后登录时间
now := time.Now()
user.LastLoginAt = &now
if err := s.userRepo.UpdateFields(ctx, user.ID, map[string]interface{}{
_ = s.userRepo.UpdateFields(ctx, user.ID, map[string]interface{}{
"last_login_at": now,
}); err != nil {
s.logger.Warn("更新最后登录时间失败",
zap.Int64("user_id", user.ID),
zap.Error(err),
)
}
})
// 记录成功登录日志
s.logSuccessLogin(ctx, user.ID, ipAddress, userAgent)
@@ -247,10 +239,7 @@ func (s *userService) UpdateAvatar(ctx context.Context, userID int64, avatarURL
func (s *userService) ChangePassword(ctx context.Context, userID int64, oldPassword, newPassword string) error {
user, err := s.userRepo.FindByID(ctx, userID)
if err != nil {
return fmt.Errorf("查询用户失败: %w", err)
}
if user == nil {
if err != nil || user == nil {
return errors.New("用户不存在")
}
@@ -260,7 +249,7 @@ func (s *userService) ChangePassword(ctx context.Context, userID int64, oldPassw
hashedPassword, err := auth.HashPassword(newPassword)
if err != nil {
return fmt.Errorf("密码加密失败: %w", err)
return errors.New("密码加密失败")
}
err = s.userRepo.UpdateFields(ctx, userID, map[string]interface{}{
@@ -278,16 +267,13 @@ func (s *userService) ChangePassword(ctx context.Context, userID int64, oldPassw
func (s *userService) ResetPassword(ctx context.Context, email, newPassword string) error {
user, err := s.userRepo.FindByEmail(ctx, email)
if err != nil {
return fmt.Errorf("查询用户失败: %w", err)
}
if user == nil {
if err != nil || user == nil {
return errors.New("用户不存在")
}
hashedPassword, err := auth.HashPassword(newPassword)
if err != nil {
return fmt.Errorf("密码加密失败: %w", err)
return errors.New("密码加密失败")
}
err = s.userRepo.UpdateFields(ctx, user.ID, map[string]interface{}{
@@ -364,13 +350,14 @@ func (s *userService) ValidateAvatarURL(ctx context.Context, avatarURL string) e
return errors.New("URL缺少主机名")
}
// 从注入的配置获取允许的域名列表
allowedDomains := s.cfg.Security.AllowedDomains
if len(allowedDomains) == 0 {
allowedDomains = []string{"localhost", "127.0.0.1"}
// 从配置获取允许的域名列表
cfg, err := config.GetConfig()
if err != nil {
allowedDomains := []string{"localhost", "127.0.0.1"}
return s.checkDomainAllowed(host, allowedDomains)
}
return s.checkDomainAllowed(host, allowedDomains)
return s.checkDomainAllowed(host, cfg.Security.AllowedDomains)
}
func (s *userService) UploadAvatar(ctx context.Context, userID int64, fileData []byte, fileName string) (string, error) {
@@ -435,23 +422,29 @@ func (s *userService) UploadAvatar(ctx context.Context, userID int64, fileData [
}
func (s *userService) GetMaxProfilesPerUser() int {
if s.cfg.Site.MaxProfilesPerUser <= 0 {
cfg, err := config.GetConfig()
if err != nil || cfg.Site.MaxProfilesPerUser <= 0 {
return 5
}
return s.cfg.Site.MaxProfilesPerUser
return cfg.Site.MaxProfilesPerUser
}
func (s *userService) GetMaxTexturesPerUser() int {
if s.cfg.Site.MaxTexturesPerUser <= 0 {
cfg, err := config.GetConfig()
if err != nil || cfg.Site.MaxTexturesPerUser <= 0 {
return 50
}
return s.cfg.Site.MaxTexturesPerUser
return cfg.Site.MaxTexturesPerUser
}
// 私有辅助方法
func (s *userService) getDefaultAvatar() string {
return s.cfg.Site.DefaultAvatar
cfg, err := config.GetConfig()
if err != nil {
return ""
}
return cfg.Site.DefaultAvatar
}
func (s *userService) checkDomainAllowed(host string, allowedDomains []string) error {
@@ -512,21 +505,3 @@ func (s *userService) logFailedLogin(ctx context.Context, userID int64, ipAddres
}
_ = s.userRepo.CreateLoginLog(ctx, log)
}
// ==================== 管理员操作 ====================
// ListUsers 分页查询用户列表(管理员)
func (s *userService) ListUsers(ctx context.Context, page, pageSize int) ([]*model.User, int64, error) {
page, pageSize = NormalizePagination(page, pageSize)
return s.userRepo.List(ctx, page, pageSize)
}
// SetRole 设置用户角色(管理员)
func (s *userService) SetRole(ctx context.Context, userID int64, role string) error {
return s.userRepo.UpdateFields(ctx, userID, map[string]interface{}{"role": role})
}
// SetStatus 设置用户状态(管理员)
func (s *userService) SetStatus(ctx context.Context, userID int64, status int16) error {
return s.userRepo.UpdateFields(ctx, userID, map[string]interface{}{"status": status})
}

View File

@@ -3,7 +3,6 @@ package service
import (
"carrotskin/internal/model"
"carrotskin/pkg/auth"
"carrotskin/pkg/config"
"context"
"testing"
@@ -15,12 +14,11 @@ func TestUserServiceImpl_Register(t *testing.T) {
userRepo := NewMockUserRepository()
jwtService := auth.NewJWTService("secret", 1)
logger := zap.NewNop()
cfg := &config.Config{}
// 初始化Service
// 注意redisClient 和 storageClient 传入 nil因为 Register 方法中没有使用它们
cacheManager := NewMockCacheManager()
userService := NewUserService(cfg, userRepo, jwtService, nil, cacheManager, nil, logger)
userService := NewUserService(userRepo, jwtService, nil, cacheManager, nil, logger)
ctx := context.Background()
@@ -130,8 +128,7 @@ func TestUserServiceImpl_Login(t *testing.T) {
_ = userRepo.Create(context.Background(), testUser)
cacheManager := NewMockCacheManager()
cfg := &config.Config{}
userService := NewUserService(cfg, userRepo, jwtService, nil, cacheManager, nil, logger)
userService := NewUserService(userRepo, jwtService, nil, cacheManager, nil, logger)
ctx := context.Background()
@@ -211,7 +208,7 @@ func TestUserServiceImpl_BasicGettersAndUpdates(t *testing.T) {
_ = userRepo.Create(context.Background(), user)
cacheManager := NewMockCacheManager()
userService := NewUserService(&config.Config{}, userRepo, jwtService, nil, cacheManager, nil, logger)
userService := NewUserService(userRepo, jwtService, nil, cacheManager, nil, logger)
ctx := context.Background()
@@ -258,7 +255,7 @@ func TestUserServiceImpl_ChangePassword(t *testing.T) {
_ = userRepo.Create(context.Background(), user)
cacheManager := NewMockCacheManager()
userService := NewUserService(&config.Config{}, userRepo, jwtService, nil, cacheManager, nil, logger)
userService := NewUserService(userRepo, jwtService, nil, cacheManager, nil, logger)
ctx := context.Background()
@@ -292,7 +289,7 @@ func TestUserServiceImpl_ResetPassword(t *testing.T) {
_ = userRepo.Create(context.Background(), user)
cacheManager := NewMockCacheManager()
userService := NewUserService(&config.Config{}, userRepo, jwtService, nil, cacheManager, nil, logger)
userService := NewUserService(userRepo, jwtService, nil, cacheManager, nil, logger)
ctx := context.Background()
@@ -319,7 +316,7 @@ func TestUserServiceImpl_ChangeEmail(t *testing.T) {
_ = userRepo.Create(context.Background(), user2)
cacheManager := NewMockCacheManager()
userService := NewUserService(&config.Config{}, userRepo, jwtService, nil, cacheManager, nil, logger)
userService := NewUserService(userRepo, jwtService, nil, cacheManager, nil, logger)
ctx := context.Background()
@@ -341,7 +338,7 @@ func TestUserServiceImpl_ValidateAvatarURL(t *testing.T) {
logger := zap.NewNop()
cacheManager := NewMockCacheManager()
userService := NewUserService(&config.Config{}, userRepo, jwtService, nil, cacheManager, nil, logger)
userService := NewUserService(userRepo, jwtService, nil, cacheManager, nil, logger)
ctx := context.Background()
@@ -377,7 +374,7 @@ func TestUserServiceImpl_MaxLimits(t *testing.T) {
// 未配置时走默认值
cacheManager := NewMockCacheManager()
userService := NewUserService(&config.Config{}, userRepo, jwtService, nil, cacheManager, nil, logger)
userService := NewUserService(userRepo, jwtService, nil, cacheManager, nil, logger)
if got := userService.GetMaxProfilesPerUser(); got != 5 {
t.Fatalf("GetMaxProfilesPerUser 默认值错误, got=%d", got)
}

View File

@@ -26,19 +26,16 @@ const (
// verificationService VerificationService的实现
type verificationService struct {
cfg *config.Config
redis *redis.Client
emailService *email.Service
}
// NewVerificationService 创建VerificationService实例
func NewVerificationService(
cfg *config.Config,
redisClient *redis.Client,
emailService *email.Service,
) VerificationService {
return &verificationService{
cfg: cfg,
redis: redisClient,
emailService: emailService,
}
@@ -47,7 +44,8 @@ func NewVerificationService(
// SendCode 发送验证码
func (s *verificationService) SendCode(ctx context.Context, email, codeType string) error {
// 测试环境下直接跳过,不存储也不发送
if s.cfg.IsTestEnvironment() {
cfg, err := config.GetConfig()
if err == nil && cfg.IsTestEnvironment() {
return nil
}
@@ -91,7 +89,8 @@ func (s *verificationService) SendCode(ctx context.Context, email, codeType stri
// VerifyCode 验证验证码
func (s *verificationService) VerifyCode(ctx context.Context, email, code, codeType string) error {
// 测试环境下直接通过验证
if s.cfg.IsTestEnvironment() {
cfg, err := config.GetConfig()
if err == nil && cfg.IsTestEnvironment() {
return nil
}
@@ -167,5 +166,8 @@ func (s *verificationService) sendEmail(to, code, codeType string) error {
}
}
// DeleteVerificationCode 已移除:重构后无调用方。如需删除验证码,请使用
// VerificationService 实现内的 redis.Del 路径。
// DeleteVerificationCode 删除验证码(工具函数,保持向后兼容)
func DeleteVerificationCode(ctx context.Context, redisClient *redis.Client, email, codeType string) error {
codeKey := fmt.Sprintf("verification:code:%s:%s", codeType, email)
return redisClient.Del(ctx, codeKey)
}

View File

@@ -1,20 +1,22 @@
package service
import (
"context"
"fmt"
apperrors "carrotskin/internal/errors"
"carrotskin/internal/model"
"carrotskin/internal/repository"
"carrotskin/pkg/auth"
"context"
"fmt"
"go.uber.org/zap"
"gorm.io/gorm"
)
// yggdrasilAuthService Yggdrasil认证服务实现
// 负责认证和密码管理
type yggdrasilAuthService struct {
db *gorm.DB
userRepo repository.UserRepository
yggdrasilRepo repository.YggdrasilRepository
logger *zap.Logger
@@ -22,11 +24,13 @@ type yggdrasilAuthService struct {
// NewYggdrasilAuthService 创建Yggdrasil认证服务实例内部使用
func NewYggdrasilAuthService(
db *gorm.DB,
userRepo repository.UserRepository,
yggdrasilRepo repository.YggdrasilRepository,
logger *zap.Logger,
) *yggdrasilAuthService {
return &yggdrasilAuthService{
db: db,
userRepo: userRepo,
yggdrasilRepo: yggdrasilRepo,
logger: logger,
@@ -74,7 +78,7 @@ func (s *yggdrasilAuthService) ResetYggdrasilPassword(ctx context.Context, userI
ID: userID,
Password: hashedPassword,
}
if err := s.yggdrasilRepo.Create(ctx, &yggdrasil); err != nil {
if err := s.db.Create(&yggdrasil).Error; err != nil {
return "", fmt.Errorf("创建Yggdrasil密码失败: %w", err)
}
return plainPassword, nil

View File

@@ -1,39 +1,23 @@
package service
import (
apperrors "carrotskin/internal/errors"
"carrotskin/internal/repository"
"context"
"fmt"
"time"
apperrors "carrotskin/internal/errors"
"carrotskin/internal/repository"
"go.uber.org/zap"
)
// CertificateService 证书服务接口
type CertificateService interface {
// GeneratePlayerCertificate 生成玩家证书
GeneratePlayerCertificate(ctx context.Context, uuid string) (*PlayerCertificate, error)
GeneratePlayerCertificate(ctx context.Context, uuid string) (map[string]interface{}, error)
// GetPublicKey 获取公钥
GetPublicKey(ctx context.Context) (string, error)
}
// PlayerCertificate 玩家证书
type PlayerCertificate struct {
KeyPair PlayerKeyPair `json:"keyPair"`
PublicKeySignature string `json:"publicKeySignature"`
PublicKeySignatureV2 string `json:"publicKeySignatureV2"`
ExpiresAt int64 `json:"expiresAt"`
RefreshedAfter int64 `json:"refreshedAfter"`
}
// PlayerKeyPair 玩家证书密钥对
type PlayerKeyPair struct {
PrivateKey string `json:"privateKey"`
PublicKey string `json:"publicKey"`
}
// yggdrasilCertificateService 证书服务实现
type yggdrasilCertificateService struct {
profileRepo repository.ProfileRepository
@@ -55,7 +39,7 @@ func NewCertificateService(
}
// GeneratePlayerCertificate 生成玩家证书
func (s *yggdrasilCertificateService) GeneratePlayerCertificate(ctx context.Context, uuid string) (*PlayerCertificate, error) {
func (s *yggdrasilCertificateService) GeneratePlayerCertificate(ctx context.Context, uuid string) (map[string]interface{}, error) {
if uuid == "" {
return nil, apperrors.ErrUUIDRequired
}
@@ -80,7 +64,7 @@ func (s *yggdrasilCertificateService) GeneratePlayerCertificate(ctx context.Cont
s.logger.Info("为用户创建新的密钥对",
zap.String("uuid", uuid),
)
keyPair, err = s.signatureService.NewKeyPair(ctx)
keyPair, err = s.signatureService.NewKeyPair()
if err != nil {
s.logger.Error("生成玩家证书密钥对失败",
zap.Error(err),
@@ -104,15 +88,15 @@ func (s *yggdrasilCertificateService) GeneratePlayerCertificate(ctx context.Cont
expiresAtMillis := keyPair.Expiration.UnixMilli()
// 返回玩家证书
certificate := &PlayerCertificate{
KeyPair: PlayerKeyPair{
PrivateKey: keyPair.PrivateKey,
PublicKey: keyPair.PublicKey,
certificate := map[string]interface{}{
"keyPair": map[string]interface{}{
"privateKey": keyPair.PrivateKey,
"publicKey": keyPair.PublicKey,
},
PublicKeySignature: keyPair.PublicKeySignature,
PublicKeySignatureV2: keyPair.PublicKeySignatureV2,
ExpiresAt: expiresAtMillis,
RefreshedAfter: keyPair.Refresh.UnixMilli(),
"publicKeySignature": keyPair.PublicKeySignature,
"publicKeySignatureV2": keyPair.PublicKeySignatureV2,
"expiresAt": expiresAtMillis,
"refreshedAfter": keyPair.Refresh.UnixMilli(),
}
s.logger.Info("成功生成玩家证书",
@@ -123,5 +107,6 @@ func (s *yggdrasilCertificateService) GeneratePlayerCertificate(ctx context.Cont
// GetPublicKey 获取公钥
func (s *yggdrasilCertificateService) GetPublicKey(ctx context.Context) (string, error) {
return s.signatureService.GetPublicKeyFromRedis(ctx)
return s.signatureService.GetPublicKeyFromRedis()
}

View File

@@ -1,511 +0,0 @@
package service
import (
"context"
"errors"
"fmt"
"strings"
"time"
apperrors "carrotskin/internal/errors"
"carrotskin/internal/model"
"carrotskin/internal/repository"
"carrotskin/pkg/redis"
"carrotskin/pkg/utils"
"go.uber.org/zap"
"gorm.io/gorm"
)
const (
// PresenceKeyPrefix 在线状态 Redis 键前缀key 形如 presence:<profileUUID>
PresenceKeyPrefix = "presence:"
// PresenceTTL 在线状态过期时间;客户端最长 5 分钟必发一次心跳(文档 1.1
PresenceTTL = 5 * time.Minute
// BlocklistCacheTTL 屏蔽列表缓存冷却时间(文档 1.6:客户端 120 秒节流)
BlocklistCacheTTL = 120 * time.Second
// BlocklistCacheKeyPrefix 屏蔽列表缓存键前缀
BlocklistCacheKeyPrefix = "blocklist:"
// PresenceStatusOffline 离线状态固定值(文档 1.1
PresenceStatusOffline = "OFFLINE"
)
// friendsService 好友系统服务实现
type friendsService struct {
friendRepo repository.FriendRepository
attrRepo repository.PlayerAttributeRepository
profileRepo repository.ProfileRepository
redis *redis.Client
logger *zap.Logger
presenceTTL time.Duration
blocklistTTL time.Duration
}
// NewFriendsService 创建好友系统服务实例
func NewFriendsService(
friendRepo repository.FriendRepository,
attrRepo repository.PlayerAttributeRepository,
profileRepo repository.ProfileRepository,
redisClient *redis.Client,
logger *zap.Logger,
) FriendsService {
return &friendsService{
friendRepo: friendRepo,
attrRepo: attrRepo,
profileRepo: profileRepo,
redis: redisClient,
logger: logger,
presenceTTL: PresenceTTL,
blocklistTTL: BlocklistCacheTTL,
}
}
// ============================================================================
// 好友列表与操作
// ============================================================================
// ListFriends 获取好友列表(文档 1.3.1
func (s *friendsService) ListFriends(ctx context.Context, requesterUUID string) (*FriendsListResponse, error) {
accepted, err := s.friendRepo.ListAccepted(ctx, requesterUUID)
if err != nil {
return nil, fmt.Errorf("查询好友列表失败: %w", err)
}
incoming, err := s.friendRepo.ListIncoming(ctx, requesterUUID)
if err != nil {
return nil, fmt.Errorf("查询收到的请求失败: %w", err)
}
outgoing, err := s.friendRepo.ListOutgoing(ctx, requesterUUID)
if err != nil {
return nil, fmt.Errorf("查询发出的请求失败: %w", err)
}
// 批量解析 profile name
friends, err := s.toFriendDTOs(ctx, accepted)
if err != nil {
return nil, err
}
incomingDTOs, err := s.toFriendDTOs(ctx, incoming)
if err != nil {
return nil, err
}
outgoingDTOs, err := s.toFriendDTOs(ctx, outgoing)
if err != nil {
return nil, err
}
return &FriendsListResponse{
Friends: friends,
IncomingRequests: incomingDTOs,
OutgoingRequests: outgoingDTOs,
}, nil
}
// PerformFriendAction 执行好友加/删操作(文档 1.3.2
func (s *friendsService) PerformFriendAction(ctx context.Context, requesterUUID string, req FriendActionRequest) (*FriendsListResponse, error) {
switch req.UpdateType {
case FriendActionAdd:
if err := s.addFriend(ctx, requesterUUID, req); err != nil {
return nil, err
}
case FriendActionRemove:
if err := s.removeFriend(ctx, requesterUUID, req); err != nil {
return nil, err
}
default:
return nil, apperrors.NewBadRequest("无效的 updateType", nil)
}
// 文档 1.3.2PUT 成功后返回最新好友列表
return s.ListFriends(ctx, requesterUUID)
}
// addFriend 添加好友 / 发送请求 / 接受请求(文档 1.3.2 ADD
func (s *friendsService) addFriend(ctx context.Context, requesterUUID string, req FriendActionRequest) error {
targetUUID, err := s.resolveTargetUUID(ctx, req)
if err != nil {
return err
}
// 校验目标存在
targetProfile, err := s.profileRepo.FindByUUID(ctx, targetUUID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return apperrors.NewBadRequest(apperrors.FriendsErrUnknownProfile, nil)
}
return fmt.Errorf("查询目标档案失败: %w", err)
}
if targetProfile == nil {
return apperrors.NewBadRequest(apperrors.FriendsErrUnknownProfile, nil)
}
// 不能添加自己
if requesterUUID == targetUUID {
return apperrors.NewBadRequest(apperrors.FriendsErrCannotAddSelf, nil)
}
// 检查 requester->target 已有记录
existing, err := s.friendRepo.FindRelation(ctx, requesterUUID, targetUUID)
if err != nil {
return fmt.Errorf("查询已有关系失败: %w", err)
}
if existing != nil {
switch existing.Status {
case model.FriendsStatusAccepted:
// 已是好友,幂等返回成功
return nil
case model.FriendsStatusBlocked:
// requester 屏蔽了 target解除屏蔽并建好友
if err := s.friendRepo.Delete(ctx, existing.ID); err != nil {
return fmt.Errorf("解除屏蔽失败: %w", err)
}
case model.FriendsStatusPending:
// 已发过请求,幂等返回
return nil
}
}
// 检查 target->requester 是否已向我发出 pending 请求 -> 自动接受
reverse, err := s.friendRepo.FindRelation(ctx, targetUUID, requesterUUID)
if err != nil {
return fmt.Errorf("查询反向关系失败: %w", err)
}
if reverse != nil {
switch reverse.Status {
case model.FriendsStatusPending:
// 对方已向我发起请求,直接互为好友(更新 A→B 为 accepted 即可,
// ListAccepted 会合并两方向,无需补建 B→A 以避免好友列表重复)
if err := s.friendRepo.UpdateStatus(ctx, reverse.ID, model.FriendsStatusAccepted); err != nil {
return fmt.Errorf("接受好友请求失败: %w", err)
}
return nil
case model.FriendsStatusAccepted:
// 对方已记录为好友(数据修复场景),确保 requester->target 也存在 accepted 记录
if existing == nil {
if err := s.friendRepo.Create(ctx, &model.Friend{
RequesterUUID: requesterUUID,
TargetUUID: targetUUID,
Status: model.FriendsStatusAccepted,
}); err != nil {
return fmt.Errorf("创建好友记录失败: %w", err)
}
}
return nil
case model.FriendsStatusBlocked:
// 对方屏蔽了我,不接受好友请求
return apperrors.NewForbidden("对方已屏蔽你")
}
}
// 普通发送请求
if existing == nil {
if err := s.friendRepo.Create(ctx, &model.Friend{
RequesterUUID: requesterUUID,
TargetUUID: targetUUID,
Status: model.FriendsStatusPending,
}); err != nil {
return fmt.Errorf("发送好友请求失败: %w", err)
}
}
return nil
}
// removeFriend 删除好友 / 拒绝请求 / 撤回请求(文档 1.3.2 REMOVE
func (s *friendsService) removeFriend(ctx context.Context, requesterUUID string, req FriendActionRequest) error {
targetUUID, err := s.resolveTargetUUID(ctx, req)
if err != nil {
return err
}
// 删除 requester->target 记录(涵盖撤回发出的请求、删除好友)
if rel, err := s.friendRepo.FindRelation(ctx, requesterUUID, targetUUID); err != nil {
return fmt.Errorf("查询关系失败: %w", err)
} else if rel != nil {
if err := s.friendRepo.Delete(ctx, rel.ID); err != nil {
return fmt.Errorf("删除关系失败: %w", err)
}
}
// 拒绝收到的请求时requester 作为 target 方),删除 target->requester 的 pending 记录
if rel, err := s.friendRepo.FindRelation(ctx, targetUUID, requesterUUID); err != nil {
return fmt.Errorf("查询反向关系失败: %w", err)
} else if rel != nil && rel.Status == model.FriendsStatusPending {
if err := s.friendRepo.Delete(ctx, rel.ID); err != nil {
return fmt.Errorf("拒绝请求失败: %w", err)
}
}
return nil
}
// resolveTargetUUID 解析请求目标 UUIDprofileId 优先,否则用 name 查 Profile
func (s *friendsService) resolveTargetUUID(ctx context.Context, req FriendActionRequest) (string, error) {
if req.ProfileID != "" {
return utils.FormatUUIDToNoDash(req.ProfileID), nil
}
if req.Name != "" {
profile, err := s.profileRepo.FindByName(ctx, req.Name)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return "", apperrors.NewBadRequest(apperrors.FriendsErrUnknownProfile, nil)
}
return "", fmt.Errorf("查询目标档案失败: %w", err)
}
if profile == nil {
return "", apperrors.NewBadRequest(apperrors.FriendsErrUnknownProfile, nil)
}
return profile.UUID, nil
}
return "", apperrors.NewBadRequest(apperrors.FriendsErrUnknownProfile, nil)
}
// toFriendDTOs 将 UUID 列表批量解析为 FriendDTO补 name
func (s *friendsService) toFriendDTOs(ctx context.Context, uuids []string) ([]FriendDTO, error) {
if len(uuids) == 0 {
return []FriendDTO{}, nil
}
profiles, err := s.profileRepo.FindByUUIDs(ctx, uuids)
if err != nil {
return nil, fmt.Errorf("批量查询档案失败: %w", err)
}
nameByUUID := make(map[string]string, len(profiles))
for _, p := range profiles {
if p != nil {
nameByUUID[p.UUID] = p.Name
}
}
result := make([]FriendDTO, 0, len(uuids))
for _, uid := range uuids {
result = append(result, FriendDTO{
ProfileID: uid,
Name: nameByUUID[uid], // 找不到 name 时留空
})
}
return result, nil
}
// ============================================================================
// 玩家偏好属性
// ============================================================================
// GetAttributes 获取玩家属性(文档 1.2.1
func (s *friendsService) GetAttributes(ctx context.Context, profileUUID string) (*PlayerAttributesResponse, error) {
attr, err := s.attrRepo.Get(ctx, profileUUID)
if err != nil {
return nil, fmt.Errorf("查询玩家偏好失败: %w", err)
}
if attr == nil {
d := model.DefaultPlayerAttributes(profileUUID)
attr = &d
}
return &PlayerAttributesResponse{
ProfanityFilterPreferences: ProfanityFilterPreferencesResp{
ProfanityFilterOn: attr.ProfanityFilterOn,
},
FriendsPreferences: FriendsPreferencesResp{
Friends: enabledToString(attr.FriendsEnabled),
AcceptInvites: enabledToString(attr.AcceptInvites),
},
ChatPreferences: ChatPreferencesResp{
TextCommunication: attr.TextCommunication,
},
}, nil
}
// UpdateAttributes 更新玩家偏好(文档 1.2.2
func (s *friendsService) UpdateAttributes(ctx context.Context, profileUUID string, req PlayerAttributesRequest) error {
// 先读取现有值(保留未传字段)
attr, err := s.attrRepo.Get(ctx, profileUUID)
if err != nil {
return fmt.Errorf("查询玩家偏好失败: %w", err)
}
if attr == nil {
d := model.DefaultPlayerAttributes(profileUUID)
attr = &d
}
if req.ProfanityFilterPreferences != nil && req.ProfanityFilterPreferences.ProfanityFilterOn != nil {
attr.ProfanityFilterOn = *req.ProfanityFilterPreferences.ProfanityFilterOn
}
if req.FriendsPreferences != nil {
if req.FriendsPreferences.Friends != nil {
attr.FriendsEnabled = *req.FriendsPreferences.Friends == "ENABLED"
}
if req.FriendsPreferences.AcceptInvites != nil {
attr.AcceptInvites = *req.FriendsPreferences.AcceptInvites == "ENABLED"
}
}
if err := s.attrRepo.Upsert(ctx, attr); err != nil {
return fmt.Errorf("更新玩家偏好失败: %w", err)
}
return nil
}
// enabledToString 将布尔偏好转为 ENABLED/DISABLED 字符串
func enabledToString(enabled bool) string {
if enabled {
return "ENABLED"
}
return "DISABLED"
}
// ============================================================================
// 在线状态
// ============================================================================
// UpdatePresence 上报自身在线状态并返回好友在线状态(文档 1.1
func (s *friendsService) UpdatePresence(ctx context.Context, requesterUUID string, status string) (*PresenceResponse, error) {
// 写入自身状态到 Redis
key := PresenceKeyPrefix + requesterUUID
now := time.Now().UTC().Format(time.RFC3339Nano)
// 存储 "status|lastUpdated",便于读取时一并恢复时间戳
value := status + "|" + now
if err := s.redis.Set(ctx, key, value, s.presenceTTL); err != nil {
s.logger.Error("写入在线状态失败",
zap.Error(err),
zap.String("profileUUID", requesterUUID),
)
return nil, fmt.Errorf("写入在线状态失败: %w", err)
}
// 拉取好友 UUID 列表
friendUUIDs, err := s.friendRepo.ListAccepted(ctx, requesterUUID)
if err != nil {
return nil, fmt.Errorf("查询好友列表失败: %w", err)
}
entries := s.batchGetPresence(ctx, friendUUIDs)
// 文档 1.1:服务器仅返回非离线玩家
filtered := make([]PresenceEntry, 0, len(entries))
for _, e := range entries {
if e.Status != "" && e.Status != PresenceStatusOffline {
filtered = append(filtered, e)
}
}
return &PresenceResponse{Presence: filtered}, nil
}
// batchGetPresence 批量读取多个 profileUUID 的在线状态
func (s *friendsService) batchGetPresence(ctx context.Context, uuids []string) []PresenceEntry {
if len(uuids) == 0 || s.redis == nil {
return []PresenceEntry{}
}
keys := make([]string, 0, len(uuids))
for _, uid := range uuids {
keys = append(keys, PresenceKeyPrefix+uid)
}
// 使用底层 go-redis 客户端的 MGet 一次读取
results, err := s.redis.Client.MGet(ctx, keys...).Result()
if err != nil {
s.logger.Warn("批量读取在线状态失败", zap.Error(err))
return []PresenceEntry{}
}
entries := make([]PresenceEntry, 0, len(uuids))
for i, uid := range uuids {
var entry PresenceEntry
entry.ProfileID = uid
if i < len(results) && results[i] != nil {
if raw, ok := results[i].(string); ok && raw != "" {
parts := strings.SplitN(raw, "|", 2)
entry.Status = parts[0]
if len(parts) == 2 {
entry.LastUpdated = parts[1]
} else {
entry.LastUpdated = time.Now().UTC().Format(time.RFC3339Nano)
}
}
}
entries = append(entries, entry)
}
return entries
}
// ============================================================================
// 屏蔽列表
// ============================================================================
// GetBlocklist 获取屏蔽列表(文档 1.6,含 120s 客户端节流缓存)
func (s *friendsService) GetBlocklist(ctx context.Context, blockerUUID string) (*BlockListResponse, error) {
// 文档 1.6:客户端 120s 节流;服务端在此也做一层缓存,避免重复查库
cacheKey := BlocklistCacheKeyPrefix + blockerUUID
if s.redis != nil {
if cached, err := s.redis.GetBytes(ctx, cacheKey); err == nil && len(cached) > 0 {
var resp BlockListResponse
if err := json.Unmarshal(cached, &resp); err == nil {
return &resp, nil
}
}
}
blocked, err := s.friendRepo.ListBlocked(ctx, blockerUUID)
if err != nil {
return nil, fmt.Errorf("查询屏蔽列表失败: %w", err)
}
if blocked == nil {
blocked = []string{}
}
resp := &BlockListResponse{BlockedProfiles: blocked}
// 写入缓存
if s.redis != nil {
if data, err := json.Marshal(resp); err == nil {
if err := s.redis.Set(ctx, cacheKey, data, s.blocklistTTL); err != nil {
s.logger.Warn("缓存屏蔽列表失败", zap.Error(err))
}
}
}
return resp, nil
}
// 屏蔽/取消屏蔽方法(供后续/管理端调用,当前协议未定义对应端点)
// Block 屏蔽目标玩家
func (s *friendsService) Block(ctx context.Context, blockerUUID, targetUUID string) error {
if blockerUUID == targetUUID {
return apperrors.NewBadRequest(apperrors.FriendsErrCannotAddSelf, nil)
}
// 若已有关系记录,更新为 blocked否则新建
if rel, err := s.friendRepo.FindRelation(ctx, blockerUUID, targetUUID); err != nil {
return fmt.Errorf("查询关系失败: %w", err)
} else if rel != nil {
if err := s.friendRepo.UpdateStatus(ctx, rel.ID, model.FriendsStatusBlocked); err != nil {
return fmt.Errorf("更新屏蔽状态失败: %w", err)
}
return s.invalidateBlocklistCache(ctx, blockerUUID)
}
if err := s.friendRepo.Create(ctx, &model.Friend{
RequesterUUID: blockerUUID,
TargetUUID: targetUUID,
Status: model.FriendsStatusBlocked,
}); err != nil {
return fmt.Errorf("创建屏蔽记录失败: %w", err)
}
return s.invalidateBlocklistCache(ctx, blockerUUID)
}
// Unblock 取消屏蔽
func (s *friendsService) Unblock(ctx context.Context, blockerUUID, targetUUID string) error {
rel, err := s.friendRepo.FindRelation(ctx, blockerUUID, targetUUID)
if err != nil {
return fmt.Errorf("查询关系失败: %w", err)
}
if rel == nil || rel.Status != model.FriendsStatusBlocked {
// 幂等:未屏蔽时直接返回
return nil
}
if err := s.friendRepo.Delete(ctx, rel.ID); err != nil {
return fmt.Errorf("取消屏蔽失败: %w", err)
}
return s.invalidateBlocklistCache(ctx, blockerUUID)
}
// invalidateBlocklistCache 清除屏蔽列表缓存
func (s *friendsService) invalidateBlocklistCache(ctx context.Context, blockerUUID string) error {
if s.redis == nil {
return nil
}
return s.redis.Del(ctx, BlocklistCacheKeyPrefix+blockerUUID)
}
// 确保引用了 go-redisMGet 通过 s.redis.Client
var _ = redis.Client{}

View File

@@ -1,260 +0,0 @@
package service
import (
"context"
"testing"
"carrotskin/internal/model"
"carrotskin/internal/repository"
"carrotskin/pkg/utils"
"go.uber.org/zap"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// newFriendsTestDB 构建内存 sqlite 并迁移所需表
func newFriendsTestDB(t *testing.T) *gorm.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
t.Fatalf("open sqlite: %v", err)
}
if err := db.AutoMigrate(&model.Profile{}, &model.Friend{}, &model.PlayerAttributes{}); err != nil {
t.Fatalf("migrate: %v", err)
}
// 清理共享内存库的残留数据
db.Exec("DELETE FROM friends")
db.Exec("DELETE FROM profiles")
db.Exec("DELETE FROM player_attributes")
return db
}
// newFriendsService 用真实 GORM repo + nil redis 构造服务presence/blocklist 缓存路径会跳过)
func newFriendsService(t *testing.T) (FriendsService, *gorm.DB) {
t.Helper()
db := newFriendsTestDB(t)
friendRepo := repository.NewFriendRepository(db)
attrRepo := repository.NewPlayerAttributeRepository(db)
profileRepo := repository.NewProfileRepository(db)
return NewFriendsService(friendRepo, attrRepo, profileRepo, nil, zap.NewNop()), db
}
func mustCreateProfile(t *testing.T, db *gorm.DB, name string) *model.Profile {
t.Helper()
p := &model.Profile{
UUID: utils.GenerateUUID(),
UserID: 1,
Name: name,
RSAPrivateKey: "x",
}
if err := db.Create(p).Error; err != nil {
t.Fatalf("create profile %s: %v", name, err)
}
return p
}
// TestAddFriend_SelfReject 添加自己应报错
func TestAddFriend_SelfReject(t *testing.T) {
svc, db := newFriendsService(t)
p := mustCreateProfile(t, db, "self")
_, err := svc.PerformFriendAction(context.Background(), p.UUID, FriendActionRequest{
ProfileID: p.UUID,
UpdateType: FriendActionAdd,
})
if err == nil {
t.Fatal("添加自己应报错")
}
}
// TestAddFriend_UnknownProfile 目标不存在应报错
func TestAddFriend_UnknownProfile(t *testing.T) {
svc, db := newFriendsService(t)
p := mustCreateProfile(t, db, "a")
// 使用 32 位无连字符 UUID规避 FormatUUIDToNoDash 对非法长度的告警路径
_, err := svc.PerformFriendAction(context.Background(), p.UUID, FriendActionRequest{
ProfileID: "ffffffffffffffffffffffffffffffff",
UpdateType: FriendActionAdd,
})
if err == nil {
t.Fatal("不存在的目标应报错")
}
}
// TestAddFriend_SendRequestThenAccept 双向流程A 发请求 -> B 接受 -> 互为好友
func TestAddFriend_SendRequestThenAccept(t *testing.T) {
svc, db := newFriendsService(t)
a := mustCreateProfile(t, db, "alice")
b := mustCreateProfile(t, db, "bob")
// A 向 B 发起请求
resp, err := svc.PerformFriendAction(context.Background(), a.UUID, FriendActionRequest{
ProfileID: b.UUID,
UpdateType: FriendActionAdd,
})
if err != nil {
t.Fatalf("A 发起请求失败: %v", err)
}
if len(resp.OutgoingRequests) != 1 || resp.OutgoingRequests[0].ProfileID != b.UUID {
t.Fatalf("A 的 outgoing 应包含 B, got %+v", resp.OutgoingRequests)
}
// B 视角incoming 应包含 A
respB, err := svc.ListFriends(context.Background(), b.UUID)
if err != nil {
t.Fatalf("B 查询列表失败: %v", err)
}
if len(respB.IncomingRequests) != 1 || respB.IncomingRequests[0].ProfileID != a.UUID {
t.Fatalf("B 的 incoming 应包含 A, got %+v", respB.IncomingRequests)
}
// B 接受请求B 用 ADD 指向 A -> 自动接受)
resp, err = svc.PerformFriendAction(context.Background(), b.UUID, FriendActionRequest{
ProfileID: a.UUID,
UpdateType: FriendActionAdd,
})
if err != nil {
t.Fatalf("B 接受请求失败: %v", err)
}
if len(resp.Friends) != 1 || resp.Friends[0].ProfileID != a.UUID {
t.Fatalf("B 的 friends 应包含 A, got %+v", resp.Friends)
}
// A 视角:也是好友
respA, err := svc.ListFriends(context.Background(), a.UUID)
if err != nil {
t.Fatalf("A 查询列表失败: %v", err)
}
if len(respA.Friends) != 1 || respA.Friends[0].ProfileID != b.UUID {
t.Fatalf("A 的 friends 应包含 B, got %+v", respA.Friends)
}
}
// TestRemoveFriend_Flow A B 互为好友后 A 删除好友 -> 双方都无好友
func TestRemoveFriend_Flow(t *testing.T) {
svc, db := newFriendsService(t)
a := mustCreateProfile(t, db, "alice")
b := mustCreateProfile(t, db, "bob")
// 互为好友
if _, err := svc.PerformFriendAction(context.Background(), a.UUID, FriendActionRequest{ProfileID: b.UUID, UpdateType: FriendActionAdd}); err != nil {
t.Fatal(err)
}
if _, err := svc.PerformFriendAction(context.Background(), b.UUID, FriendActionRequest{ProfileID: a.UUID, UpdateType: FriendActionAdd}); err != nil {
t.Fatal(err)
}
// A 删除好友
if _, err := svc.PerformFriendAction(context.Background(), a.UUID, FriendActionRequest{ProfileID: b.UUID, UpdateType: FriendActionRemove}); err != nil {
t.Fatalf("A 删除好友失败: %v", err)
}
// B 视角应不再有好友
respB, err := svc.ListFriends(context.Background(), b.UUID)
if err != nil {
t.Fatal(err)
}
if len(respB.Friends) != 0 {
t.Fatalf("B 应无好友, got %+v", respB.Friends)
}
}
// TestDeclineIncomingRequest B 拒绝 A 的请求 -> A 的 outgoing 清空
func TestDeclineIncomingRequest(t *testing.T) {
svc, db := newFriendsService(t)
a := mustCreateProfile(t, db, "alice")
b := mustCreateProfile(t, db, "bob")
if _, err := svc.PerformFriendAction(context.Background(), a.UUID, FriendActionRequest{ProfileID: b.UUID, UpdateType: FriendActionAdd}); err != nil {
t.Fatal(err)
}
// B 拒绝B 用 REMOVE 指向 A
if _, err := svc.PerformFriendAction(context.Background(), b.UUID, FriendActionRequest{ProfileID: a.UUID, UpdateType: FriendActionRemove}); err != nil {
t.Fatalf("B 拒绝失败: %v", err)
}
// A 的 outgoing 应清空
respA, err := svc.ListFriends(context.Background(), a.UUID)
if err != nil {
t.Fatal(err)
}
if len(respA.OutgoingRequests) != 0 {
t.Fatalf("A 的 outgoing 应已清空, got %+v", respA.OutgoingRequests)
}
}
// TestGetAttributes_Default 默认属性
func TestGetAttributes_Default(t *testing.T) {
svc, db := newFriendsService(t)
p := mustCreateProfile(t, db, "a")
resp, err := svc.GetAttributes(context.Background(), p.UUID)
if err != nil {
t.Fatal(err)
}
if !resp.ProfanityFilterPreferences.ProfanityFilterOn {
t.Error("默认应启用脏词过滤")
}
if resp.FriendsPreferences.Friends != "ENABLED" {
t.Errorf("默认 friends = %q, want ENABLED", resp.FriendsPreferences.Friends)
}
}
// TestUpdateAttributes_PartialUpdate 部分更新保留其它字段
func TestUpdateAttributes_PartialUpdate(t *testing.T) {
svc, db := newFriendsService(t)
p := mustCreateProfile(t, db, "a")
off := false
if err := svc.UpdateAttributes(context.Background(), p.UUID, PlayerAttributesRequest{
ProfanityFilterPreferences: &ProfanityFilterPreferences{ProfanityFilterOn: &off},
}); err != nil {
t.Fatalf("UpdateAttributes err: %v", err)
}
var row model.PlayerAttributes
if err := db.First(&row, "profile_uuid = ?", p.UUID).Error; err != nil {
t.Fatalf("查询 row 失败: %v", err)
}
t.Logf("DB row: %+v", row)
resp, err := svc.GetAttributes(context.Background(), p.UUID)
if err != nil {
t.Fatalf("GetAttributes err: %v", err)
}
if resp.ProfanityFilterPreferences.ProfanityFilterOn {
t.Error("脏词过滤应已关闭")
}
if resp.FriendsPreferences.Friends != "ENABLED" {
t.Errorf("friends 应保留 ENABLED, got %q", resp.FriendsPreferences.Friends)
}
}
// TestBlocklist_BlockUnblock 屏蔽/取消屏蔽
func TestBlocklist_BlockUnblock(t *testing.T) {
svc, db := newFriendsService(t)
a := mustCreateProfile(t, db, "alice")
b := mustCreateProfile(t, db, "bob")
// 使用类型断言访问 Block/Unblock接口未暴露但实现有
fs := svc.(*friendsService)
if err := fs.Block(context.Background(), a.UUID, b.UUID); err != nil {
t.Fatalf("屏蔽失败: %v", err)
}
resp, err := svc.GetBlocklist(context.Background(), a.UUID)
if err != nil {
t.Fatal(err)
}
if len(resp.BlockedProfiles) != 1 || resp.BlockedProfiles[0] != b.UUID {
t.Fatalf("屏蔽列表应含 B, got %+v", resp.BlockedProfiles)
}
if err := fs.Unblock(context.Background(), a.UUID, b.UUID); err != nil {
t.Fatalf("取消屏蔽失败: %v", err)
}
resp, err = svc.GetBlocklist(context.Background(), a.UUID)
if err != nil {
t.Fatal(err)
}
if len(resp.BlockedProfiles) != 0 {
t.Fatalf("屏蔽列表应空, got %+v", resp.BlockedProfiles)
}
}

View File

@@ -1,13 +1,12 @@
package service
import (
"carrotskin/internal/model"
"carrotskin/internal/repository"
"context"
"encoding/base64"
"time"
"carrotskin/internal/model"
"carrotskin/internal/repository"
"go.uber.org/zap"
)
@@ -15,8 +14,6 @@ import (
type SerializationService interface {
// SerializeProfile 序列化档案为Yggdrasil格式
SerializeProfile(ctx context.Context, profile model.Profile) map[string]interface{}
// SerializeProfileWithUnsigned 序列化档案为Yggdrasil格式支持unsigned参数
SerializeProfileWithUnsigned(ctx context.Context, profile model.Profile, unsigned bool) map[string]interface{}
// SerializeUser 序列化用户为Yggdrasil格式
SerializeUser(ctx context.Context, user *model.User, uuid string) map[string]interface{}
}
@@ -48,15 +45,10 @@ func NewSerializationService(
}
}
// SerializeProfile 序列化档案为Yggdrasil格式(默认返回签名)
// SerializeProfile 序列化档案为Yggdrasil格式
func (s *yggdrasilSerializationService) SerializeProfile(ctx context.Context, profile model.Profile) map[string]interface{} {
return s.SerializeProfileWithUnsigned(ctx, profile, false)
}
// SerializeProfileWithUnsigned 序列化档案为Yggdrasil格式支持unsigned参数
func (s *yggdrasilSerializationService) SerializeProfileWithUnsigned(ctx context.Context, profile model.Profile, unsigned bool) map[string]interface{} {
// 预分配材质 map最多 SKIN + CAPE 两个条目,避免运行时扩容)
texturesMap := make(map[string]interface{}, 2)
// 创建基本材质数据
texturesMap := make(map[string]interface{})
textures := map[string]interface{}{
"timestamp": time.Now().UnixMilli(),
"profileId": profile.UUID,
@@ -64,7 +56,7 @@ func (s *yggdrasilSerializationService) SerializeProfileWithUnsigned(ctx context
"textures": texturesMap,
}
// 处理皮肤metadata 仅对 SKIN 有效,值为 {"model":"slim"}classic/默认省略 metadata
// 处理皮肤
if profile.SkinID != nil {
skin, err := s.textureRepo.FindByID(ctx, *profile.SkinID)
if err != nil {
@@ -73,19 +65,14 @@ func (s *yggdrasilSerializationService) SerializeProfileWithUnsigned(ctx context
zap.Int64("skinID", *profile.SkinID),
)
} else if skin != nil {
// slim 才需要 metadata 字段classic 直接仅含 url
if skin.IsSlim {
texturesMap["SKIN"] = map[string]interface{}{
"url": skin.URL,
"metadata": map[string]string{"model": "slim"},
}
} else {
texturesMap["SKIN"] = map[string]interface{}{"url": skin.URL}
texturesMap["SKIN"] = map[string]interface{}{
"url": skin.URL,
"metadata": skin.Size,
}
}
}
// 处理披风CAPE 不携带 metadata 字段
// 处理披风
if profile.CapeID != nil {
cape, err := s.textureRepo.FindByID(ctx, *profile.CapeID)
if err != nil {
@@ -94,12 +81,15 @@ func (s *yggdrasilSerializationService) SerializeProfileWithUnsigned(ctx context
zap.Int64("capeID", *profile.CapeID),
)
} else if cape != nil {
texturesMap["CAPE"] = map[string]interface{}{"url": cape.URL}
texturesMap["CAPE"] = map[string]interface{}{
"url": cape.URL,
"metadata": cape.Size,
}
}
}
// 将 textures 编码为 base64
textureBytes, err := json.Marshal(textures)
// 将textures编码为base64
bytes, err := json.Marshal(textures)
if err != nil {
s.logger.Error("序列化textures失败",
zap.Error(err),
@@ -108,31 +98,29 @@ func (s *yggdrasilSerializationService) SerializeProfileWithUnsigned(ctx context
return nil
}
textureData := base64.StdEncoding.EncodeToString(textureBytes)
// 只有在 unsigned=false 时才签名
property := Property{
Name: "textures",
Value: textureData,
}
if !unsigned {
signature, err := s.signatureService.SignStringWithSHA1withRSA(ctx, textureData)
if err != nil {
s.logger.Error("签名textures失败",
zap.Error(err),
zap.String("profileUUID", profile.UUID),
)
return nil
}
property.Signature = signature
textureData := base64.StdEncoding.EncodeToString(bytes)
signature, err := s.signatureService.SignStringWithSHA1withRSA(textureData)
if err != nil {
s.logger.Error("签名textures失败",
zap.Error(err),
zap.String("profileUUID", profile.UUID),
)
return nil
}
// 构建结果
return map[string]interface{}{
"id": profile.UUID,
"name": profile.Name,
"properties": []Property{property},
data := map[string]interface{}{
"id": profile.UUID,
"name": profile.Name,
"properties": []Property{
{
Name: "textures",
Value: textureData,
Signature: signature,
},
},
}
return data
}
// SerializeUser 序列化用户为Yggdrasil格式

View File

@@ -1,16 +1,17 @@
package service
import (
"context"
"errors"
"fmt"
"carrotskin/internal/model"
"carrotskin/internal/repository"
"carrotskin/pkg/redis"
"carrotskin/pkg/utils"
"context"
"errors"
"fmt"
"go.uber.org/zap"
"gorm.io/gorm"
)
// yggdrasilServiceComposite 组合服务,保持接口兼容性
@@ -27,20 +28,20 @@ type yggdrasilServiceComposite struct {
// NewYggdrasilServiceComposite 创建组合服务实例
func NewYggdrasilServiceComposite(
db *gorm.DB,
userRepo repository.UserRepository,
profileRepo repository.ProfileRepository,
yggdrasilRepo repository.YggdrasilRepository,
textureRepo repository.TextureRepository,
signatureService *SignatureService,
redisClient *redis.Client,
logger *zap.Logger,
tokenService TokenService, // 新增TokenService接口
) YggdrasilService {
// 创建各个专门的服务
authService := NewYggdrasilAuthService(userRepo, yggdrasilRepo, logger)
authService := NewYggdrasilAuthService(db, userRepo, yggdrasilRepo, logger)
sessionService := NewSessionService(redisClient, logger)
serializationService := NewSerializationService(
textureRepo,
repository.NewTextureRepository(db),
signatureService,
logger,
)
@@ -84,8 +85,8 @@ func (s *yggdrasilServiceComposite) JoinServer(ctx context.Context, serverID, ac
return fmt.Errorf("验证Token失败: %w", err)
}
// 确保UUID是32位无符号格式用于向后兼容
formattedProfile := utils.FormatUUIDToNoDash(selectedProfile)
// 格式化UUID并验证与Token关联的配置文件
formattedProfile := utils.FormatUUID(selectedProfile)
if uuid != formattedProfile {
return errors.New("selectedProfile与Token不匹配")
}
@@ -114,18 +115,13 @@ func (s *yggdrasilServiceComposite) SerializeProfile(ctx context.Context, profil
return s.serializationService.SerializeProfile(ctx, profile)
}
// SerializeProfileWithUnsigned 序列化档案支持unsigned参数
func (s *yggdrasilServiceComposite) SerializeProfileWithUnsigned(ctx context.Context, profile model.Profile, unsigned bool) map[string]interface{} {
return s.serializationService.SerializeProfileWithUnsigned(ctx, profile, unsigned)
}
// SerializeUser 序列化用户
func (s *yggdrasilServiceComposite) SerializeUser(ctx context.Context, user *model.User, uuid string) map[string]interface{} {
return s.serializationService.SerializeUser(ctx, user, uuid)
}
// GeneratePlayerCertificate 生成玩家证书
func (s *yggdrasilServiceComposite) GeneratePlayerCertificate(ctx context.Context, uuid string) (*PlayerCertificate, error) {
func (s *yggdrasilServiceComposite) GeneratePlayerCertificate(ctx context.Context, uuid string) (map[string]interface{}, error) {
return s.certificateService.GeneratePlayerCertificate(ctx, uuid)
}

View File

@@ -1,15 +1,14 @@
package service
import (
apperrors "carrotskin/internal/errors"
"carrotskin/pkg/redis"
"context"
"fmt"
"net"
"strings"
"time"
apperrors "carrotskin/internal/errors"
"carrotskin/pkg/redis"
"go.uber.org/zap"
)
@@ -83,7 +82,7 @@ func (s *yggdrasilSessionService) CreateSession(ctx context.Context, serverID, a
return apperrors.ErrInvalidAccessToken
}
if username == "" {
return apperrors.ErrUsernameRequired
return apperrors.ErrUsernameMismatch
}
if profileUUID == "" {
return apperrors.ErrProfileMismatch
@@ -127,8 +126,12 @@ func (s *yggdrasilSessionService) CreateSession(ctx context.Context, serverID, a
return nil
}
// GetSession 获取会话数据(内部调用前已对 serverID 校验过,跳过重复校验)
// GetSession 获取会话数据
func (s *yggdrasilSessionService) GetSession(ctx context.Context, serverID string) (*SessionData, error) {
if err := ValidateServerID(serverID); err != nil {
return nil, err
}
// 从Redis获取会话数据
sessionKey := SessionKeyPrefix + serverID
data, err := s.redis.GetBytes(ctx, sessionKey)
@@ -159,7 +162,6 @@ func (s *yggdrasilSessionService) ValidateSession(ctx context.Context, serverID,
return apperrors.ErrSessionMismatch
}
// ValidateSession 由 HasJoinedServer 调用serverID 已经过校验,此处无需重复 ValidateServerID
sessionData, err := s.GetSession(ctx, serverID)
if err != nil {
return apperrors.ErrSessionNotFound

View File

@@ -0,0 +1,81 @@
package service
import (
"errors"
"net"
"regexp"
"strings"
)
// Validator Yggdrasil验证器
type Validator struct{}
// NewValidator 创建验证器实例
func NewValidator() *Validator {
return &Validator{}
}
var (
// emailRegex 邮箱正则表达式
emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$`)
)
// ValidateServerID 验证服务器ID格式
func (v *Validator) ValidateServerID(serverID string) error {
if serverID == "" {
return errors.New("服务器ID不能为空")
}
if len(serverID) > 100 {
return errors.New("服务器ID长度超过限制最大100字符")
}
// 防止注入攻击:检查危险字符
if strings.ContainsAny(serverID, "<>\"'&") {
return errors.New("服务器ID包含非法字符")
}
return nil
}
// ValidateIP 验证IP地址格式
func (v *Validator) ValidateIP(ip string) error {
if ip == "" {
return nil // IP是可选的
}
if net.ParseIP(ip) == nil {
return errors.New("IP地址格式无效")
}
return nil
}
// ValidateEmail 验证邮箱格式
func (v *Validator) ValidateEmail(email string) error {
if email == "" {
return errors.New("邮箱不能为空")
}
if !emailRegex.MatchString(email) {
return errors.New("邮箱格式不正确")
}
return nil
}
// ValidateUUID 验证UUID格式简单验证
func (v *Validator) ValidateUUID(uuid string) error {
if uuid == "" {
return errors.New("UUID不能为空")
}
// UUID格式xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (32个十六进制字符 + 4个连字符)
if len(uuid) < 32 || len(uuid) > 36 {
return errors.New("UUID格式无效")
}
return nil
}
// ValidateAccessToken 验证访问令牌
func (v *Validator) ValidateAccessToken(token string) error {
if token == "" {
return errors.New("访问令牌不能为空")
}
if len(token) < 10 {
return errors.New("访问令牌格式无效")
}
return nil
}

View File

@@ -31,8 +31,6 @@ func NewTestDB(t *testing.T) *gorm.DB {
&model.TextureDownloadLog{},
&model.Client{},
&model.Yggdrasil{},
&model.Friend{},
&model.PlayerAttributes{},
&model.AuditLog{},
&model.CasbinRule{},
); err != nil {

View File

@@ -2,8 +2,13 @@ package types
import "time"
// 注意:BaseResponse 与 PaginationResponse 已删除(与 model.Response /
// model.PaginationResponse 重复)。统一使用 model 包的响应结构
// BaseResponse 基础响应结构
// @Description 通用API响应结构
type BaseResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
// PaginationRequest 分页请求
// @Description 分页查询参数
@@ -12,6 +17,16 @@ type PaginationRequest struct {
PageSize int `json:"page_size" form:"page_size" binding:"omitempty,min=1,max=100"`
}
// PaginationResponse 分页响应
// @Description 分页查询结果
type PaginationResponse struct {
List interface{} `json:"list"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
TotalPages int `json:"total_pages"`
}
// LoginRequest 登录请求
// @Description 用户登录请求参数
type LoginRequest struct {
@@ -26,7 +41,6 @@ type RegisterRequest struct {
Email string `json:"email" binding:"required,email" example:"user@example.com"`
Password string `json:"password" binding:"required,min=6,max=128" example:"password123"`
VerificationCode string `json:"verification_code" binding:"required,len=6" example:"123456"` // 邮箱验证码
CaptchaID string `json:"captcha_id" binding:"required" example:"uuid-xxxx-xxxx"` // 滑动验证码ID
Avatar string `json:"avatar" binding:"omitempty,url" example:"https://rustfs.example.com/avatars/user_1/avatar.png"` // 可选,用户自定义头像
}
@@ -140,7 +154,7 @@ type TextureInfo struct {
// ProfileInfo 角色信息
// @Description Minecraft档案信息
type ProfileInfo struct {
UUID string `json:"uuid" example:"550e8400e29b41d4a716446655440000"`
UUID string `json:"uuid" example:"550e8400-e29b-41d4-a716-446655440000"`
UserID int64 `json:"user_id" example:"1"`
Name string `json:"name" example:"PlayerName"`
SkinID *int64 `json:"skin_id,omitempty" example:"1"`

View File

@@ -7,9 +7,9 @@ import (
// TestPaginationRequest_Validation 测试分页请求验证逻辑
func TestPaginationRequest_Validation(t *testing.T) {
tests := []struct {
name string
page int
pageSize int
name string
page int
pageSize int
wantValid bool
}{
{
@@ -63,15 +63,102 @@ func TestTextureType_Constants(t *testing.T) {
}
}
// TestPaginationRequest_Defaults 测试分页请求结构
// 注意:PaginationResponse 已删除(与 model.PaginationResponse 重复)
func TestPaginationRequest_Defaults(t *testing.T) {
req := PaginationRequest{Page: 1, PageSize: 20}
if req.Page != 1 {
t.Errorf("Page = %d, want 1", req.Page)
// TestPaginationResponse_Structure 测试分页响应结构
func TestPaginationResponse_Structure(t *testing.T) {
resp := PaginationResponse{
List: []string{"a", "b", "c"},
Total: 100,
Page: 1,
PageSize: 20,
TotalPages: 5,
}
if req.PageSize != 20 {
t.Errorf("PageSize = %d, want 20", req.PageSize)
if resp.Total != 100 {
t.Errorf("Total = %d, want 100", resp.Total)
}
if resp.Page != 1 {
t.Errorf("Page = %d, want 1", resp.Page)
}
if resp.PageSize != 20 {
t.Errorf("PageSize = %d, want 20", resp.PageSize)
}
if resp.TotalPages != 5 {
t.Errorf("TotalPages = %d, want 5", resp.TotalPages)
}
}
// TestPaginationResponse_TotalPagesCalculation 测试总页数计算逻辑
func TestPaginationResponse_TotalPagesCalculation(t *testing.T) {
tests := []struct {
name string
total int64
pageSize int
wantPages int
}{
{
name: "正好整除",
total: 100,
pageSize: 20,
wantPages: 5,
},
{
name: "有余数",
total: 101,
pageSize: 20,
wantPages: 6, // 向上取整
},
{
name: "总数小于每页数量",
total: 10,
pageSize: 20,
wantPages: 1,
},
{
name: "总数为0",
total: 0,
pageSize: 20,
wantPages: 0,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// 计算总页数:向上取整
var totalPages int
if tt.total == 0 {
totalPages = 0
} else {
totalPages = int((tt.total + int64(tt.pageSize) - 1) / int64(tt.pageSize))
}
if totalPages != tt.wantPages {
t.Errorf("TotalPages = %d, want %d", totalPages, tt.wantPages)
}
})
}
}
// TestBaseResponse_Structure 测试基础响应结构
func TestBaseResponse_Structure(t *testing.T) {
resp := BaseResponse{
Code: 200,
Message: "success",
Data: "test data",
}
if resp.Code != 200 {
t.Errorf("Code = %d, want 200", resp.Code)
}
if resp.Message != "success" {
t.Errorf("Message = %q, want 'success'", resp.Message)
}
if resp.Data != "test data" {
t.Errorf("Data = %v, want 'test data'", resp.Data)
}
}
@@ -83,10 +170,36 @@ func TestLoginRequest_Validation(t *testing.T) {
password string
wantValid bool
}{
{name: "有效的登录请求", username: "testuser", password: "password123", wantValid: true},
{name: "用户名为空", username: "", password: "password123", wantValid: false},
{name: "密码为空", username: "testuser", password: "", wantValid: false},
{name: "密码长度小于6", username: "testuser", password: "12345", wantValid: false},
{
name: "有效的登录请求",
username: "testuser",
password: "password123",
wantValid: true,
},
{
name: "用户名为空",
username: "",
password: "password123",
wantValid: false,
},
{
name: "密码为空",
username: "testuser",
password: "",
wantValid: false,
},
{
name: "密码长度小于6",
username: "testuser",
password: "12345",
wantValid: false,
},
{
name: "密码长度超过128",
username: "testuser",
password: string(make([]byte, 129)),
wantValid: false,
},
}
for _, tt := range tests {
@@ -98,3 +211,174 @@ func TestLoginRequest_Validation(t *testing.T) {
})
}
}
// TestRegisterRequest_Validation 测试注册请求验证逻辑
func TestRegisterRequest_Validation(t *testing.T) {
tests := []struct {
name string
username string
email string
password string
verificationCode string
wantValid bool
}{
{
name: "有效的注册请求",
username: "newuser",
email: "user@example.com",
password: "password123",
verificationCode: "123456",
wantValid: true,
},
{
name: "用户名为空",
username: "",
email: "user@example.com",
password: "password123",
verificationCode: "123456",
wantValid: false,
},
{
name: "用户名长度小于3",
username: "ab",
email: "user@example.com",
password: "password123",
verificationCode: "123456",
wantValid: false,
},
{
name: "用户名长度超过50",
username: string(make([]byte, 51)),
email: "user@example.com",
password: "password123",
verificationCode: "123456",
wantValid: false,
},
{
name: "邮箱格式无效",
username: "newuser",
email: "invalid-email",
password: "password123",
verificationCode: "123456",
wantValid: false,
},
{
name: "验证码长度不是6",
username: "newuser",
email: "user@example.com",
password: "password123",
verificationCode: "12345",
wantValid: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
isValid := tt.username != "" &&
len(tt.username) >= 3 && len(tt.username) <= 50 &&
tt.email != "" && contains(tt.email, "@") &&
len(tt.password) >= 6 && len(tt.password) <= 128 &&
len(tt.verificationCode) == 6
if isValid != tt.wantValid {
t.Errorf("Validation failed: got %v, want %v", isValid, tt.wantValid)
}
})
}
}
// 辅助函数
func contains(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}
// TestResetPasswordRequest_Validation 测试重置密码请求验证
func TestResetPasswordRequest_Validation(t *testing.T) {
tests := []struct {
name string
email string
verificationCode string
newPassword string
wantValid bool
}{
{
name: "有效的重置密码请求",
email: "user@example.com",
verificationCode: "123456",
newPassword: "newpassword123",
wantValid: true,
},
{
name: "邮箱为空",
email: "",
verificationCode: "123456",
newPassword: "newpassword123",
wantValid: false,
},
{
name: "验证码长度不是6",
email: "user@example.com",
verificationCode: "12345",
newPassword: "newpassword123",
wantValid: false,
},
{
name: "新密码长度小于6",
email: "user@example.com",
verificationCode: "123456",
newPassword: "12345",
wantValid: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
isValid := tt.email != "" &&
len(tt.verificationCode) == 6 &&
len(tt.newPassword) >= 6 && len(tt.newPassword) <= 128
if isValid != tt.wantValid {
t.Errorf("Validation failed: got %v, want %v", isValid, tt.wantValid)
}
})
}
}
// TestCreateProfileRequest_Validation 测试创建档案请求验证
func TestCreateProfileRequest_Validation(t *testing.T) {
tests := []struct {
name string
profileName string
wantValid bool
}{
{
name: "有效的档案名",
profileName: "PlayerName",
wantValid: true,
},
{
name: "档案名为空",
profileName: "",
wantValid: false,
},
{
name: "档案名长度超过16",
profileName: string(make([]byte, 17)),
wantValid: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
isValid := tt.profileName != "" &&
len(tt.profileName) >= 1 && len(tt.profileName) <= 16
if isValid != tt.wantValid {
t.Errorf("Validation failed: got %v, want %v", isValid, tt.wantValid)
}
})
}
}

View File

@@ -4,7 +4,7 @@ import (
"fmt"
"sync"
"github.com/casbin/casbin/v3"
"github.com/casbin/casbin/v2"
gormadapter "github.com/casbin/gorm-adapter/v3"
"go.uber.org/zap"
"gorm.io/gorm"

View File

@@ -1,8 +1,46 @@
package auth
// 本文件原包含基于 sync.Once 的全局单例Init/GetJWTService/MustGetJWTService
//
// 在 DI 迁移阶段4全局单例已被移除。JWT 服务由 fx.Provide 构造
// (见 internal/app/infra_module.go通过构造函数参数注入到各消费者。
//
// JWT 服务构造逻辑见 jwt.go 的 NewJWTService()。
import (
"carrotskin/pkg/config"
"fmt"
"sync"
)
var (
// jwtServiceInstance 全局JWT服务实例
jwtServiceInstance *JWTService
// once 确保只初始化一次
once sync.Once
// initError 初始化错误
)
// Init 初始化JWT服务线程安全只会执行一次
func Init(cfg config.JWTConfig) error {
once.Do(func() {
jwtServiceInstance = NewJWTService(cfg.Secret, cfg.ExpireHours)
})
return nil
}
// GetJWTService 获取JWT服务实例线程安全
func GetJWTService() (*JWTService, error) {
if jwtServiceInstance == nil {
return nil, fmt.Errorf("JWT服务未初始化请先调用 auth.Init()")
}
return jwtServiceInstance, nil
}
// MustGetJWTService 获取JWT服务实例如果未初始化则panic
func MustGetJWTService() *JWTService {
service, err := GetJWTService()
if err != nil {
panic(err)
}
return service
}

86
pkg/auth/manager_test.go Normal file
View File

@@ -0,0 +1,86 @@
package auth
import (
"carrotskin/pkg/config"
"testing"
)
// TestGetJWTService_NotInitialized 测试未初始化时获取JWT服务
func TestGetJWTService_NotInitialized(t *testing.T) {
_, err := GetJWTService()
if err == nil {
t.Error("未初始化时应该返回错误")
}
expectedError := "JWT服务未初始化请先调用 auth.Init()"
if err.Error() != expectedError {
t.Errorf("错误消息 = %q, want %q", err.Error(), expectedError)
}
}
// TestMustGetJWTService_Panic 测试MustGetJWTService在未初始化时panic
func TestMustGetJWTService_Panic(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("MustGetJWTService 应该在未初始化时panic")
}
}()
_ = MustGetJWTService()
}
// TestInit_JWTService 测试JWT服务初始化
func TestInit_JWTService(t *testing.T) {
cfg := config.JWTConfig{
Secret: "test-secret-key",
ExpireHours: 24,
}
err := Init(cfg)
if err != nil {
t.Errorf("Init() 错误 = %v, want nil", err)
}
// 验证可以获取服务
service, err := GetJWTService()
if err != nil {
t.Errorf("GetJWTService() 错误 = %v, want nil", err)
}
if service == nil {
t.Error("GetJWTService() 返回的服务不应为nil")
}
}
// TestInit_JWTService_Once 测试Init只执行一次
func TestInit_JWTService_Once(t *testing.T) {
cfg := config.JWTConfig{
Secret: "test-secret-key-1",
ExpireHours: 24,
}
// 第一次初始化
err1 := Init(cfg)
if err1 != nil {
t.Fatalf("第一次Init() 错误 = %v", err1)
}
service1, _ := GetJWTService()
// 第二次初始化(应该不会改变服务)
cfg2 := config.JWTConfig{
Secret: "test-secret-key-2",
ExpireHours: 48,
}
err2 := Init(cfg2)
if err2 != nil {
t.Fatalf("第二次Init() 错误 = %v", err2)
}
service2, _ := GetJWTService()
// 验证是同一个实例sync.Once保证
if service1 != service2 {
t.Error("Init应该只执行一次返回同一个实例")
}
}

View File

@@ -1,13 +1,29 @@
package auth
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"sync"
"time"
"github.com/golang-jwt/jwt/v5"
)
const (
YggdrasilPrivateKeyRedisKey = "yggdrasil:private_key"
)
// RedisClient 定义Redis客户端接口用于测试
type RedisClient interface {
Get(ctx context.Context, key string) (string, error)
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
}
// YggdrasilJWTService Yggdrasil JWT服务使用RSA512
type YggdrasilJWTService struct {
privateKey *rsa.PrivateKey
@@ -106,3 +122,98 @@ func (j *YggdrasilJWTService) ParseAccessToken(accessToken string, stalePolicy S
func (j *YggdrasilJWTService) GetPublicKey() *rsa.PublicKey {
return j.publicKey
}
// YggdrasilJWTManager Yggdrasil JWT管理器用于获取或创建JWT服务
type YggdrasilJWTManager struct {
redisClient RedisClient
jwtService *YggdrasilJWTService
privateKey *rsa.PrivateKey
mu sync.RWMutex
}
// NewYggdrasilJWTManager 创建Yggdrasil JWT管理器
func NewYggdrasilJWTManager(redisClient RedisClient) *YggdrasilJWTManager {
return &YggdrasilJWTManager{
redisClient: redisClient,
}
}
// GetJWTService 获取或创建Yggdrasil JWT服务线程安全
func (m *YggdrasilJWTManager) GetJWTService() (*YggdrasilJWTService, error) {
m.mu.RLock()
if m.jwtService != nil {
service := m.jwtService
m.mu.RUnlock()
return service, nil
}
m.mu.RUnlock()
m.mu.Lock()
defer m.mu.Unlock()
// 双重检查
if m.jwtService != nil {
return m.jwtService, nil
}
// 从Redis获取私钥
privateKey, err := m.getPrivateKeyFromRedis()
if err != nil {
return nil, fmt.Errorf("获取私钥失败: %w", err)
}
m.privateKey = privateKey
m.jwtService = NewYggdrasilJWTService(privateKey, "carrotskin")
return m.jwtService, nil
}
// SetPrivateKey 直接设置私钥用于测试或直接从signatureService获取
func (m *YggdrasilJWTManager) SetPrivateKey(privateKey *rsa.PrivateKey) {
m.mu.Lock()
defer m.mu.Unlock()
m.privateKey = privateKey
if privateKey != nil {
m.jwtService = NewYggdrasilJWTService(privateKey, "carrotskin")
}
}
// getPrivateKeyFromRedis 从Redis获取私钥
func (m *YggdrasilJWTManager) getPrivateKeyFromRedis() (*rsa.PrivateKey, error) {
if m.privateKey != nil {
return m.privateKey, nil
}
ctx := context.Background()
privateKeyPEM, err := m.redisClient.Get(ctx, YggdrasilPrivateKeyRedisKey)
if err != nil || privateKeyPEM == "" {
return nil, fmt.Errorf("从Redis获取私钥失败: %w", err)
}
// 解析PEM格式的私钥
block, _ := pem.Decode([]byte(privateKeyPEM))
if block == nil {
return nil, fmt.Errorf("解析PEM私钥失败")
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("解析RSA私钥失败: %w", err)
}
return privateKey, nil
}
// GenerateKeyPair 生成RSA密钥对用于测试
func GenerateKeyPair() (*rsa.PrivateKey, error) {
return rsa.GenerateKey(rand.Reader, 2048)
}
// EncodePrivateKeyToPEM 将私钥编码为PEM格式用于测试
func EncodePrivateKeyToPEM(privateKey *rsa.PrivateKey) (string, error) {
privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey)
privateKeyPEM := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: privateKeyBytes,
})
return string(privateKeyPEM), nil
}

View File

@@ -1,16 +1,65 @@
package auth
import (
"crypto/rand"
"context"
"crypto/rsa"
"errors"
"testing"
"time"
"github.com/redis/go-redis/v9"
)
// generateTestKeyPair 生成测试用的 RSA 密钥对
// MockRedisClient 模拟Redis客户端
type MockRedisClient struct {
data map[string]string
err error
}
func NewMockRedisClient() *MockRedisClient {
return &MockRedisClient{
data: make(map[string]string),
}
}
func (m *MockRedisClient) Get(ctx context.Context, key string) (string, error) {
if m.err != nil {
return "", m.err
}
if val, ok := m.data[key]; ok {
return val, nil
}
return "", redis.Nil
}
func (m *MockRedisClient) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
if m.err != nil {
return m.err
}
m.data[key] = value.(string)
return nil
}
func (m *MockRedisClient) SetError(err error) {
m.err = err
}
func (m *MockRedisClient) ClearError() {
m.err = nil
}
func (m *MockRedisClient) SetData(key, value string) {
m.data[key] = value
}
func (m *MockRedisClient) Clear() {
m.data = make(map[string]string)
m.err = nil
}
// 测试辅助函数:生成测试用的密钥对
func generateTestKeyPair(t *testing.T) *rsa.PrivateKey {
t.Helper()
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
privateKey, err := GenerateKeyPair()
if err != nil {
t.Fatalf("生成密钥对失败: %v", err)
}
@@ -236,6 +285,169 @@ func TestYggdrasilJWTService_GetPublicKey(t *testing.T) {
}
}
func TestNewYggdrasilJWTManager(t *testing.T) {
mockRedis := NewMockRedisClient()
manager := NewYggdrasilJWTManager(mockRedis)
if manager == nil {
t.Fatal("管理器创建失败")
}
if manager.redisClient != mockRedis {
t.Error("Redis客户端未正确设置")
}
}
func TestYggdrasilJWTManager_SetPrivateKey(t *testing.T) {
mockRedis := NewMockRedisClient()
manager := NewYggdrasilJWTManager(mockRedis)
privateKey := generateTestKeyPair(t)
manager.SetPrivateKey(privateKey)
// 验证JWT服务已创建
service, err := manager.GetJWTService()
if err != nil {
t.Fatalf("获取JWT服务失败: %v", err)
}
if service == nil {
t.Fatal("JWT服务不应为nil")
}
// 验证服务可以正常工作
if service.GetPublicKey() == nil {
t.Error("公钥不应为nil")
}
}
func TestYggdrasilJWTManager_GetJWTService_FromPrivateKey(t *testing.T) {
mockRedis := NewMockRedisClient()
manager := NewYggdrasilJWTManager(mockRedis)
privateKey := generateTestKeyPair(t)
manager.SetPrivateKey(privateKey)
// 第一次获取
service1, err := manager.GetJWTService()
if err != nil {
t.Fatalf("获取JWT服务失败: %v", err)
}
// 第二次获取应该返回同一个实例
service2, err := manager.GetJWTService()
if err != nil {
t.Fatalf("获取JWT服务失败: %v", err)
}
if service1 != service2 {
t.Error("应该返回同一个JWT服务实例")
}
}
func TestYggdrasilJWTManager_GetJWTService_FromRedis(t *testing.T) {
mockRedis := NewMockRedisClient()
manager := NewYggdrasilJWTManager(mockRedis)
privateKey := generateTestKeyPair(t)
privateKeyPEM, err := EncodePrivateKeyToPEM(privateKey)
if err != nil {
t.Fatalf("编码私钥失败: %v", err)
}
// 设置Redis数据
mockRedis.SetData(YggdrasilPrivateKeyRedisKey, privateKeyPEM)
// 获取JWT服务
service, err := manager.GetJWTService()
if err != nil {
t.Fatalf("获取JWT服务失败: %v", err)
}
if service == nil {
t.Error("JWT服务不应为nil")
}
// 验证服务可以正常工作
token, err := service.GenerateAccessToken(123, "client-uuid", 1, "profile-uuid",
time.Now().Add(24*time.Hour), time.Now().Add(30*24*time.Hour))
if err != nil {
t.Fatalf("生成Token失败: %v", err)
}
if token == "" {
t.Error("Token不应为空")
}
}
func TestYggdrasilJWTManager_GetJWTService_RedisError(t *testing.T) {
mockRedis := NewMockRedisClient()
manager := NewYggdrasilJWTManager(mockRedis)
// 设置Redis错误
mockRedis.SetError(errors.New("redis connection error"))
// 尝试获取JWT服务应该失败
_, err := manager.GetJWTService()
if err == nil {
t.Error("期望出现错误,但没有错误")
}
}
func TestYggdrasilJWTManager_GetJWTService_InvalidPEM(t *testing.T) {
mockRedis := NewMockRedisClient()
manager := NewYggdrasilJWTManager(mockRedis)
// 设置无效的PEM数据
mockRedis.SetData(YggdrasilPrivateKeyRedisKey, "invalid-pem-data")
// 尝试获取JWT服务应该失败
_, err := manager.GetJWTService()
if err == nil {
t.Error("期望出现错误,但没有错误")
}
}
func TestYggdrasilJWTManager_GetJWTService_Concurrent(t *testing.T) {
mockRedis := NewMockRedisClient()
manager := NewYggdrasilJWTManager(mockRedis)
privateKey := generateTestKeyPair(t)
privateKeyPEM, err := EncodePrivateKeyToPEM(privateKey)
if err != nil {
t.Fatalf("编码私钥失败: %v", err)
}
mockRedis.SetData(YggdrasilPrivateKeyRedisKey, privateKeyPEM)
// 并发获取JWT服务
const numGoroutines = 10
results := make(chan *YggdrasilJWTService, numGoroutines)
errors := make(chan error, numGoroutines)
for i := 0; i < numGoroutines; i++ {
go func() {
service, err := manager.GetJWTService()
if err != nil {
errors <- err
return
}
results <- service
}()
}
// 收集结果
services := make(map[*YggdrasilJWTService]bool)
for i := 0; i < numGoroutines; i++ {
select {
case service := <-results:
services[service] = true
case err := <-errors:
t.Fatalf("获取JWT服务失败: %v", err)
}
}
// 所有goroutine应该返回同一个服务实例
if len(services) != 1 {
t.Errorf("期望所有goroutine返回同一个服务实例但得到 %d 个不同的实例", len(services))
}
}
func TestYggdrasilTokenClaims_EmptyProfileID(t *testing.T) {
privateKey := generateTestKeyPair(t)
service := NewYggdrasilJWTService(privateKey, "test-issuer")

View File

@@ -65,21 +65,18 @@ type DatabaseConfig struct {
// RedisConfig Redis配置
type RedisConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Password string `mapstructure:"password"`
Database int `mapstructure:"database"`
PoolSize int `mapstructure:"pool_size"` // 连接池大小
MinIdleConns int `mapstructure:"min_idle_conns"` // 最小空闲连接数
MaxRetries int `mapstructure:"max_retries"` // 最大重试次数
DialTimeout time.Duration `mapstructure:"dial_timeout"` // 连接超时
ReadTimeout time.Duration `mapstructure:"read_timeout"` // 读取超时
WriteTimeout time.Duration `mapstructure:"write_timeout"` // 写入超时
PoolTimeout time.Duration `mapstructure:"pool_timeout"` // 连接池超时
ConnMaxIdleTime time.Duration `mapstructure:"conn_max_idle_time"` // 连接最大空闲时间
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"` // 连接最大生命周期(新增)
HealthCheckInterval time.Duration `mapstructure:"health_check_interval"` // 健康检查间隔(新增)
EnableRetryOnError bool `mapstructure:"enable_retry_on_error"` // 错误时启用重试(新增)
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Password string `mapstructure:"password"`
Database int `mapstructure:"database"`
PoolSize int `mapstructure:"pool_size"` // 连接池大小
MinIdleConns int `mapstructure:"min_idle_conns"` // 最小空闲连接数
MaxRetries int `mapstructure:"max_retries"` // 最大重试次数
DialTimeout time.Duration `mapstructure:"dial_timeout"` // 连接超时
ReadTimeout time.Duration `mapstructure:"read_timeout"` // 读取超时
WriteTimeout time.Duration `mapstructure:"write_timeout"` // 写入超时
PoolTimeout time.Duration `mapstructure:"pool_timeout"` // 连接池超时
ConnMaxIdleTime time.Duration `mapstructure:"conn_max_idle_time"` // 连接最大空闲时间
}
// RustFSConfig RustFS对象存储配置 (S3兼容)
@@ -195,21 +192,18 @@ func setDefaults() {
viper.SetDefault("database.conn_max_lifetime", "1h")
viper.SetDefault("database.conn_max_idle_time", "10m")
// Redis默认配置(优化后的默认值)
// Redis默认配置
viper.SetDefault("redis.host", "localhost")
viper.SetDefault("redis.port", 6379)
viper.SetDefault("redis.database", 0)
viper.SetDefault("redis.pool_size", 16) // 优化:提高默认连接池大小
viper.SetDefault("redis.min_idle_conns", 8) // 优化:提高最小空闲连接数
viper.SetDefault("redis.pool_size", 10)
viper.SetDefault("redis.min_idle_conns", 5)
viper.SetDefault("redis.max_retries", 3)
viper.SetDefault("redis.dial_timeout", "5s")
viper.SetDefault("redis.read_timeout", "3s")
viper.SetDefault("redis.write_timeout", "3s")
viper.SetDefault("redis.pool_timeout", "4s")
viper.SetDefault("redis.conn_max_idle_time", "10m") // 优化:减少空闲连接超时时间
viper.SetDefault("redis.conn_max_lifetime", "30m") // 新增:连接最大生命周期
viper.SetDefault("redis.health_check_interval", "30s") // 新增:健康检查间隔
viper.SetDefault("redis.enable_retry_on_error", true) // 新增:错误时启用重试
viper.SetDefault("redis.conn_max_idle_time", "30m")
// RustFS默认配置
viper.SetDefault("rustfs.endpoint", "127.0.0.1:9000")
@@ -259,7 +253,6 @@ func setupEnvMappings() {
viper.BindEnv("server.read_timeout", "SERVER_READ_TIMEOUT")
viper.BindEnv("server.write_timeout", "SERVER_WRITE_TIMEOUT")
viper.BindEnv("server.swagger_enabled", "SERVER_SWAGGER_ENABLED")
viper.BindEnv("environment", "ENVIRONMENT")
// 数据库配置
viper.BindEnv("database.driver", "DATABASE_DRIVER")
@@ -288,9 +281,6 @@ func setupEnvMappings() {
viper.BindEnv("redis.write_timeout", "REDIS_WRITE_TIMEOUT")
viper.BindEnv("redis.pool_timeout", "REDIS_POOL_TIMEOUT")
viper.BindEnv("redis.conn_max_idle_time", "REDIS_CONN_MAX_IDLE_TIME")
viper.BindEnv("redis.conn_max_lifetime", "REDIS_CONN_MAX_LIFETIME")
viper.BindEnv("redis.health_check_interval", "REDIS_HEALTH_CHECK_INTERVAL")
viper.BindEnv("redis.enable_retry_on_error", "REDIS_ENABLE_RETRY_ON_ERROR")
// RustFS配置
viper.BindEnv("rustfs.endpoint", "RUSTFS_ENDPOINT")
@@ -307,10 +297,6 @@ func setupEnvMappings() {
viper.BindEnv("log.level", "LOG_LEVEL")
viper.BindEnv("log.format", "LOG_FORMAT")
viper.BindEnv("log.output", "LOG_OUTPUT")
viper.BindEnv("log.max_size", "LOG_MAX_SIZE")
viper.BindEnv("log.max_backups", "LOG_MAX_BACKUPS")
viper.BindEnv("log.max_age", "LOG_MAX_AGE")
viper.BindEnv("log.compress", "LOG_COMPRESS")
// 邮件配置
viper.BindEnv("email.enabled", "EMAIL_ENABLED")
@@ -441,28 +427,15 @@ func overrideFromEnv(config *Config) {
}
}
if connMaxLifetime := os.Getenv("REDIS_CONN_MAX_LIFETIME"); connMaxLifetime != "" {
if val, err := time.ParseDuration(connMaxLifetime); err == nil {
config.Redis.ConnMaxLifetime = val
}
}
if healthCheckInterval := os.Getenv("REDIS_HEALTH_CHECK_INTERVAL"); healthCheckInterval != "" {
if val, err := time.ParseDuration(healthCheckInterval); err == nil {
config.Redis.HealthCheckInterval = val
}
}
if enableRetryOnError := os.Getenv("REDIS_ENABLE_RETRY_ON_ERROR"); enableRetryOnError != "" {
config.Redis.EnableRetryOnError = enableRetryOnError == "true" || enableRetryOnError == "1"
}
// 处理邮件配置
if emailEnabled := os.Getenv("EMAIL_ENABLED"); emailEnabled != "" {
config.Email.Enabled = emailEnabled == "true" || emailEnabled == "True" || emailEnabled == "TRUE" || emailEnabled == "1"
}
// 处理环境配置(已由 BindEnv("environment", "ENVIRONMENT") + AutomaticEnv 处理)
// 处理环境配置
if env := os.Getenv("ENVIRONMENT"); env != "" {
config.Environment = env
}
// 处理安全配置
if allowedOrigins := os.Getenv("SECURITY_ALLOWED_ORIGINS"); allowedOrigins != "" {

View File

@@ -1,8 +1,71 @@
package config
// 本文件原包含基于 sync.Once 的全局单例Init/GetConfig/MustGetConfig/GetRustFSConfig
//
// 在 DI 迁移阶段4全局单例已被移除。配置通过 config.Load() 加载,
// 由 fx.Supply 注入到依赖图中。各消费者通过构造函数参数接收 *Config 或子配置。
//
// 配置加载逻辑见 config.go 的 Load()。
import (
"fmt"
"sync"
)
var (
// configInstance 全局配置实例
configInstance *Config
// rustFSConfigInstance 全局RustFS配置实例
rustFSConfigInstance *RustFSConfig
// once 确保只初始化一次
once sync.Once
// initError 初始化错误
initError error
)
// Init 初始化配置(线程安全,只会执行一次)
func Init() error {
once.Do(func() {
configInstance, initError = Load()
if initError != nil {
return
}
rustFSConfigInstance = &configInstance.RustFS
})
return initError
}
// GetConfig 获取配置实例(线程安全)
func GetConfig() (*Config, error) {
if configInstance == nil {
return nil, fmt.Errorf("配置未初始化,请先调用 config.Init()")
}
return configInstance, nil
}
// MustGetConfig 获取配置实例如果未初始化则panic
func MustGetConfig() *Config {
cfg, err := GetConfig()
if err != nil {
panic(err)
}
return cfg
}
// GetRustFSConfig 获取RustFS配置实例线程安全
func GetRustFSConfig() (*RustFSConfig, error) {
if rustFSConfigInstance == nil {
return nil, fmt.Errorf("配置未初始化,请先调用 config.Init()")
}
return rustFSConfigInstance, nil
}
// MustGetRustFSConfig 获取RustFS配置实例如果未初始化则panic
func MustGetRustFSConfig() *RustFSConfig {
cfg, err := GetRustFSConfig()
if err != nil {
panic(err)
}
return cfg
}

View File

@@ -4,19 +4,67 @@ import (
"testing"
)
// TestLoad_Config 验证 Load() 能成功加载配置(从环境变量/默认值)
// 全局单例访问器GetConfig/MustGetConfig已在 DI 迁移中移除,
// 配置通过 config.Load() 加载并由 fx.Supply 注入。
func TestLoad_Config(t *testing.T) {
cfg, err := Load()
if err != nil {
t.Fatalf("Load() 返回错误: %v", err)
// TestGetConfig_NotInitialized 测试未初始化时获取配置
func TestGetConfig_NotInitialized(t *testing.T) {
// 重置全局变量(在实际测试中可能需要更复杂的重置逻辑)
// 注意:由于使用了 sync.Once这个测试主要验证错误处理逻辑
// 测试未初始化时的错误消息
_, err := GetConfig()
if err == nil {
t.Error("未初始化时应该返回错误")
}
if cfg == nil {
t.Fatal("Load() 返回 nil 配置")
}
// 验证默认值生效
if cfg.Server.Port == "" {
t.Error("Server.Port 不应为空")
expectedError := "配置未初始化,请先调用 config.Init()"
if err.Error() != expectedError {
t.Errorf("错误消息 = %q, want %q", err.Error(), expectedError)
}
}
// TestMustGetConfig_Panic 测试MustGetConfig在未初始化时panic
func TestMustGetConfig_Panic(t *testing.T) {
// 注意这个测试会触发panic需要recover
defer func() {
if r := recover(); r == nil {
t.Error("MustGetConfig 应该在未初始化时panic")
}
}()
// 尝试获取未初始化的配置
_ = MustGetConfig()
}
// TestGetRustFSConfig_NotInitialized 测试未初始化时获取RustFS配置
func TestGetRustFSConfig_NotInitialized(t *testing.T) {
_, err := GetRustFSConfig()
if err == nil {
t.Error("未初始化时应该返回错误")
}
expectedError := "配置未初始化,请先调用 config.Init()"
if err.Error() != expectedError {
t.Errorf("错误消息 = %q, want %q", err.Error(), expectedError)
}
}
// TestMustGetRustFSConfig_Panic 测试MustGetRustFSConfig在未初始化时panic
func TestMustGetRustFSConfig_Panic(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("MustGetRustFSConfig 应该在未初始化时panic")
}
}()
_ = MustGetRustFSConfig()
}
// TestInit_Once 测试Init只执行一次的逻辑
func TestInit_Once(t *testing.T) {
// 注意由于sync.Once的特性这个测试主要验证逻辑
// 实际测试中可能需要重置机制
// 验证Init函数可调用函数不能直接比较nil
// 这里只验证函数存在
_ = Init
}

View File

@@ -122,11 +122,7 @@ func (cm *CacheManager) Set(ctx context.Context, key string, value interface{},
// SetAsync 异步设置缓存,避免在主请求链路阻塞
func (cm *CacheManager) SetAsync(ctx context.Context, key string, value interface{}, expiration ...time.Duration) {
go func() {
// 使用独立 ctx 配合超时,防止上游 ctx 取消导致缓存写入失败,
// 同时避免 Redis 卡死时 goroutine 永久堆积
asyncCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
_ = cm.Set(asyncCtx, key, value, expiration...)
_ = cm.Set(ctx, key, value, expiration...)
}()
}
@@ -373,6 +369,11 @@ func (b *CacheKeyBuilder) ProfilePattern(userID int64) string {
return fmt.Sprintf("%sprofile:*:%d*", b.prefix, userID)
}
// UserFavoritesPattern 用户收藏相关的所有缓存键模式
func (b *CacheKeyBuilder) UserFavoritesPattern(userID int64) string {
return fmt.Sprintf("%sfavorites:*:%d*", b.prefix, userID)
}
// Exists 检查缓存键是否存在
func (cm *CacheManager) Exists(ctx context.Context, key string) (bool, error) {
if !cm.config.Enabled || cm.redis == nil {

View File

@@ -1,27 +1,65 @@
package database
import (
"fmt"
"carrotskin/internal/model"
"carrotskin/pkg/config"
"fmt"
"sync"
"go.uber.org/zap"
"gorm.io/gorm"
)
// 本文件原包含基于 sync.Once 的全局单例Init/GetDB/MustGetDB/GetDBWrapper
//
// 在 DI 迁移阶段4全局单例已被移除。数据库连接由 fx.Provide 构造
// (见 internal/app/infra_module.go 的 provideDatabase通过构造函数参数
// 注入 *database.DB 与 *gorm.DB 到各消费者。
//
// 数据库构造逻辑见 postgres.go 的 New()。
var (
// dbInstance 全局数据库实例
dbInstance *gorm.DB
// once 确保只初始化一次
once sync.Once
// initError 初始化错误
initError error
)
// Init 初始化数据库连接(线程安全,只会执行一次)
func Init(cfg config.DatabaseConfig, logger *zap.Logger) error {
once.Do(func() {
dbInstance, initError = New(cfg)
if initError != nil {
logger.Error("数据库初始化失败", zap.Error(initError))
return
}
logger.Info("数据库连接成功")
})
return initError
}
// GetDB 获取数据库实例(线程安全)
func GetDB() (*gorm.DB, error) {
if dbInstance == nil {
return nil, fmt.Errorf("数据库未初始化,请先调用 database.Init()")
}
return dbInstance, nil
}
// MustGetDB 获取数据库实例如果未初始化则panic
func MustGetDB() *gorm.DB {
db, err := GetDB()
if err != nil {
panic(err)
}
return db
}
// AutoMigrate 自动迁移数据库表结构
func AutoMigrate(logger *zap.Logger) error {
db, err := GetDB()
if err != nil {
return fmt.Errorf("获取数据库实例失败: %w", err)
}
// AutoMigrateWithDB 使用指定的 *gorm.DB 执行表结构迁移(供 DI 使用)。
// 注意表的创建顺序:先创建被引用的表,再创建引用表。
func AutoMigrateWithDB(db *gorm.DB, logger *zap.Logger) error {
logger.Info("开始执行数据库迁移...")
// 迁移所有表 - 注意顺序:先创建被引用的表,再创建引用表
// 使用分批迁移,避免某些表的问题影响其他表
tables := []interface{}{
// 用户相关表(先创建,因为其他表可能引用它)
&model.User{},
@@ -42,10 +80,6 @@ func AutoMigrateWithDB(db *gorm.DB, logger *zap.Logger) error {
// Yggdrasil相关表在User之后创建因为它引用User
&model.Yggdrasil{},
// 好友系统相关表(好友关系、玩家偏好属性)
&model.Friend{},
&model.PlayerAttributes{},
// 审计日志表
&model.AuditLog{},
@@ -53,6 +87,7 @@ func AutoMigrateWithDB(db *gorm.DB, logger *zap.Logger) error {
&model.CasbinRule{},
}
// 批量迁移表
if err := db.AutoMigrate(tables...); err != nil {
logger.Error("数据库迁移失败", zap.Error(err))
return fmt.Errorf("数据库迁移失败: %w", err)
@@ -61,3 +96,17 @@ func AutoMigrateWithDB(db *gorm.DB, logger *zap.Logger) error {
logger.Info("数据库迁移完成")
return nil
}
// Close 关闭数据库连接
func Close() error {
if dbInstance == nil {
return nil
}
sqlDB, err := dbInstance.DB()
if err != nil {
return err
}
return sqlDB.Close()
}

View File

@@ -8,16 +8,17 @@ import (
"gorm.io/gorm"
)
// 使用内存 sqlite 验证 AutoMigrateWithDB 关键路径,无需真实 Postgres
// 全局单例访问器Init/GetDB/MustGetDB已在 DI 迁移中移除。
// 使用内存 sqlite 验证 AutoMigrate 关键路径,无需真实 Postgres
func TestAutoMigrate_WithSQLite(t *testing.T) {
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
if err != nil {
t.Fatalf("open sqlite err: %v", err)
}
dbInstance = db
defer func() { dbInstance = nil }()
logger := zaptest.NewLogger(t)
if err := AutoMigrateWithDB(db, logger); err != nil {
t.Fatalf("AutoMigrateWithDB sqlite err: %v", err)
if err := AutoMigrate(logger); err != nil {
t.Fatalf("AutoMigrate sqlite err: %v", err)
}
}

View File

@@ -0,0 +1,87 @@
package database
import (
"carrotskin/pkg/config"
"testing"
"go.uber.org/zap/zaptest"
)
// TestGetDB_NotInitialized 测试未初始化时获取数据库实例
func TestGetDB_NotInitialized(t *testing.T) {
dbInstance = nil
_, err := GetDB()
if err == nil {
t.Error("未初始化时应该返回错误")
}
expectedError := "数据库未初始化,请先调用 database.Init()"
if err.Error() != expectedError {
t.Errorf("错误消息 = %q, want %q", err.Error(), expectedError)
}
}
// TestMustGetDB_Panic 测试MustGetDB在未初始化时panic
func TestMustGetDB_Panic(t *testing.T) {
dbInstance = nil
defer func() {
if r := recover(); r == nil {
t.Error("MustGetDB 应该在未初始化时panic")
}
}()
_ = MustGetDB()
}
// TestInit_Database 测试数据库初始化逻辑
func TestInit_Database(t *testing.T) {
dbInstance = nil
cfg := config.DatabaseConfig{
Driver: "postgres",
Host: "localhost",
Port: 5432,
Username: "postgres",
Password: "password",
Database: "testdb",
SSLMode: "disable",
Timezone: "Asia/Shanghai",
MaxIdleConns: 10,
MaxOpenConns: 100,
ConnMaxLifetime: 0,
}
logger := zaptest.NewLogger(t)
// 验证Init函数存在且可调用
// 注意:实际连接可能失败,这是可以接受的
err := Init(cfg, logger)
if err != nil {
t.Skipf("数据库未运行,跳过连接测试: %v", err)
}
}
// TestAutoMigrate_ErrorHandling 测试AutoMigrate的错误处理逻辑
func TestAutoMigrate_ErrorHandling(t *testing.T) {
logger := zaptest.NewLogger(t)
// 测试未初始化时的错误处理
err := AutoMigrate(logger)
if err == nil {
// 如果数据库已初始化,这是正常的
t.Log("AutoMigrate() 成功(数据库可能已初始化)")
} else {
// 如果数据库未初始化,应该返回错误
if err.Error() == "" {
t.Error("AutoMigrate() 应该返回有意义的错误消息")
}
}
}
// TestClose_NotInitialized 测试未初始化时关闭数据库
func TestClose_NotInitialized(t *testing.T) {
// 未初始化时关闭应该不返回错误
err := Close()
if err != nil {
t.Errorf("Close() 在未初始化时应该返回nil实际返回: %v", err)
}
}

View File

@@ -1,12 +1,9 @@
package database
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"sync"
"time"
"carrotskin/pkg/config"
@@ -16,31 +13,8 @@ import (
"gorm.io/gorm/logger"
)
// DBStats 数据库连接池统计信息
type DBStats struct {
MaxOpenConns int // 最大打开连接数
OpenConns int // 当前打开的连接数
InUseConns int // 正在使用的连接数
IdleConns int // 空闲连接数
WaitCount int64 // 等待连接的总次数
WaitDuration time.Duration // 等待连接的总时间
LastPingTime time.Time // 上次探活时间
LastPingSuccess bool // 上次探活是否成功
mu sync.RWMutex // 保护 LastPingTime 和 LastPingSuccess
}
// DB 数据库封装,包含连接池统计
type DB struct {
*gorm.DB
stats *DBStats
sqlDB *sql.DB
healthCh chan struct{} // 健康检查信号通道
closeCh chan struct{} // 关闭信号通道
wg sync.WaitGroup
}
// New 创建新的PostgreSQL数据库连接
func New(cfg config.DatabaseConfig) (*DB, error) {
func New(cfg config.DatabaseConfig) (*gorm.DB, error) {
dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s TimeZone=%s",
cfg.Host,
cfg.Port,
@@ -51,11 +25,11 @@ func New(cfg config.DatabaseConfig) (*DB, error) {
cfg.Timezone,
)
// 配置慢查询监控 - 优化从200ms调整为100ms
// 配置慢查询监控
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags),
logger.Config{
SlowThreshold: 100 * time.Millisecond, // 慢查询阈值:100ms(优化后)
SlowThreshold: 200 * time.Millisecond, // 慢查询阈值:200ms
LogLevel: logger.Warn, // 只记录警告和错误
IgnoreRecordNotFoundError: true, // 忽略记录未找到错误
Colorful: false, // 生产环境禁用彩色
@@ -105,131 +79,12 @@ func New(cfg config.DatabaseConfig) (*DB, error) {
sqlDB.SetConnMaxLifetime(connMaxLifetime)
sqlDB.SetConnMaxIdleTime(connMaxIdleTime)
// 测试连接(带重试机制)
if err := pingWithRetry(sqlDB, 3, 2*time.Second); err != nil {
// 测试连接
if err := sqlDB.Ping(); err != nil {
return nil, fmt.Errorf("数据库连接测试失败: %w", err)
}
// 创建数据库封装
database := &DB{
DB: db,
sqlDB: sqlDB,
stats: &DBStats{},
healthCh: make(chan struct{}, 1),
closeCh: make(chan struct{}),
}
// 初始化统计信息
database.updateStats()
// 启动定期健康检查
database.startHealthCheck(30 * time.Second)
log.Println("[Database] PostgreSQL连接池初始化成功")
log.Printf("[Database] 连接池配置: MaxIdleConns=%d, MaxOpenConns=%d, ConnMaxLifetime=%v, ConnMaxIdleTime=%v",
maxIdleConns, maxOpenConns, connMaxLifetime, connMaxIdleTime)
return database, nil
}
// pingWithRetry 带重试的Ping操作
func pingWithRetry(sqlDB *sql.DB, maxRetries int, retryInterval time.Duration) error {
var err error
for i := 0; i < maxRetries; i++ {
if err = sqlDB.Ping(); err == nil {
return nil
}
if i < maxRetries-1 {
log.Printf("[Database] Ping失败%v 后重试 (%d/%d): %v", retryInterval, i+1, maxRetries, err)
time.Sleep(retryInterval)
}
}
return err
}
// startHealthCheck 启动定期健康检查
func (d *DB) startHealthCheck(interval time.Duration) {
d.wg.Add(1)
go func() {
defer d.wg.Done()
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
d.ping()
case <-d.healthCh:
d.ping()
case <-d.closeCh:
return
}
}
}()
}
// ping 执行连接健康检查
func (d *DB) ping() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := d.sqlDB.PingContext(ctx)
d.stats.mu.Lock()
d.stats.LastPingTime = time.Now()
d.stats.LastPingSuccess = err == nil
d.stats.mu.Unlock()
if err != nil {
log.Printf("[Database] 连接健康检查失败: %v", err)
} else {
log.Println("[Database] 连接健康检查成功")
}
}
// GetStats 获取连接池统计信息
func (d *DB) GetStats() DBStats {
d.stats.mu.RLock()
defer d.stats.mu.RUnlock()
// 从底层获取实时统计
stats := d.sqlDB.Stats()
d.stats.MaxOpenConns = stats.MaxOpenConnections
d.stats.OpenConns = stats.OpenConnections
d.stats.InUseConns = stats.InUse
d.stats.IdleConns = stats.Idle
d.stats.WaitCount = stats.WaitCount
d.stats.WaitDuration = stats.WaitDuration
return *d.stats
}
// updateStats 初始化统计信息
func (d *DB) updateStats() {
stats := d.sqlDB.Stats()
d.stats.MaxOpenConns = stats.MaxOpenConnections
d.stats.OpenConns = stats.OpenConnections
d.stats.InUseConns = stats.InUse
d.stats.IdleConns = stats.Idle
}
// LogStats 记录连接池状态日志
func (d *DB) LogStats() {
stats := d.GetStats()
log.Printf("[Database] 连接池状态: Open=%d, Idle=%d, InUse=%d, WaitCount=%d, WaitDuration=%v, LastPing=%v (%v)",
stats.OpenConns, stats.IdleConns, stats.InUseConns, stats.WaitCount, stats.WaitDuration,
stats.LastPingTime.Format("2006-01-02 15:04:05"), stats.LastPingSuccess)
}
// Close 关闭数据库连接
func (d *DB) Close() error {
close(d.closeCh)
d.wg.Wait()
return d.sqlDB.Close()
}
// WithTimeout 创建带有超时控制的上下文
func WithTimeout(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
return context.WithTimeout(parent, timeout)
return db, nil
}
// GetDSN 获取数据源名称
@@ -244,3 +99,9 @@ func GetDSN(cfg config.DatabaseConfig) string {
cfg.Timezone,
)
}

View File

@@ -50,8 +50,13 @@ var defaultCasbinRules = []model.CasbinRule{
{PType: "g", V0: "admin", V1: "user"},
}
// SeedWithDB 使用指定的 *gorm.DB 初始化种子数据(供 DI 使用)
func SeedWithDB(db *gorm.DB, logger *zap.Logger) error {
// Seed 初始化种子数据
func Seed(logger *zap.Logger) error {
db, err := GetDB()
if err != nil {
return err
}
logger.Info("开始初始化种子数据...")
// 初始化默认管理员用户

View File

@@ -3,11 +3,13 @@ package email
import (
"crypto/tls"
"fmt"
"net/smtp"
"net/textproto"
"carrotskin/pkg/config"
"github.com/jordan-wright/email"
"go.uber.org/zap"
gomail "gopkg.in/mail.v2"
)
// Service 邮件服务
@@ -34,7 +36,7 @@ func (s *Service) SendVerificationCode(to, code, purpose string) error {
subject := s.getSubject(purpose)
body := s.getBody(code, purpose)
return s.send(to, subject, body)
return s.send([]string{to}, subject, body)
}
// SendResetPassword 发送重置密码邮件
@@ -53,13 +55,23 @@ func (s *Service) SendChangeEmail(to, code string) error {
}
// send 发送邮件
func (s *Service) send(to, subject, body string) error {
m := gomail.NewMessage()
m.SetHeader("From", fmt.Sprintf("%s <%s>", s.cfg.FromName, s.cfg.Username))
m.SetHeader("To", to)
m.SetHeader("Subject", subject)
m.SetBody("text/html", body)
func (s *Service) send(to []string, subject, body string) error {
e := email.NewEmail()
e.From = fmt.Sprintf("%s <%s>", s.cfg.FromName, s.cfg.Username)
e.To = to
e.Subject = subject
e.HTML = []byte(body)
e.Headers = textproto.MIMEHeader{}
// SMTP认证
auth := smtp.PlainAuth("", s.cfg.Username, s.cfg.Password, s.cfg.SMTPHost)
// 发送邮件
addr := fmt.Sprintf("%s:%d", s.cfg.SMTPHost, s.cfg.SMTPPort)
// 判断端口决定发送方式
// 465端口使用SSL/TLS隐式TLS
// 587端口使用STARTTLS显式TLS
var err error
if s.cfg.SMTPPort == 465 {
// 使用SSL/TLS连接适用于465端口
@@ -67,28 +79,15 @@ func (s *Service) send(to, subject, body string) error {
ServerName: s.cfg.SMTPHost,
InsecureSkipVerify: false, // 生产环境建议设置为false
}
d := &gomail.Dialer{
Host: s.cfg.SMTPHost,
Port: s.cfg.SMTPPort,
Username: s.cfg.Username,
Password: s.cfg.Password,
TLSConfig: tlsConfig,
}
err = d.DialAndSend(m)
err = e.SendWithTLS(addr, auth, tlsConfig)
} else {
// 使用STARTTLS连接适用于587端口等
d := &gomail.Dialer{
Host: s.cfg.SMTPHost,
Port: s.cfg.SMTPPort,
Username: s.cfg.Username,
Password: s.cfg.Password,
}
err = d.DialAndSend(m)
err = e.Send(addr, auth)
}
if err != nil {
s.logger.Error("发送邮件失败",
zap.String("to", to),
zap.Strings("to", to),
zap.String("subject", subject),
zap.String("smtp_host", s.cfg.SMTPHost),
zap.Int("smtp_port", s.cfg.SMTPPort),
@@ -98,7 +97,7 @@ func (s *Service) send(to, subject, body string) error {
}
s.logger.Info("邮件发送成功",
zap.String("to", to),
zap.Strings("to", to),
zap.String("subject", subject),
)

View File

@@ -2,6 +2,7 @@ package email
import (
"strings"
"sync"
"testing"
"carrotskin/pkg/config"
@@ -9,18 +10,25 @@ import (
"go.uber.org/zap"
)
// 全局单例访问器Init/GetService/MustGetService已在 DI 迁移中移除。
// 本测试改为直接使用构造函数 NewService。
func resetEmailOnce() {
serviceInstance = nil
once = sync.Once{}
}
func TestEmailManager_Disabled(t *testing.T) {
resetEmailOnce()
cfg := config.EmailConfig{Enabled: false}
svc := NewService(cfg, zap.NewNop())
if err := Init(cfg, zap.NewNop()); err != nil {
t.Fatalf("Init disabled err: %v", err)
}
svc := MustGetService()
if err := svc.SendVerificationCode("to@test.com", "123456", "email_verification"); err == nil {
t.Fatalf("expected error when disabled")
}
}
func TestEmailManager_SendFailsWithInvalidSMTP(t *testing.T) {
resetEmailOnce()
cfg := config.EmailConfig{
Enabled: true,
SMTPHost: "127.0.0.1",
@@ -29,7 +37,8 @@ func TestEmailManager_SendFailsWithInvalidSMTP(t *testing.T) {
Password: "pwd",
FromName: "name",
}
svc := NewService(cfg, zap.NewNop())
_ = Init(cfg, zap.NewNop())
svc := MustGetService()
if err := svc.SendVerificationCode("to@test.com", "123456", "reset_password"); err == nil {
t.Fatalf("expected send error with invalid smtp")
}

View File

@@ -1,8 +1,54 @@
package email
// 本文件原包含基于 sync.Once 的全局单例Init/GetService/MustGetService
//
// 在 DI 迁移阶段4全局单例已被移除。Email 服务由 fx.Provide(email.NewService)
// 构造,通过构造函数参数注入到各消费者。
//
// 邮件服务构造逻辑见 email.go 的 NewService()。
import (
"carrotskin/pkg/config"
"fmt"
"sync"
"go.uber.org/zap"
)
var (
// serviceInstance 全局邮件服务实例
serviceInstance *Service
// once 确保只初始化一次
once sync.Once
// initError 初始化错误
initError error
)
// Init 初始化邮件服务(线程安全,只会执行一次)
func Init(cfg config.EmailConfig, logger *zap.Logger) error {
once.Do(func() {
serviceInstance = NewService(cfg, logger)
})
return nil
}
// GetService 获取邮件服务实例(线程安全)
func GetService() (*Service, error) {
if serviceInstance == nil {
return nil, fmt.Errorf("邮件服务未初始化,请先调用 email.Init()")
}
return serviceInstance, nil
}
// MustGetService 获取邮件服务实例如果未初始化则panic
func MustGetService() *Service {
service, err := GetService()
if err != nil {
panic(err)
}
return service
}

69
pkg/email/manager_test.go Normal file
View File

@@ -0,0 +1,69 @@
package email
import (
"carrotskin/pkg/config"
"sync"
"testing"
"go.uber.org/zap/zaptest"
)
func resetEmail() {
serviceInstance = nil
once = sync.Once{}
}
// TestGetService_NotInitialized 测试未初始化时获取邮件服务
func TestGetService_NotInitialized(t *testing.T) {
resetEmail()
_, err := GetService()
if err == nil {
t.Error("未初始化时应该返回错误")
}
expectedError := "邮件服务未初始化,请先调用 email.Init()"
if err.Error() != expectedError {
t.Errorf("错误消息 = %q, want %q", err.Error(), expectedError)
}
}
// TestMustGetService_Panic 测试MustGetService在未初始化时panic
func TestMustGetService_Panic(t *testing.T) {
resetEmail()
defer func() {
if r := recover(); r == nil {
t.Error("MustGetService 应该在未初始化时panic")
}
}()
_ = MustGetService()
}
// TestInit_Email 测试邮件服务初始化
func TestInit_Email(t *testing.T) {
resetEmail()
cfg := config.EmailConfig{
Enabled: false,
SMTPHost: "smtp.example.com",
SMTPPort: 587,
Username: "user@example.com",
Password: "password",
FromName: "noreply@example.com",
}
logger := zaptest.NewLogger(t)
err := Init(cfg, logger)
if err != nil {
t.Errorf("Init() 错误 = %v, want nil", err)
}
// 验证可以获取服务
service, err := GetService()
if err != nil {
t.Errorf("GetService() 错误 = %v, want nil", err)
}
if service == nil {
t.Error("GetService() 返回的服务不应为nil")
}
}

View File

@@ -3,9 +3,9 @@ package logger
import (
"os"
"path/filepath"
"carrotskin/pkg/config"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
@@ -50,7 +50,7 @@ func New(cfg config.LogConfig) (*zap.Logger, error) {
if err := os.MkdirAll(logDir, 0755); err != nil {
return nil, err
}
file, err := os.OpenFile(cfg.Output, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
return nil, err

View File

@@ -1,8 +1,57 @@
package logger
// 本文件原包含基于 sync.Once 的全局单例Init/GetLogger/MustGetLogger
//
// 在 DI 迁移阶段4全局单例已被移除。Logger 由 fx.Provide(logger.New)
// 构造,通过构造函数参数注入到各消费者。
//
// 日志构造逻辑见 logger.go 的 New()。
import (
"carrotskin/pkg/config"
"fmt"
"sync"
"go.uber.org/zap"
)
var (
// loggerInstance 全局日志实例
loggerInstance *zap.Logger
// once 确保只初始化一次
once sync.Once
// initError 初始化错误
initError error
)
// Init 初始化日志记录器(线程安全,只会执行一次)
func Init(cfg config.LogConfig) error {
once.Do(func() {
loggerInstance, initError = New(cfg)
if initError != nil {
return
}
})
return initError
}
// GetLogger 获取日志实例(线程安全)
func GetLogger() (*zap.Logger, error) {
if loggerInstance == nil {
return nil, fmt.Errorf("日志未初始化,请先调用 logger.Init()")
}
return loggerInstance, nil
}
// MustGetLogger 获取日志实例如果未初始化则panic
func MustGetLogger() *zap.Logger {
logger, err := GetLogger()
if err != nil {
panic(err)
}
return logger
}

View File

@@ -0,0 +1,47 @@
package logger
import (
"carrotskin/pkg/config"
"testing"
)
// TestGetLogger_NotInitialized 测试未初始化时获取日志实例
func TestGetLogger_NotInitialized(t *testing.T) {
_, err := GetLogger()
if err == nil {
t.Error("未初始化时应该返回错误")
}
expectedError := "日志未初始化,请先调用 logger.Init()"
if err.Error() != expectedError {
t.Errorf("错误消息 = %q, want %q", err.Error(), expectedError)
}
}
// TestMustGetLogger_Panic 测试MustGetLogger在未初始化时panic
func TestMustGetLogger_Panic(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("MustGetLogger 应该在未初始化时panic")
}
}()
_ = MustGetLogger()
}
// TestInit_Logger 测试日志初始化逻辑
func TestInit_Logger(t *testing.T) {
cfg := config.LogConfig{
Level: "info",
Format: "json",
Output: "stdout",
}
// 验证Init函数存在且可调用
err := Init(cfg)
if err != nil {
// 初始化可能失败(例如缺少依赖),这是可以接受的
t.Logf("Init() 返回错误(可能正常): %v", err)
}
}

View File

@@ -1,38 +1,75 @@
package redis
import (
"carrotskin/pkg/config"
"fmt"
"os"
"sync"
"github.com/alicebob/miniredis/v2"
redis9 "github.com/redis/go-redis/v9"
"go.uber.org/zap"
)
// 本文件原包含基于 sync.Once 的全局单例Init/GetClient/MustGetClient/Close
//
// 在 DI 迁移阶段4全局单例已被移除。Redis 客户端由 fx.Provide 构造
// (见 internal/app/infra_module.go 的 provideRedis包含 miniredis 回退逻辑),
// 通过构造函数参数注入到各消费者。
//
// Redis 客户端构造逻辑见 redis.go 的 New()。
var (
// clientInstance 全局Redis客户端实例
clientInstance *Client
// once 确保只初始化一次
once sync.Once
// initError 初始化错误
initError error
// miniredisInstance 用于测试/开发环境
miniredisInstance *miniredis.Miniredis
)
// AllowFallbackToMiniRedis 检查当前环境是否允许回退到 miniredis仅开发/测试环境)。
func AllowFallbackToMiniRedis() bool {
// Init 初始化Redis客户端线程安全只会执行一次
// 如果Redis连接失败且环境为测试/开发则回退到miniredis
func Init(cfg config.RedisConfig, logger *zap.Logger) error {
var err error
once.Do(func() {
// 尝试连接真实Redis
clientInstance, err = New(cfg, logger)
if err != nil {
logger.Warn("Redis连接失败尝试使用miniredis回退", zap.Error(err))
// 检查是否允许回退到miniredis仅开发/测试环境)
if allowFallbackToMiniRedis() {
clientInstance, err = initMiniRedis(logger)
if err != nil {
initError = fmt.Errorf("Redis和miniredis都初始化失败: %w", err)
logger.Error("miniredis初始化失败", zap.Error(initError))
return
}
logger.Info("已回退到miniredis用于开发/测试环境")
} else {
initError = fmt.Errorf("Redis连接失败且不允许回退: %w", err)
logger.Error("Redis连接失败", zap.Error(initError))
return
}
}
})
return initError
}
// allowFallbackToMiniRedis 检查是否允许回退到miniredis
func allowFallbackToMiniRedis() bool {
// 检查环境变量
env := os.Getenv("ENVIRONMENT")
return env == "development" || env == "test" || env == "dev" ||
os.Getenv("USE_MINIREDIS") == "true"
}
// InitMiniRedis 初始化 miniredis用于开发/测试环境的 DI 回退)。
func InitMiniRedis(logger *zap.Logger) (*Client, error) {
mr, err := miniredis.Run()
// initMiniRedis 初始化miniredis用于开发/测试环境
func initMiniRedis(logger *zap.Logger) (*Client, error) {
var err error
miniredisInstance, err = miniredis.Run()
if err != nil {
return nil, fmt.Errorf("启动miniredis失败: %w", err)
}
// 创建Redis客户端连接到miniredis
redisClient := redis9.NewClient(&redis9.Options{
Addr: mr.Addr(),
Addr: miniredisInstance.Addr(),
})
client := &Client{
@@ -40,6 +77,42 @@ func InitMiniRedis(logger *zap.Logger) (*Client, error) {
logger: logger,
}
logger.Info("miniredis已启动", zap.String("addr", mr.Addr()))
logger.Info("miniredis已启动", zap.String("addr", miniredisInstance.Addr()))
return client, nil
}
// GetClient 获取Redis客户端实例线程安全
func GetClient() (*Client, error) {
if clientInstance == nil {
return nil, fmt.Errorf("Redis客户端未初始化请先调用 redis.Init()")
}
return clientInstance, nil
}
// MustGetClient 获取Redis客户端实例如果未初始化则panic
func MustGetClient() *Client {
client, err := GetClient()
if err != nil {
panic(err)
}
return client
}
// Close 关闭Redis连接包括miniredis如果使用了
func Close() error {
var err error
if miniredisInstance != nil {
miniredisInstance.Close()
miniredisInstance = nil
}
if clientInstance != nil {
err = clientInstance.Close()
clientInstance = nil
}
return err
}
// IsUsingMiniRedis 检查是否使用了miniredis
func IsUsingMiniRedis() bool {
return miniredisInstance != nil
}

53
pkg/redis/manager_test.go Normal file
View File

@@ -0,0 +1,53 @@
package redis
import (
"carrotskin/pkg/config"
"testing"
"go.uber.org/zap/zaptest"
)
// TestGetClient_NotInitialized 测试未初始化时获取Redis客户端
func TestGetClient_NotInitialized(t *testing.T) {
_, err := GetClient()
if err == nil {
t.Error("未初始化时应该返回错误")
}
expectedError := "Redis客户端未初始化请先调用 redis.Init()"
if err.Error() != expectedError {
t.Errorf("错误消息 = %q, want %q", err.Error(), expectedError)
}
}
// TestMustGetClient_Panic 测试MustGetClient在未初始化时panic
func TestMustGetClient_Panic(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("MustGetClient 应该在未初始化时panic")
}
}()
_ = MustGetClient()
}
// TestInit_Redis 测试Redis初始化逻辑
func TestInit_Redis(t *testing.T) {
cfg := config.RedisConfig{
Host: "localhost",
Port: 6379,
Password: "",
Database: 0,
PoolSize: 10,
}
logger := zaptest.NewLogger(t)
// 验证Init函数存在且可调用
// 注意:实际连接可能失败,这是可以接受的
err := Init(cfg, logger)
if err != nil {
t.Logf("Init() 返回错误可能正常如果Redis未运行: %v", err)
}
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"sync"
"time"
"carrotskin/pkg/config"
@@ -13,39 +12,23 @@ import (
"go.uber.org/zap"
)
// Client Redis客户端包装(包含连接池统计和健康检查)
// Client Redis客户端包装
type Client struct {
*redis.Client // 嵌入原始Redis客户端
logger *zap.Logger // 日志记录器
stats *RedisStats // 连接池统计信息
healthCheckDone chan struct{} // 健康检查完成信号
closeCh chan struct{} // 关闭信号通道
wg sync.WaitGroup // 等待组
*redis.Client
logger *zap.Logger
}
// RedisStats Redis连接池统计信息
type RedisStats struct {
PoolSize int // 连接池大小
IdleConns int // 空闲连接数
ActiveConns int // 活跃连接数
StaleConns int // 过期连接数
TotalConns int // 总连接数
LastPingTime time.Time // 上次探活时间
LastPingSuccess bool // 上次探活是否成功
mu sync.RWMutex // 保护统计信息
}
// New 创建Redis客户端带健康检查和优化配置
// New 创建Redis客户端
func New(cfg config.RedisConfig, logger *zap.Logger) (*Client, error) {
// 设置默认值
poolSize := cfg.PoolSize
if poolSize <= 0 {
poolSize = 16 // 优化:提高默认连接池大小
poolSize = 10
}
minIdleConns := cfg.MinIdleConns
if minIdleConns <= 0 {
minIdleConns = 8 // 优化:提高最小空闲连接数
minIdleConns = 5
}
maxRetries := cfg.MaxRetries
@@ -75,15 +58,10 @@ func New(cfg config.RedisConfig, logger *zap.Logger) (*Client, error) {
connMaxIdleTime := cfg.ConnMaxIdleTime
if connMaxIdleTime <= 0 {
connMaxIdleTime = 10 * time.Minute // 优化:减少空闲连接超时
connMaxIdleTime = 30 * time.Minute
}
connMaxLifetime := cfg.ConnMaxLifetime
if connMaxLifetime <= 0 {
connMaxLifetime = 30 * time.Minute // 新增:连接最大生命周期
}
// 创建Redis客户端带优化配置
// 创建Redis客户端
rdb := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
Password: cfg.Password,
@@ -96,254 +74,125 @@ func New(cfg config.RedisConfig, logger *zap.Logger) (*Client, error) {
WriteTimeout: writeTimeout,
PoolTimeout: poolTimeout,
ConnMaxIdleTime: connMaxIdleTime,
ConnMaxLifetime: connMaxLifetime,
})
// 测试连接(带重试机制)
if err := pingWithRetry(rdb, 3, 2*time.Second); err != nil {
// 测试连接
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := rdb.Ping(ctx).Err(); err != nil {
return nil, fmt.Errorf("Redis连接失败: %w", err)
}
// 创建客户端包装
client := &Client{
Client: rdb,
logger: logger,
stats: &RedisStats{},
healthCheckDone: make(chan struct{}),
closeCh: make(chan struct{}),
}
// 初始化统计信息
client.updateStats()
// 启动定期健康检查
healthCheckInterval := cfg.HealthCheckInterval
if healthCheckInterval <= 0 {
healthCheckInterval = 30 * time.Second
}
client.startHealthCheck(healthCheckInterval)
logger.Info("Redis连接成功",
zap.String("host", cfg.Host),
zap.Int("port", cfg.Port),
zap.Int("database", cfg.Database),
zap.Int("pool_size", poolSize),
zap.Int("min_idle_conns", minIdleConns),
)
return client, nil
}
// pingWithRetry 带重试的Ping操作
func pingWithRetry(rdb *redis.Client, maxRetries int, retryInterval time.Duration) error {
var err error
for i := 0; i < maxRetries; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
err = rdb.Ping(ctx).Err()
cancel()
if err == nil {
return nil
}
if i < maxRetries-1 {
time.Sleep(retryInterval)
}
}
return err
}
// startHealthCheck 启动定期健康检查
func (c *Client) startHealthCheck(interval time.Duration) {
c.wg.Add(1)
go func() {
defer c.wg.Done()
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
c.doHealthCheck()
case <-c.closeCh:
return
}
}
}()
}
// doHealthCheck 执行健康检查
func (c *Client) doHealthCheck() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// 更新统计信息
c.updateStats()
// 执行Ping检查
err := c.Client.Ping(ctx).Err()
c.stats.mu.Lock()
c.stats.LastPingTime = time.Now()
c.stats.LastPingSuccess = err == nil
c.stats.mu.Unlock()
if err != nil {
c.logger.Warn("Redis健康检查失败", zap.Error(err))
} else {
c.logger.Debug("Redis健康检查成功")
}
}
// updateStats 更新连接池统计信息
func (c *Client) updateStats() {
// 获取底层连接池统计信息
stats := c.Client.PoolStats()
c.stats.mu.Lock()
c.stats.PoolSize = c.Client.Options().PoolSize
c.stats.IdleConns = int(stats.IdleConns)
c.stats.ActiveConns = int(stats.TotalConns) - int(stats.IdleConns)
c.stats.TotalConns = int(stats.TotalConns)
c.stats.StaleConns = int(stats.StaleConns)
c.stats.mu.Unlock()
}
// GetStats 获取连接池统计信息
func (c *Client) GetStats() RedisStats {
c.stats.mu.RLock()
defer c.stats.mu.RUnlock()
return RedisStats{
PoolSize: c.stats.PoolSize,
IdleConns: c.stats.IdleConns,
ActiveConns: c.stats.ActiveConns,
StaleConns: c.stats.StaleConns,
TotalConns: c.stats.TotalConns,
LastPingTime: c.stats.LastPingTime,
LastPingSuccess: c.stats.LastPingSuccess,
}
}
// LogStats 记录连接池状态日志
func (c *Client) LogStats() {
stats := c.GetStats()
c.logger.Info("Redis连接池状态",
zap.Int("pool_size", stats.PoolSize),
zap.Int("idle_conns", stats.IdleConns),
zap.Int("active_conns", stats.ActiveConns),
zap.Int("total_conns", stats.TotalConns),
zap.Int("stale_conns", stats.StaleConns),
zap.Bool("last_ping_success", stats.LastPingSuccess),
)
}
// Ping 验证Redis连接带超时控制
func (c *Client) Ping(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
return c.Client.Ping(ctx).Err()
return &Client{
Client: rdb,
logger: logger,
}, nil
}
// Close 关闭Redis连接
func (c *Client) Close() error {
// 停止健康检查
close(c.closeCh)
c.wg.Wait()
c.logger.Info("正在关闭Redis连接")
c.LogStats() // 关闭前记录最终状态
return c.Client.Close()
}
// ===== 以下是封装的便捷方法,用于返回 (value, error) 格式 =====
// Set 设置键值对(带过期时间)- 封装版本
// Set 设置键值对(带过期时间)
func (c *Client) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
return c.Client.Set(ctx, key, value, expiration).Err()
}
// Get 获取键值 - 封装版本
// Get 获取键值
func (c *Client) Get(ctx context.Context, key string) (string, error) {
return c.Client.Get(ctx, key).Result()
}
// Del 删除键 - 封装版本
// Del 删除键
func (c *Client) Del(ctx context.Context, keys ...string) error {
return c.Client.Del(ctx, keys...).Err()
}
// Exists 检查键是否存在 - 封装版本
// Exists 检查键是否存在
func (c *Client) Exists(ctx context.Context, keys ...string) (int64, error) {
return c.Client.Exists(ctx, keys...).Result()
}
// Expire 设置键的过期时间 - 封装版本
// Expire 设置键的过期时间
func (c *Client) Expire(ctx context.Context, key string, expiration time.Duration) error {
return c.Client.Expire(ctx, key, expiration).Err()
}
// TTL 获取键的剩余过期时间 - 封装版本
// TTL 获取键的剩余过期时间
func (c *Client) TTL(ctx context.Context, key string) (time.Duration, error) {
return c.Client.TTL(ctx, key).Result()
}
// Incr 自增 - 封装版本
// Incr 自增
func (c *Client) Incr(ctx context.Context, key string) (int64, error) {
return c.Client.Incr(ctx, key).Result()
}
// Decr 自减 - 封装版本
// Decr 自减
func (c *Client) Decr(ctx context.Context, key string) (int64, error) {
return c.Client.Decr(ctx, key).Result()
}
// HSet 设置哈希字段 - 封装版本
// HSet 设置哈希字段
func (c *Client) HSet(ctx context.Context, key string, values ...interface{}) error {
return c.Client.HSet(ctx, key, values...).Err()
}
// HGet 获取哈希字段 - 封装版本
// HGet 获取哈希字段
func (c *Client) HGet(ctx context.Context, key, field string) (string, error) {
return c.Client.HGet(ctx, key, field).Result()
}
// HGetAll 获取所有哈希字段 - 封装版本
// HGetAll 获取所有哈希字段
func (c *Client) HGetAll(ctx context.Context, key string) (map[string]string, error) {
return c.Client.HGetAll(ctx, key).Result()
}
// HDel 删除哈希字段 - 封装版本
// HDel 删除哈希字段
func (c *Client) HDel(ctx context.Context, key string, fields ...string) error {
return c.Client.HDel(ctx, key, fields...).Err()
}
// SAdd 添加集合成员 - 封装版本
// SAdd 添加集合成员
func (c *Client) SAdd(ctx context.Context, key string, members ...interface{}) error {
return c.Client.SAdd(ctx, key, members...).Err()
}
// SMembers 获取集合所有成员 - 封装版本
// SMembers 获取集合所有成员
func (c *Client) SMembers(ctx context.Context, key string) ([]string, error) {
return c.Client.SMembers(ctx, key).Result()
}
// SRem 删除集合成员 - 封装版本
// SRem 删除集合成员
func (c *Client) SRem(ctx context.Context, key string, members ...interface{}) error {
return c.Client.SRem(ctx, key, members...).Err()
}
// SIsMember 检查是否是集合成员 - 封装版本
// SIsMember 检查是否是集合成员
func (c *Client) SIsMember(ctx context.Context, key string, member interface{}) (bool, error) {
return c.Client.SIsMember(ctx, key, member).Result()
}
// ZAdd 添加有序集合成员 - 封装版本
// ZAdd 添加有序集合成员
func (c *Client) ZAdd(ctx context.Context, key string, members ...redis.Z) error {
return c.Client.ZAdd(ctx, key, members...).Err()
}
// ZRange 获取有序集合范围内的成员 - 封装版本
// ZRange 获取有序集合范围内的成员
func (c *Client) ZRange(ctx context.Context, key string, start, stop int64) ([]string, error) {
return c.Client.ZRange(ctx, key, start, stop).Result()
}
// ZRem 删除有序集合成员 - 封装版本
// ZRem 删除有序集合成员
func (c *Client) ZRem(ctx context.Context, key string, members ...interface{}) error {
return c.Client.ZRem(ctx, key, members...).Err()
}
@@ -358,7 +207,6 @@ func (c *Client) TxPipeline() redis.Pipeliner {
return c.Client.TxPipeline()
}
// Nil 检查错误是否为Nilkey不存在
func (c *Client) Nil(err error) bool {
return errors.Is(err, redis.Nil)
}

View File

@@ -1,8 +1,55 @@
package storage
// 本文件原包含基于 sync.Once 的全局单例Init/GetClient/MustGetClient
//
// 在 DI 迁移阶段4全局单例已被移除。Storage 客户端由 fx.Provide(storage.NewStorage)
// 构造,通过构造函数参数注入到各消费者。
//
// 存储客户端构造逻辑见 minio.go 的 NewStorage()。
import (
"carrotskin/pkg/config"
"fmt"
"sync"
)
var (
// clientInstance 全局存储客户端实例
clientInstance *StorageClient
// once 确保只初始化一次
once sync.Once
// initError 初始化错误
initError error
)
// Init 初始化存储客户端(线程安全,只会执行一次)
func Init(cfg config.RustFSConfig) error {
once.Do(func() {
clientInstance, initError = NewStorage(cfg)
if initError != nil {
return
}
})
return initError
}
// GetClient 获取存储客户端实例(线程安全)
func GetClient() (*StorageClient, error) {
if clientInstance == nil {
return nil, fmt.Errorf("存储客户端未初始化,请先调用 storage.Init()")
}
return clientInstance, nil
}
// MustGetClient 获取存储客户端实例如果未初始化则panic
func MustGetClient() *StorageClient {
client, err := GetClient()
if err != nil {
panic(err)
}
return client
}

View File

@@ -0,0 +1,52 @@
package storage
import (
"carrotskin/pkg/config"
"testing"
)
// TestGetClient_NotInitialized 测试未初始化时获取存储客户端
func TestGetClient_NotInitialized(t *testing.T) {
_, err := GetClient()
if err == nil {
t.Error("未初始化时应该返回错误")
}
expectedError := "存储客户端未初始化,请先调用 storage.Init()"
if err.Error() != expectedError {
t.Errorf("错误消息 = %q, want %q", err.Error(), expectedError)
}
}
// TestMustGetClient_Panic 测试MustGetClient在未初始化时panic
func TestMustGetClient_Panic(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("MustGetClient 应该在未初始化时panic")
}
}()
_ = MustGetClient()
}
// TestInit_Storage 测试存储客户端初始化逻辑
func TestInit_Storage(t *testing.T) {
cfg := config.RustFSConfig{
Endpoint: "http://localhost:9000",
AccessKey: "minioadmin",
SecretKey: "minioadmin",
UseSSL: false,
Buckets: map[string]string{
"avatars": "avatars",
"textures": "textures",
},
}
// 验证Init函数存在且可调用
// 注意:实际连接可能失败,这是可以接受的
err := Init(cfg)
if err != nil {
t.Logf("Init() 返回错误(可能正常,如果存储服务未运行): %v", err)
}
}

Some files were not shown because too many files have changed in this diff Show More