增加图形验证码的功能

This commit is contained in:
2026-08-01 00:05:04 +08:00
parent 97450f0739
commit 4f00b83e86
15 changed files with 838 additions and 2 deletions

View File

@@ -89,6 +89,7 @@ go run ./cmd/server -config config.json -addr :8080
| Excel | `Excel()` | 每次新建导出器 |
| 国际化 | `I18n()` / `MustI18n()` | 一般由 `NewHandler` 注入 |
| MCP 工具 | `MCP()` / `MustMCP()` | `ListTools` / `CallTool`(见 §8 |
| 图形验证码 | `Captcha()` / `MustCaptcha()` | `Generate` / `Verify` / 登录防暴力(见 §8 |
| HTTP 出参 | `NewHandler(w, r)` | `Success` / `Error` / `ErrorData` |
| 中间件 | `MiddlewareChain()` | `Append` / `ThenFunc` |
| 迁移 | `Migrator(dir)` | Up / Down / Status |
@@ -205,6 +206,41 @@ ctx = mcp.WithRequestID(ctx, requestID)
加一条配置,不改代码;`allowedTools` 留空表示开放该 server 全部工具。完整字段见
[`config/example.json`](./config/example.json) 的 `mcp` 段。
### 图形验证码Captcha
可选模块:`config.captcha.enabled=false`(或未配置)时 `Captcha().Enabled()` 为 false**不影响 middleware**;业务 handler 按需调用即可。
```go
cap := app.MustCaptcha() // enabled=true 时需配置 redis
// 1. 生成(注册/改手机号等发短信前)
result, _ := cap.Generate(ctx, captcha.SceneRegister)
// 返回 result.ID + result.ImageBase64 给前端展示
// 2. 校验(一次性消费)
if err := cap.Verify(ctx, captcha.VerifyRequest{
Scene: captcha.SceneRegister, ID: captchaID, Answer: userInput,
}); err != nil {
h.Error("captcha.invalid")
return
}
// 验证通过后再 app.MustSMS().SendSMS(...)
// 3. 登录防暴力(失败 N 次后要求验证码M 次后锁定)
key := username // 或 username+IP由业务决定
if need, _ := cap.LoginNeedCaptcha(ctx, key); need {
// 要求前端传 captchaId + captchaCode并 Verify
}
status, err := cap.RecordLoginFailure(ctx, key)
if status.Locked { h.Error("captcha.login_locked"); return }
// 登录成功后
_ = cap.ClearLoginFailures(ctx, key)
```
场景常量:`SceneRegister` / `SceneChangePhone` / `SceneLogin` / `SceneSendSMS`
`scenes.register.mode=always` 表示该场景始终要求图形验证码;登录场景由 `login.showAfterFailures` 控制「失败后才要求」。
完整配置见 [`config/example.json`](./config/example.json) 的 `captcha` 段。
---
## 9. 最小 config.json