base64.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package captcha
  2. import (
  3. "git.bvbej.com/bvbej/base-golang/pkg/cache"
  4. "github.com/mojocn/base64Captcha"
  5. "go.uber.org/zap"
  6. "strings"
  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. return err
  20. }
  21. return nil
  22. }
  23. func (s *store) Get(id string, clear bool) string {
  24. value, err := s.cache.Get(RedisKeyPrefixCaptcha + id)
  25. if err == nil && clear {
  26. s.cache.Del(RedisKeyPrefixCaptcha + id)
  27. }
  28. return value
  29. }
  30. func (s *store) Verify(id, answer string, clear bool) bool {
  31. value := s.Get(id, clear)
  32. if value == "" || answer == "" {
  33. return false
  34. }
  35. return strings.ToLower(value) == strings.ToLower(answer)
  36. }
  37. func NewStore(cache cache.Repo, ttl time.Duration) base64Captcha.Store {
  38. return &store{
  39. cache: cache,
  40. ttl: ttl,
  41. }
  42. }
  43. var _ Captcha = (*captcha)(nil)
  44. type Captcha interface {
  45. Generate() (id, b64s string, err error)
  46. Verify(id, value string) bool
  47. }
  48. type captcha struct {
  49. conf *base64Captcha.DriverString
  50. store base64Captcha.Store
  51. }
  52. func NewCaptcha(store base64Captcha.Store, height, width, length int) Captcha {
  53. conf := &base64Captcha.DriverString{
  54. Height: height,
  55. Width: width,
  56. NoiseCount: length * 2,
  57. ShowLineOptions: base64Captcha.OptionShowHollowLine,
  58. Length: length,
  59. Source: "ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz0123456789",
  60. }
  61. return &captcha{
  62. conf: conf,
  63. store: store,
  64. }
  65. }
  66. func (c *captcha) Generate() (id, b64s string, err error) {
  67. driver := c.conf.ConvertFonts()
  68. newCaptcha := base64Captcha.NewCaptcha(driver, c.store)
  69. return newCaptcha.Generate()
  70. }
  71. func (c *captcha) Verify(id, value string) bool {
  72. return c.store.Verify(id, value, true)
  73. }