You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.2 KiB

  1. package captcha
  2. import (
  3. "context"
  4. "github.com/flipped-aurora/gin-vue-admin/server/global"
  5. "github.com/mojocn/base64Captcha"
  6. "go.uber.org/zap"
  7. "time"
  8. )
  9. func NewDefaultRedisStore() *RedisStore {
  10. return &RedisStore{
  11. Expiration: time.Second * 180,
  12. PreKey: "CAPTCHA_",
  13. }
  14. }
  15. type RedisStore struct {
  16. Expiration time.Duration
  17. PreKey string
  18. Context context.Context
  19. }
  20. func (rs *RedisStore) UseWithCtx(ctx context.Context) base64Captcha.Store {
  21. rs.Context = ctx
  22. return rs
  23. }
  24. func (rs *RedisStore) Set(id string, value string) {
  25. err := global.GVA_REDIS.Set(rs.Context, rs.PreKey+id, value, rs.Expiration).Err()
  26. if err != nil {
  27. global.GVA_LOG.Error("RedisStoreSetError!", zap.Error(err))
  28. }
  29. }
  30. func (rs *RedisStore) Get(key string, clear bool) string {
  31. val, err := global.GVA_REDIS.Get(rs.Context, key).Result()
  32. if err != nil {
  33. global.GVA_LOG.Error("RedisStoreGetError!", zap.Error(err))
  34. return ""
  35. }
  36. if clear {
  37. err := global.GVA_REDIS.Del(rs.Context, key).Err()
  38. if err != nil {
  39. global.GVA_LOG.Error("RedisStoreClearError!", zap.Error(err))
  40. return ""
  41. }
  42. }
  43. return val
  44. }
  45. func (rs *RedisStore) Verify(id, answer string, clear bool) bool {
  46. key := rs.PreKey + id
  47. v := rs.Get(key, clear)
  48. return v == answer
  49. }