captcha.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package service
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/text/gstr"
  5. "github.com/mojocn/base64Captcha"
  6. )
  7. type ICaptcha interface {
  8. GetVerifyImgString(ctx context.Context) (idKeyC string, base64stringC string, err error)
  9. VerifyString(id, answer string) bool
  10. }
  11. type captchaImpl struct {
  12. driver *base64Captcha.DriverString
  13. store base64Captcha.Store
  14. }
  15. var (
  16. captcha = captchaImpl{
  17. driver: &base64Captcha.DriverString{
  18. Height: 80,
  19. Width: 240,
  20. NoiseCount: 50,
  21. ShowLineOptions: 20,
  22. Length: 4,
  23. Source: "abcdefghjkmnpqrstuvwxyz23456789",
  24. Fonts: []string{"chromohv.ttf"},
  25. },
  26. store: base64Captcha.DefaultMemStore,
  27. }
  28. )
  29. func Captcha() ICaptcha {
  30. return ICaptcha(&captcha)
  31. }
  32. // GetVerifyImgString 获取字母数字混合验证码
  33. func (s *captchaImpl) GetVerifyImgString(ctx context.Context) (idKeyC string, base64stringC string, err error) {
  34. driver := s.driver.ConvertFonts()
  35. c := base64Captcha.NewCaptcha(driver, s.store)
  36. idKeyC, base64stringC, err = c.Generate()
  37. return
  38. }
  39. // VerifyString 验证输入的验证码是否正确
  40. func (s *captchaImpl) VerifyString(id, answer string) bool {
  41. c := base64Captcha.NewCaptcha(s.driver, s.store)
  42. answer = gstr.ToLower(answer)
  43. return c.Verify(id, answer, true)
  44. }