captcha.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * @desc:验证码处理
  3. * @company:云南奇讯科技有限公司
  4. * @Author: yixiaohu<yxh669@qq.com>
  5. * @Date: 2022/9/28 9:01
  6. */
  7. package captcha
  8. import (
  9. "context"
  10. "github.com/gogf/gf/v2/text/gstr"
  11. "github.com/mojocn/base64Captcha"
  12. "github.com/tiger1103/gfast/v3/internal/app/common/service"
  13. )
  14. func init() {
  15. service.RegisterCaptcha(New())
  16. }
  17. func New() *sCaptcha {
  18. return &sCaptcha{
  19. driver: &base64Captcha.DriverString{
  20. Height: 80,
  21. Width: 240,
  22. NoiseCount: 50,
  23. ShowLineOptions: 20,
  24. Length: 4,
  25. Source: "abcdefghjkmnpqrstuvwxyz23456789",
  26. Fonts: []string{"chromohv.ttf"},
  27. },
  28. store: base64Captcha.DefaultMemStore,
  29. }
  30. }
  31. type sCaptcha struct {
  32. driver *base64Captcha.DriverString
  33. store base64Captcha.Store
  34. }
  35. var (
  36. captcha = sCaptcha{
  37. driver: &base64Captcha.DriverString{
  38. Height: 80,
  39. Width: 240,
  40. NoiseCount: 50,
  41. ShowLineOptions: 20,
  42. Length: 4,
  43. Source: "abcdefghjkmnpqrstuvwxyz23456789",
  44. Fonts: []string{"chromohv.ttf"},
  45. },
  46. store: base64Captcha.DefaultMemStore,
  47. }
  48. )
  49. // GetVerifyImgString 获取字母数字混合验证码
  50. func (s *sCaptcha) GetVerifyImgString(ctx context.Context) (idKeyC string, base64stringC string, err error) {
  51. driver := s.driver.ConvertFonts()
  52. c := base64Captcha.NewCaptcha(driver, s.store)
  53. idKeyC, base64stringC, err = c.Generate()
  54. return
  55. }
  56. // VerifyString 验证输入的验证码是否正确
  57. func (s *sCaptcha) VerifyString(id, answer string) bool {
  58. c := base64Captcha.NewCaptcha(s.driver, s.store)
  59. answer = gstr.ToLower(answer)
  60. return c.Verify(id, answer, true)
  61. }