base64.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package captcha
  2. import (
  3. "fmt"
  4. "git.bvbej.com/bvbej/base-golang/pkg/cache"
  5. "github.com/mojocn/base64Captcha"
  6. "go.uber.org/zap"
  7. "time"
  8. )
  9. const RedisKeyPrefixCaptcha = "captcha:base64:"
  10. var _ base64Captcha.Store = (*store)(nil)
  11. type store struct {
  12. cache cache.Repo
  13. ttl time.Duration
  14. logger *zap.Logger
  15. }
  16. func (s *store) Set(id string, value string) error {
  17. err := s.cache.Set(RedisKeyPrefixCaptcha+id, value, s.ttl)
  18. if err != nil {
  19. s.logger.Error(fmt.Sprintf("hu缓存Captcha信息错误[%s]", err))
  20. return err
  21. }
  22. return nil
  23. }
  24. func (s *store) Get(id string, clear bool) string {
  25. value, err := s.cache.Get(RedisKeyPrefixCaptcha + id)
  26. if err != nil {
  27. s.logger.Error(fmt.Sprintf("获取Captcha信息错误[%s]", err))
  28. }
  29. return value
  30. }
  31. func (s *store) Verify(id, answer string, clear bool) bool {
  32. return s.Get(id, clear) == answer
  33. }
  34. func NewStore(cache cache.Repo, ttl time.Duration, logger *zap.Logger) base64Captcha.Store {
  35. return &store{
  36. cache: cache,
  37. ttl: ttl,
  38. logger: logger,
  39. }
  40. }
  41. var _ Captcha = (*captcha)(nil)
  42. type Captcha interface {
  43. Generate() (id, b64s string, err error)
  44. Verify(id, value string) bool
  45. }
  46. type captcha struct {
  47. conf *base64Captcha.DriverString
  48. store base64Captcha.Store
  49. }
  50. func NewCaptcha(store base64Captcha.Store, height, width, length int) Captcha {
  51. conf := &base64Captcha.DriverString{
  52. Height: height,
  53. Width: width,
  54. Length: length,
  55. }
  56. return &captcha{
  57. conf: conf,
  58. store: store,
  59. }
  60. }
  61. func (c *captcha) Generate() (id, b64s string, err error) {
  62. driver := base64Captcha.DriverString.ConvertFonts(c.conf)
  63. newCaptcha := base64Captcha.NewCaptcha(driver, c.store)
  64. return newCaptcha.Generate()
  65. }
  66. func (c *captcha) Verify(id, value string) bool {
  67. return c.store.Verify(id, value, true)
  68. }