package pub import ( "context" "perms-system-server/internal/svc" "perms-system-server/internal/types" "github.com/mojocn/base64Captcha" "github.com/zeromicro/go-zero/core/logx" ) // defaultCaptchaStore 全进程内共享的内存 store;多实例部署时验证码 ID 会在实例间不一致, // 属于已知局限——可后续替换为 Redis store。 var defaultCaptchaStore = base64Captcha.DefaultMemStore type CaptchaLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CaptchaLogic { return &CaptchaLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *CaptchaLogic) Captcha(req *types.CaptchaReq) (*types.CaptchaInfo, error) { width := req.Width height := req.Height if width <= 0 { width = 240 } if height <= 0 { height = 80 } driver := base64Captcha.NewDriverDigit(height, width, 4, 0.7, 80) c := base64Captcha.NewCaptcha(driver, defaultCaptchaStore) id, b64, _, err := c.Generate() if err != nil { l.Errorf("captcha generate error: %v", err) return nil, err } return &types.CaptchaInfo{Id: id, Base64Image: b64}, nil } // VerifyCaptcha 供 loginLogic 内部调用,校验图片验证码后立即消费(防重放)。 func VerifyCaptcha(id, code string) bool { return defaultCaptchaStore.Verify(id, code, true) }