base64.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. driver base64Captcha.Driver
  50. store base64Captcha.Store
  51. }
  52. func NewStringCaptcha(store base64Captcha.Store, height, width, length int) Captcha {
  53. conf := &base64Captcha.DriverString{
  54. Height: height,
  55. Width: width,
  56. NoiseCount: length,
  57. ShowLineOptions: base64Captcha.OptionShowHollowLine,
  58. Length: length,
  59. Source: "ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz0123456789",
  60. }
  61. return &captcha{
  62. driver: conf.ConvertFonts(),
  63. store: store,
  64. }
  65. }
  66. func NewDigitCaptcha(store base64Captcha.Store, height, width, length int) Captcha {
  67. conf := base64Captcha.NewDriverDigit(height, width, length, 0.7, height)
  68. return &captcha{
  69. driver: conf,
  70. store: store,
  71. }
  72. }
  73. func (c *captcha) Generate() (id, b64s string, err error) {
  74. newCaptcha := base64Captcha.NewCaptcha(c.driver, c.store)
  75. return newCaptcha.Generate()
  76. }
  77. func (c *captcha) Verify(id, value string) bool {
  78. return c.store.Verify(id, value, true)
  79. }