docs: 新增运维和使用指南文档

新增文档:
- guides/ADMIN_GUIDE.md — 管理员操作手册(用户/角色/设备/日志管理)
- guides/USER_GUIDE.md — 普通用户操作手册(注册/登录/TOTP/设备管理)
- guides/CONFIG_REFERENCE.md — 配置文件参考手册(含全部配置项说明)
- guides/MONITORING.md — 健康检查、Prometheus 指标和告警规则

同步更新:
- docs/README.md 文档索引,加入新增文档链接
This commit is contained in:
2026-05-10 13:22:51 +08:00
parent bb7588b7c0
commit f050c60a09
5 changed files with 1181 additions and 0 deletions

View File

@@ -24,6 +24,20 @@
| `API.md` | 当前 API 合同。 | | `API.md` | 当前 API 合同。 |
| `PROJECT_REVIEW_REPORT.md` | 当前 review 报告。 | | `PROJECT_REVIEW_REPORT.md` | 当前 review 报告。 |
## 运维与使用指南guides/
| 路径 | 说明 |
|------|------|
| `guides/ADMIN_GUIDE.md` | 管理员操作手册(用户/角色/设备/日志管理)。 |
| `guides/USER_GUIDE.md` | 普通用户操作手册(注册/登录/TOTP/设备管理)。 |
| `guides/CONFIG_REFERENCE.md` | 配置文件参考手册(含全部配置项说明)。 |
| `guides/MONITORING.md` | 健康检查、Prometheus 指标和告警规则。 |
| `guides/ALERTING_ONCALL_RUNBOOK.md` | 告警响应和值班 Runbook。 |
| `guides/ROLLBACK_RUNBOOK.md` | 回滚操作 Runbook。 |
| `guides/TESTING.md` | 测试执行指南。 |
| `guides/GO_TROUBLESHOOTING.md` | Go 问题排查指南。 |
| `DEPLOYMENT.md` | 部署和运维指南(容器化部署、集群方案)。 |
## 归档说明 ## 归档说明
- 已被新状态、新规则或新结论替代的历史文档,应移动到 `docs/archive/` - 已被新状态、新规则或新结论替代的历史文档,应移动到 `docs/archive/`

265
docs/guides/ADMIN_GUIDE.md Normal file
View File

@@ -0,0 +1,265 @@
# 管理员操作手册
本文档面向系统管理员,描述用户管理系统的日常运维操作。
---
## 1. 管理员账号
### 1.1 默认管理员
系统初始化后,通过以下方式创建第一个管理员:
```bash
# 调用 bootstrap 接口创建管理员
curl -X POST http://localhost:8080/api/v1/auth/bootstrap-admin \
-H "Content-Type: application/json" \
-d '{
"username": "admin",
"password": "Admin@123456",
"email": "admin@example.com"
}'
```
**注意**:首次启动后必须立即修改默认密码。
### 1.2 管理员角色
管理员拥有系统所有权限:
- 用户管理(创建、编辑、删除、启用/禁用)
- 角色与权限管理
- 设备管理
- 登录日志查看
- 操作日志查看
- Webhook 管理
- 主题设置
---
## 2. 用户管理
### 2.1 用户列表
**路径**`GET /api/v1/users`
| 参数 | 类型 | 说明 |
|------|------|------|
| page | int | 页码(默认 1 |
| page_size | int | 每页数量(默认 20最大 100 |
| keyword | string | 按用户名/邮箱/手机号搜索 |
| status | int | 状态筛选1=正常0=禁用) |
### 2.2 创建用户
**路径**`POST /api/v1/users`
```json
{
"username": "john",
"email": "john@example.com",
"password": "SecurePass123!",
"nickname": "John Doe",
"phone": "13800138000"
}
```
### 2.3 编辑用户
**路径**`PUT /api/v1/users/:id`
可更新字段:`nickname``phone``status``email`
### 2.4 重置用户密码
**路径**`PUT /api/v1/users/:id/password`
```json
{
"new_password": "NewSecurePass123!"
}
```
管理员重置密码不需要原密码。
### 2.5 删除用户
**路径**`DELETE /api/v1/users/:id`
用户删除后不可恢复。
---
## 3. 角色与权限管理
### 3.1 预定义角色
系统预定义了以下角色:
| 角色代码 | 说明 |
|----------|------|
| admin | 系统管理员,拥有全部权限 |
| user | 普通用户,仅有基础权限 |
| operator | 运营人员,可管理用户和查看日志 |
### 3.2 创建自定义角色
**路径**`POST /api/v1/roles`
```json
{
"name": "内容审核员",
"code": "content_moderator",
"description": "负责内容审核",
"permissions": ["user:read", "user:update", "content:moderate"]
}
```
### 3.3 赋权
**路径**`POST /api/v1/users/:id/roles`
```json
{
"role_ids": [3, 5]
}
```
---
## 4. 设备管理
### 4.1 查看设备列表
**路径**`GET /api/v1/admin/devices`
| 参数 | 类型 | 说明 |
|------|------|------|
| page | int | 页码 |
| page_size | int | 每页数量 |
| user_id | int | 按用户筛选 |
| status | int | 设备状态0=禁用1=启用) |
### 4.2 设备信任管理
管理员可为用户信任设备:
- 信任设备在有效期内免二次验证TOTP
- 可设置信任时长30d / 90d / 180d
**路径**`POST /api/v1/devices/:id/trust`
```json
{
"trust_duration": "30d"
}
```
### 4.3 登出用户设备
**路径**`POST /api/v1/devices/logout-others`
通过 `X-Device-ID` header 指定当前设备,其他设备全部登出。
---
## 5. 日志查看
### 5.1 登录日志
**路径**`GET /api/v1/logs/login`
| 参数 | 类型 | 说明 |
|------|------|------|
| page | int | 页码 |
| page_size | int | 每页数量 |
| user_id | int | 筛选用户 |
| start_time | string | 开始时间RFC3339 |
| end_time | string | 结束时间RFC3339 |
### 5.2 操作日志
**路径**`GET /api/v1/logs/operations`
记录所有变更操作的审计日志。
---
## 6. 系统安全配置
### 6.1 密码策略
可通过 `PUT /api/v1/admin/settings` 修改:
| 配置项 | 说明 | 默认值 |
|--------|------|--------|
| password_min_length | 最小长度 | 8 |
| password_require_uppercase | 必须包含大写 | true |
| password_require_lowercase | 必须包含小写 | true |
| password_require_digit | 必须包含数字 | true |
| password_require_special | 必须包含特殊字符 | true |
### 6.2 登录安全
| 配置项 | 说明 | 默认值 |
|--------|------|--------|
| max_login_attempts | 连续失败锁定次数 | 5 |
| lockout_duration | 锁定时长(分钟) | 30 |
| session_timeout | 会话超时(小时) | 24 |
### 6.3 TOTP 两步验证
系统支持 TOTP 方式的二次验证Google Authenticator 等)。
管理员可强制要求用户启用 TOTP。
---
## 7. 常见运维操作
### 7.1 禁用用户登录
```bash
# 禁用用户
curl -X PUT http://localhost:8080/api/v1/users/123 \
-H "Authorization: Bearer <admin_token>" \
-H "Content-Type: application/json" \
-d '{"status": 0}'
```
### 7.2 查看系统健康状态
```bash
# 健康检查
curl http://localhost:8080/health
# 就绪检查
curl http://localhost:8080/health/ready
# 存活检查
curl http://localhost:8080/health/live
```
### 7.3 强制登出用户
删除用户的会话令牌,使其中断当前会话。
---
## 8. 监控指标
系统暴露以下 Prometheus 格式指标:
| 指标名 | 说明 |
|--------|------|
| `http_requests_total` | HTTP 请求总数 |
| `http_request_duration_seconds` | 请求延迟分布 |
| `login_attempts_total` | 登录尝试次数 |
| `active_sessions_total` | 当前活跃会话数 |
| `db_query_duration_seconds` | 数据库查询延迟 |
---
## 9. 备份策略
参考 Runbook`docs/runbooks/05-备份恢复.md`
---
*最后更新2026-05-10*

View File

@@ -0,0 +1,331 @@
# 配置参考手册
本文档描述 `configs/config.yaml` 各配置项的含义、默认值和生产环境建议。
---
## 1. server — 服务配置
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `port` | int | 8080 | HTTP 服务监听端口 |
| `mode` | string | release | 运行模式:`debug` / `release` |
| `read_timeout` | duration | 30s | 读取请求体的超时 |
| `read_header_timeout` | duration | 10s | 读取请求头的超时 |
| `write_timeout` | duration | 30s | 写入响应的超时 |
| `idle_timeout` | duration | 60s | 空闲连接保持时间 |
| `shutdown_timeout` | duration | 15s | 优雅停机的最大等待时间 |
| `max_header_bytes` | int | 1048576 | 请求头最大字节数 |
**生产建议**:若前端 CDN 缓存较多,可将 `cache-control` 等头设置较长,减少回源。
---
## 2. database — 数据库配置
### 2.1 通用
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `type` | string | sqlite | 数据库类型:`sqlite` / `postgresql` / `mysql` |
> ⚠️ 当前生产环境推荐使用 `postgresql`SQLite 仅适用于开发和小规模部署。
### 2.2 SQLite
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `path` | string | ./data/user_management.db | 数据库文件路径(相对于工作目录) |
### 2.3 PostgreSQL
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `host` | string | localhost | 数据库主机 |
| `port` | int | 5432 | 数据库端口 |
| `database` | string | user_management | 数据库名 |
| `username` | string | postgres | 用户名 |
| `password` | string | "" | 密码(生产必须通过环境变量设置) |
| `ssl_mode` | string | disable | SSL 模式:`disable` / `require` / `verify-ca` / `verify-full` |
| `max_open_conns` | int | 100 | 最大打开连接数 |
| `max_idle_conns` | int | 10 | 最大空闲连接数 |
**生产建议**
- `ssl_mode` 至少设为 `require`
- 生产密码必须通过 `DB_PASSWORD` 环境变量注入,不要写在配置文件中
- 高并发场景建议 `max_open_conns = 200~500`
### 2.4 MySQL
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `host` | string | localhost | 数据库主机 |
| `port` | int | 3306 | 数据库端口 |
| `database` | string | user_management | 数据库名 |
| `username` | string | root | 用户名 |
| `password` | string | "" | 密码(生产必须通过环境变量) |
| `charset` | string | utf8mb4 | 字符集(必须使用 utf8mb4 |
| `max_open_conns` | int | 100 | 最大打开连接数 |
| `max_idle_conns` | int | 10 | 最大空闲连接数 |
---
## 3. cache — 缓存配置
### 3.1 L1 缓存(内存)
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `enabled` | bool | true | 是否启用 L1 缓存 |
| `max_size` | int | 10000 | 最大缓存条目数 |
| `ttl` | duration | 5m | 缓存条目 TTL |
### 3.2 L2 缓存Redis
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `enabled` | bool | false | 是否启用 Redis L2 缓存 |
| `type` | string | redis | 缓存类型(仅支持 redis |
| `redis.addr` | string | localhost:6379 | Redis 地址 |
| `redis.password` | string | "" | Redis 密码 |
| `redis.db` | int | 0 | Redis DB 编号 |
| `redis.pool_size` | int | 50 | 连接池大小 |
| `redis.ttl` | duration | 30m | 缓存 TTL |
**生产建议**:高并发场景建议启用 Redis L2 缓存,并设置合理的 `pool_size`
---
## 4. jwt — JWT 配置
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `algorithm` | string | HS256 | 签名算法:`HS256`debug/ `RS256`(生产推荐) |
| `secret` | string | "" | HMAC 签名密钥(生产必须设置) |
| `access_token_expire_minutes` | int | 120 | Access Token 有效期(分钟) |
| `refresh_token_expire_days` | int | 7 | Refresh Token 有效期(天) |
**生产建议**
- 生产环境建议使用 `RS256`RSA 密钥对),不要使用共享密钥
- `JWT_SECRET` 环境变量必须设置强随机字符串(至少 32 字节)
- Access Token 建议 30~120 分钟
- Refresh Token 建议 7~30 天
---
## 5. security — 安全配置
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `password_min_length` | int | 8 | 密码最小长度 |
| `password_require_special` | bool | true | 必须包含特殊字符 |
| `password_require_number` | bool | true | 必须包含数字 |
| `login_max_attempts` | int | 5 | 连续登录失败锁定次数 |
| `login_lock_duration` | duration | 30m | 账户锁定时长 |
---
## 6. ratelimit — 限流配置
所有限流均可独立开启/关闭。算法说明:
- `token_bucket`:令牌桶,适合突发流量
- `leaky_bucket`:漏桶,输出速率恒定
- `sliding_window`:滑动窗口,统计最平滑
### 6.1 登录限流
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `enabled` | bool | true | 是否启用 |
| `algorithm` | string | token_bucket | 限流算法 |
| `capacity` | int | 5 | 令牌桶容量(即 burst 上限) |
| `rate` | int | 1 | 每窗口补充令牌数 |
| `window` | duration | 1m | 统计窗口 |
### 6.2 注册限流
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `enabled` | bool | true | 是否启用 |
| `algorithm` | string | leaky_bucket | 限流算法 |
| `capacity` | int | 3 | 桶容量 |
| `rate` | int | 1 | 输出速率 |
| `window` | duration | 1h | 统计窗口 |
### 6.3 API 通用限流
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `enabled` | bool | true | 是否启用 |
| `algorithm` | string | sliding_window | 限流算法 |
| `capacity` | int | 1000 | 窗口内最大请求数 |
| `window` | duration | 1m | 统计窗口 |
---
## 7. monitoring — 监控配置
### 7.1 Prometheus 指标
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `enabled` | bool | true | 是否启用 Prometheus 指标 |
| `path` | string | /metrics | 指标暴露路径 |
### 7.2 分布式追踪
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `enabled` | bool | false | 是否启用追踪 |
| `endpoint` | string | localhost:4318 | OTLP gRPC 接收端点 |
| `service_name` | string | user-management-system | 服务名(用于链路关联) |
**生产建议**:接入 Jaeger 或 Zipkin 时启用追踪。
---
## 8. logging — 日志配置
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `level` | string | info | 日志级别:`debug` / `info` / `warn` / `error` |
| `format` | string | json | 日志格式:`json`(生产)/ `text`(开发) |
| `output` | []string | stdout, ./logs/app.log | 日志输出目标 |
| `rotation.max_size` | int | 100 | 单文件最大 MB |
| `rotation.max_age` | int | 30 | 保留天数 |
| `rotation.max_backups` | int | 10 | 保留文件数 |
---
## 9. cors — 跨域配置
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `enabled` | bool | true | 是否启用 CORS |
| `allowed_origins` | []string | localhost:3000 | 允许的来源(生产必须精确配置) |
| `allowed_methods` | []string | GET,POST,PUT,DELETE,OPTIONS | 允许的方法 |
| `allowed_headers` | []string | 见 config.yaml | 允许的请求头 |
| `allow_credentials` | bool | true | 是否允许携带凭证 |
| `max_age` | int | 3600 | 预检请求缓存时间(秒) |
> ⚠️ **生产禁止**将 `*` 与 `allow_credentials: true` 同时使用CORS 规范不允许,会被浏览器拒绝)。
---
## 10. email — 邮件配置
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `host` | string | "" | SMTP 主机 |
| `port` | int | 587 | SMTP 端口TLS587SSL465 |
| `username` | string | "" | 用户名 |
| `password` | string | "" | 密码(生产通过环境变量) |
| `from_email` | string | "" | 发件人地址 |
| `from_name` | string | 用户管理系统 | 发件人名称 |
**生产建议**:使用企业邮箱(如 SendGrid、Mailgun或自建 SMTP。
---
## 11. sms — 短信配置
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `enabled` | bool | false | 是否启用短信功能 |
| `provider` | string | "" | 提供商:`aliyun` / `tencent`,留空禁用 |
| `code_ttl` | duration | 5m | 验证码有效期 |
| `resend_cooldown` | duration | 1m | 再次发送的冷却时间 |
| `max_daily_limit` | int | 10 | 单号码每日发送上限 |
### 11.1 阿里云
| 配置项 | 说明 |
|--------|------|
| `access_key_id` | 阿里云 AccessKey ID |
| `access_key_secret` | 阿里云 AccessKey Secret |
| `sign_name` | 短信签名 |
| `template_code` | 短信模板 CODE |
### 11.2 腾讯云
| 配置项 | 说明 |
|--------|------|
| `secret_id` | 腾讯云 Secret ID |
| `secret_key` | 腾讯云 Secret Key |
| `app_id` | 短信 SDK App ID |
| `sign_name` | 短信签名 |
| `template_id` | 模板 ID |
---
## 12. oauth — 社交登录配置
| Provider | 配置项 | 说明 |
|----------|--------|------|
| 通用 | `client_id` | 应用 Client ID |
| 通用 | `client_secret` | 应用 Client Secret生产通过环境变量 |
| 通用 | `redirect_url` | OAuth 回调地址(生产必须使用 HTTPS |
| Google | — | 支持 Google 账号登录 |
| GitHub | — | 支持 GitHub 账号登录 |
| WeChat | — | 支持微信账号登录 |
| QQ | — | 支持 QQ 账号登录 |
| 支付宝 | — | 支持支付宝账号登录 |
| 抖音 | — | 支持抖音账号登录 |
> ⚠️ 所有 OAuth 回调地址必须使用 HTTPS禁止在生产环境使用 HTTP。
---
## 13. webhook — Webhook 配置
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `enabled` | bool | true | 是否启用 Webhook |
| `secret_header` | string | X-Webhook-Signature | 签名验证 Header 名 |
| `timeout_sec` | int | 30 | 单次投递超时(秒) |
| `max_retries` | int | 3 | 最大重试次数 |
| `retry_backoff` | string | exponential | 退避策略:`exponential` / `fixed` |
| `worker_count` | int | 4 | 后台投递协程数 |
| `queue_size` | int | 1000 | 投递队列大小 |
---
## 14. ip_security — IP 安全配置
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `auto_block_enabled` | bool | true | 是否启用自动封禁 |
| `auto_block_duration` | duration | 30m | 封禁时长 |
| `brute_force_threshold` | int | 10 | 暴力破解判定阈值(窗口内失败次数) |
| `detection_window` | duration | 15m | 检测时间窗口 |
---
## 15. password_reset — 密码重置配置
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `token_ttl` | duration | 15m | 重置令牌有效期 |
| `site_url` | string | http://localhost:8080 | 前端站点 URL用于构造邮件链接 |
---
## 环境变量优先级
配置项中包含敏感信息的字段,支持通过环境变量覆盖:
| 配置项 | 环境变量 |
|--------|----------|
| `jwt.secret` | `JWT_SECRET` |
| `database.postgresql.password` | `DB_PASSWORD` |
| `database.mysql.password` | `DB_PASSWORD` |
| `redis.password` | `REDIS_PASSWORD` |
| `email.password` | `SMTP_PASSWORD` |
| `jwt.algorithm`(生产) | `JWT_ALGORITHM` |
| `oauth.*.client_secret` | 各 Provider 的 `CLIENT_SECRET` |
> 环境变量优先级高于配置文件,用于生产密钥注入。
---
*最后更新2026-05-10*

318
docs/guides/MONITORING.md Normal file
View File

@@ -0,0 +1,318 @@
# 健康检查与监控指南
本文档描述系统健康检查端点、Prometheus 监控指标和告警规则。
---
## 1. 健康检查端点
系统提供三个健康检查端点,适用于不同场景:
| 端点 | 路径 | 说明 | 使用场景 |
|------|------|------|----------|
| 存活探针 | `/health/live` | 确认进程存活 | Kubernetes `livenessProbe` |
| 就绪探针 | `/health/ready` | 确认服务就绪 | Kubernetes `readinessProbe` |
| 健康检查 | `/health` | 综合健康状态 | 负载均衡器、健康检查脚本 |
### 1.1 响应格式
```json
{
"status": "ok",
"timestamp": "2026-05-10T13:00:00Z",
"version": "1.0.0"
}
```
### 1.2 响应码
| 状态 | HTTP 响应码 | 说明 |
|------|-------------|------|
| ok | 200 | 服务正常 |
| degraded | 200 | 服务降级(部分依赖不可用,如 Redis |
| unhealthy | 503 | 服务不健康(如数据库不可达) |
---
## 2. Prometheus 监控指标
### 2.1 暴露方式
指标端点:`GET /metrics`
返回 Prometheus 格式文本。
### 2.2 核心指标
#### HTTP 指标
| 指标名 | 类型 | 标签 | 说明 |
|--------|------|------|------|
| `http_requests_total` | Counter | method, path, status | HTTP 请求总数 |
| `http_request_duration_seconds` | Histogram | method, path | 请求延迟分布 |
#### 认证指标
| 指标名 | 类型 | 标签 | 说明 |
|--------|------|------|------|
| `login_attempts_total` | Counter | result, method | 登录尝试次数(成功/失败) |
| `active_sessions_total` | Gauge | — | 当前活跃会话数 |
| `refresh_tokens_total` | Counter | — | Token 刷新次数 |
#### 数据库指标
| 指标名 | 类型 | 标签 | 说明 |
|--------|------|------|------|
| `db_query_duration_seconds` | Histogram | operation, table | 数据库查询延迟 |
| `db_connections_open` | Gauge | type | 当前打开的连接数 |
| `db_connections_in_use` | Gauge | type | 使用中的连接数 |
#### 缓存指标
| 指标名 | 类型 | 标签 | 说明 |
|--------|------|------|------|
| `cache_hits_total` | Counter | cache_level | 缓存命中次数 |
| `cache_misses_total` | Counter | cache_level | 缓存未命中次数 |
| `cache_operations_total` | Counter | operation | 缓存操作总数 |
#### 限流指标
| 指标名 | 类型 | 标签 | 说明 |
|--------|------|------|------|
| `ratelimit_rejections_total` | Counter | endpoint, algorithm | 限流拦截次数 |
### 2.3 查看当前指标
```bash
curl http://localhost:8080/metrics
```
---
## 3. 告警规则
### 3.1 建议的告警规则Prometheus / Alertmanager 格式)
```yaml
groups:
- name: user-management
rules:
# 服务不可用
- alert: ServiceDown
expr: up{job="user-management"} == 0
for: 1m
labels:
severity: critical
annotations:
summary: "用户管理服务不可用"
# 错误率过高
- alert: HighErrorRate
expr: |
rate(http_requests_total{status=~"5.."}[5m]) /
rate(http_requests_total[5m]) > 0.05
for: 5m
labels:
severity: warning
annotations:
summary: "HTTP 5xx 错误率超过 5%"
# 登录失败率过高(可能暴力破解)
- alert: HighLoginFailureRate
expr: |
rate(login_attempts_total{result="fail"}[5m]) /
rate(login_attempts_total[5m]) > 0.8
for: 5m
labels:
severity: warning
annotations:
summary: "登录失败率超过 80%,可能存在暴力破解"
# 响应延迟过高
- alert: HighLatency
expr: |
histogram_quantile(0.99,
rate(http_request_duration_seconds_bucket[5m])) > 1
for: 5m
labels:
severity: warning
annotations:
summary: "P99 响应延迟超过 1 秒"
# 数据库连接池耗尽
- alert: DatabaseConnectionPoolExhausted
expr: db_connections_in_use / db_connections_open > 0.9
for: 5m
labels:
severity: critical
annotations:
summary: "数据库连接池使用率超过 90%"
# 活跃会话数异常下降
- alert: ActiveSessionsDropped
expr: |
active_sessions_total < 10
and
delta(active_sessions_total[10m]) < -5
for: 5m
labels:
severity: warning
annotations:
summary: "活跃会话数急剧下降"
# 限流拦截频繁
- alert: RateLimitRejectionsHigh
expr: |
rate(ratelimit_rejections_total[5m]) > 10
for: 5m
labels:
severity: warning
annotations:
summary: "限流拦截频率过高"
```
---
## 4. Grafana 看板
建议导入以下看板配置:
### 4.1 核心看板指标
**Overview 看板**
- 请求率QPS
- P50/P90/P99 延迟
- 错误率
- 活跃会话数
**Auth 看板**
- 登录尝试(成功/失败)
- Token 刷新次数
- 活跃会话趋势
- TOTP 启用率
**Database 看板**
- 查询延迟 P99
- 连接池使用率
- 慢查询数量
**Cache 看板**
- 命中率
- 未命中率
- L1/L2 缓存对比
---
## 5. 日志关键字监控
建议在日志收集系统(如 Loki/ELK中配置以下关键字告警
| 关键字 | 严重程度 | 说明 |
|--------|----------|------|
| `auth: increment login attempts failed` | warning | Redis/L1 缓存不可用 |
| `goroutine leak` | critical | 潜在的 goroutine 泄漏 |
| `token blacklisted but refresh failed` | critical | Token 黑名单写入失败 |
| `password reset code replay` | warning | 可能存在验证码重放 |
| `temporary login token cleanup failed` | warning | 临时令牌清理失败 |
| `cache.Set failed` | warning | 缓存写入失败 |
| `failed to send email` | warning | 邮件发送失败 |
---
## 6. 健康检查脚本示例
```bash
#!/bin/bash
# health_check.sh — 服务健康检查脚本
HEALTH_URL="http://localhost:8080/health"
READY_URL="http://localhost:8080/health/ready"
METRICS_URL="http://localhost:8080/metrics"
check_endpoint() {
local url=$1
local name=$2
local status=$(curl -s -o /dev/null -w "%{http_code}" "$url")
if [ "$status" -eq 200 ]; then
echo "[OK] $name: $status"
return 0
else
echo "[FAIL] $name: $status"
return 1
fi
}
# 执行检查
failed=0
check_endpoint "$HEALTH_URL" "Health" || failed=$((failed + 1))
check_endpoint "$READY_URL" "Ready" || failed=$((failed + 1))
# 检查 Prometheus 指标端点
status=$(curl -s -o /dev/null -w "%{http_code}" "$METRICS_URL")
if [ "$status" -eq 200 ]; then
echo "[OK] Metrics: $status"
else
echo "[WARN] Metrics: $status"
fi
# 检查数据库连接(通过日志)
if grep -q "database opened" logs/app.log 2>/dev/null; then
echo "[OK] Database: connected"
else
echo "[FAIL] Database: not connected"
failed=$((failed + 1))
fi
exit $failed
```
---
## 7. Kubernetes 部署配置示例
```yaml
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
containers:
- name: user-management
livenessProbe:
httpGet:
path: /health/live
port: 8080
initialDelaySeconds: 10
periodSeconds: 15
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /health/ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3
ports:
- name: http
containerPort: 8080
- name: metrics
containerPort: 9090
resources:
requests:
memory: "256Mi"
cpu: "200m"
limits:
memory: "1Gi"
cpu: "1000m"
```
---
*最后更新2026-05-10*

253
docs/guides/USER_GUIDE.md Normal file
View File

@@ -0,0 +1,253 @@
# 用户操作手册
本文档面向普通用户,描述用户管理系统的使用方法。
---
## 1. 注册与登录
### 1.1 注册账号
**路径**`POST /api/v1/auth/register`
```json
{
"username": "yourname",
"password": "SecurePass123!",
"email": "you@example.com"
}
```
**密码要求**
- 最少 8 位
- 必须包含大写字母
- 必须包含小写字母
- 必须包含数字
- 必须包含特殊字符(`!@#$%^&*` 等)
### 1.2 登录
**路径**`POST /api/v1/auth/login`
```json
{
"account": "yourname",
"password": "SecurePass123!",
"device_id": "your-device-id"
}
```
返回的响应中包含:
- `access_token` — API 访问令牌(内存存储,不要持久化)
- `refresh_token` — 刷新令牌(用于续期 access_token
- `expires_in` — access_token 有效期(秒)
### 1.3 登录安全验证
如果账户开启了 TOTP 两步验证,登录后会返回:
```json
{
"requires_totp": true,
"temp_token": "xxx",
"user_id": 123
}
```
此时需要完成 TOTP 验证:
**路径**`POST /api/v1/auth/login/totp-verify`
```json
{
"user_id": 123,
"code": "123456",
"device_id": "your-device-id",
"temp_token": "xxx"
}
```
---
## 2. 账户安全
### 2.1 修改密码
**路径**`PUT /api/v1/auth/password`
```json
{
"old_password": "OldPass123!",
"new_password": "NewPass456!"
}
```
**注意**:修改密码会使除当前设备外的所有会话失效。
### 2.2 忘记密码
**路径**`POST /api/v1/auth/password/forgot`
```json
{
"email": "you@example.com"
}
```
系统会向邮箱发送重置链接。
### 2.3 设置 TOTP 两步验证
**步骤 1**:请求 TOTP 绑定信息
**路径**`POST /api/v1/auth/totp/setup`
返回二维码和密钥。使用 Google Authenticator 或其他 TOTP 应用扫描。
**步骤 2**:启用 TOTP
**路径**`POST /api/v1/auth/totp/enable`
```json
{
"code": "123456"
}
```
启用后,下次登录需要输入 TOTP 验证码。
### 2.4 禁用 TOTP
**路径**`POST /api/v1/auth/totp/disable`
```json
{
"code": "123456"
}
```
### 2.5 恢复码
首次启用 TOPT 时,系统会提供一组恢复码。
**用途**:当 TOTP 设备丢失时,使用恢复码恢复登录。
**保存建议**:将恢复码打印或手写保存到安全位置,切勿截图或保存到云端。
---
## 3. 设备管理
### 3.1 查看我的设备
**路径**`GET /api/v1/devices`
返回当前账户下所有已登录设备列表。
### 3.2 查看信任设备
**路径**`GET /api/v1/devices/trusted`
返回已标记为信任的设备列表。信任设备在有效期内免 TOTP 验证。
### 3.3 信任当前设备
**路径**`POST /api/v1/devices/trust`
将当前设备标记为信任设备。
**注意**:需要在设备详情中查看设备 ID。
### 3.4 取消设备信任
**路径**`DELETE /api/v1/devices/:id/trust`
### 3.5 登出其他设备
**路径**`POST /api/v1/devices/logout-others`
将除当前设备外的所有其他设备登出。
Header 中需要指定当前设备:`X-Device-ID: your-device-id`
---
## 4. 个人资料
### 4.1 查看个人资料
**路径**`GET /api/v1/auth/userinfo`
### 4.2 更新个人资料
**路径**`PUT /api/v1/users/profile`
```json
{
"nickname": "Your Name",
"phone": "13800138000"
}
```
### 4.3 上传头像
**路径**`POST /api/v1/users/:id/avatar`
支持的格式JPEG、PNG、GIF、WebP
最大文件大小5MB
---
## 5. Token 刷新
Access Token 有效期较短,过期后需要使用 Refresh Token 续期:
**路径**`POST /api/v1/auth/refresh`
```json
{
"refresh_token": "your_refresh_token"
}
```
返回新的 access_token 和 refresh_token。
---
## 6. 账户注销
**路径**`DELETE /api/v1/users/account`
注销后所有数据将被永久删除,不可恢复。
---
## 7. API 认证
所有需要认证的 API在请求 Header 中添加:
```
Authorization: Bearer <access_token>
```
示例:
```bash
curl http://localhost:8080/api/v1/auth/userinfo \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```
---
## 8. 错误代码
| 代码 | 说明 |
|------|------|
| 400 | 请求参数错误 |
| 401 | 未认证或 Token 已过期 |
| 403 | 无权限 |
| 404 | 资源不存在 |
| 429 | 请求过于频繁(触发限流) |
| 500 | 服务器内部错误 |
---
*最后更新2026-05-10*