base64.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. "strings"
  8. "time"
  9. )
  10. var _ base64Captcha.Store = (*store)(nil)
  11. type store struct {
  12. cache cache.Repo
  13. ttl time.Duration
  14. logger *zap.Logger
  15. ns string
  16. prefix string
  17. }
  18. func (s *store) Set(id string, value string) error {
  19. err := s.cache.Set(fmt.Sprintf("%s%s%s", s.ns, s.prefix, id), value, s.ttl)
  20. if err != nil {
  21. return err
  22. }
  23. return nil
  24. }
  25. func (s *store) Get(id string, clear bool) string {
  26. value, err := s.cache.Get(fmt.Sprintf("%s%s%s", s.ns, s.prefix, id))
  27. if err == nil && clear {
  28. s.cache.Del(fmt.Sprintf("%s%s%s", s.ns, s.prefix, id))
  29. }
  30. return value
  31. }
  32. func (s *store) Verify(id, answer string, clear bool) bool {
  33. value := s.Get(id, clear)
  34. if value == "" || answer == "" {
  35. return false
  36. }
  37. return strings.ToLower(value) == strings.ToLower(answer)
  38. }
  39. func NewStore(cache cache.Repo, ttl time.Duration, namespace string) base64Captcha.Store {
  40. return &store{
  41. cache: cache,
  42. ttl: ttl,
  43. ns: namespace,
  44. prefix: "captcha:base64:",
  45. }
  46. }
  47. var _ Captcha = (*captcha)(nil)
  48. type Captcha interface {
  49. Generate() (id, b64s string, err error)
  50. Verify(id, value string) bool
  51. }
  52. type captcha struct {
  53. driver base64Captcha.Driver
  54. store base64Captcha.Store
  55. }
  56. func NewStringCaptcha(store base64Captcha.Store, height, width, length int) Captcha {
  57. conf := &base64Captcha.DriverString{
  58. Height: height,
  59. Width: width,
  60. NoiseCount: length,
  61. ShowLineOptions: base64Captcha.OptionShowHollowLine,
  62. Length: length,
  63. Source: "ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz0123456789",
  64. }
  65. return &captcha{
  66. driver: conf.ConvertFonts(),
  67. store: store,
  68. }
  69. }
  70. func NewDigitCaptcha(store base64Captcha.Store, height, width, length int) Captcha {
  71. conf := base64Captcha.NewDriverDigit(height, width, length, 0.7, height)
  72. return &captcha{
  73. driver: conf,
  74. store: store,
  75. }
  76. }
  77. func (c *captcha) Generate() (id, b64s string, err error) {
  78. newCaptcha := base64Captcha.NewCaptcha(c.driver, c.store)
  79. return newCaptcha.Generate()
  80. }
  81. func (c *captcha) Verify(id, value string) bool {
  82. return c.store.Verify(id, value, true)
  83. }