captchaLogic.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package pub
  2. import (
  3. "context"
  4. "perms-system-server/internal/svc"
  5. "perms-system-server/internal/types"
  6. "github.com/mojocn/base64Captcha"
  7. "github.com/zeromicro/go-zero/core/logx"
  8. )
  9. // defaultCaptchaStore 全进程内共享的内存 store;多实例部署时验证码 ID 会在实例间不一致,
  10. // 属于已知局限——可后续替换为 Redis store。
  11. var defaultCaptchaStore = base64Captcha.DefaultMemStore
  12. type CaptchaLogic struct {
  13. logx.Logger
  14. ctx context.Context
  15. svcCtx *svc.ServiceContext
  16. }
  17. func NewCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CaptchaLogic {
  18. return &CaptchaLogic{
  19. Logger: logx.WithContext(ctx),
  20. ctx: ctx,
  21. svcCtx: svcCtx,
  22. }
  23. }
  24. func (l *CaptchaLogic) Captcha(req *types.CaptchaReq) (*types.CaptchaInfo, error) {
  25. width := req.Width
  26. height := req.Height
  27. if width <= 0 {
  28. width = 240
  29. }
  30. if height <= 0 {
  31. height = 80
  32. }
  33. driver := base64Captcha.NewDriverDigit(height, width, 4, 0.7, 80)
  34. c := base64Captcha.NewCaptcha(driver, defaultCaptchaStore)
  35. id, b64, _, err := c.Generate()
  36. if err != nil {
  37. l.Errorf("captcha generate error: %v", err)
  38. return nil, err
  39. }
  40. return &types.CaptchaInfo{Id: id, Base64Image: b64}, nil
  41. }
  42. // VerifyCaptcha 供 loginLogic 内部调用,校验图片验证码后立即消费(防重放)。
  43. func VerifyCaptcha(id, code string) bool {
  44. return defaultCaptchaStore.Verify(id, code, true)
  45. }