增加图形验证码的功能

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

@@ -0,0 +1,62 @@
//go:build example
// +build example
package main
import (
"context"
"fmt"
"log"
"git.toowon.com/jimmy/go-common/captcha"
"git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/factory"
)
func main() {
cfg, err := config.LoadFromFile("./config/example.json")
if err != nil {
log.Fatal(err)
}
app := factory.New(cfg)
cap, err := app.Captcha()
if err != nil {
log.Fatal(err)
}
if !cap.Enabled() {
fmt.Println("captcha disabled — set captcha.enabled=true and configure redis to enable")
return
}
ctx := context.Background()
// 1. 注册场景:生成图形验证码
result, err := cap.Generate(ctx, captcha.SceneRegister)
if err != nil {
log.Fatal(err)
}
fmt.Printf("captcha id: %s\n", result.ID)
fmt.Printf("captcha image length: %d (base64)\n", len(result.ImageBase64))
// 2. 发短信前校验(业务侧在 handler 中调用;此处演示 API
// 实际使用时 answer 来自用户输入
_ = cap.Verify(ctx, captcha.VerifyRequest{
Scene: captcha.SceneRegister,
ID: result.ID,
Answer: "user-input",
})
// 3. 登录防暴力
key := "user@example.com"
status, _ := cap.RecordLoginFailure(ctx, key)
fmt.Printf("login failures: %d, needCaptcha: %v, locked: %v\n",
status.FailCount, status.NeedCaptcha, status.Locked)
need, _ := cap.LoginNeedCaptcha(ctx, key)
fmt.Printf("login need captcha: %v\n", need)
// 登录成功后清除
_ = cap.ClearLoginFailures(ctx, key)
}