captcha_storage.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (c) [2022] [巴拉迪维 BaratSemet]
  2. // [ohUrlShortener] is licensed under Mulan PSL v2.
  3. // You can use this software according to the terms and conditions of the Mulan PSL v2.
  4. // You may obtain a copy of Mulan PSL v2 at:
  5. // http://license.coscl.org.cn/MulanPSL2
  6. // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
  7. // See the Mulan PSL v2 for more details.
  8. //
  9. // Custom redis storage for captcha, According to https://github.com/dchest/captcha/blob/master/store.go
  10. //
  11. // An object implementing Store interface can be registered with SetCustomStore
  12. // function to handle storage and retrieval of captcha ids and solutions for
  13. // them, replacing the default memory store.
  14. //
  15. // It is the responsibility of an object to delete expired and used captchas
  16. // when necessary (for example, the default memory store collects them in Set
  17. // method after the certain amount of captchas has been stored.)
  18. package storage
  19. import (
  20. "fmt"
  21. "time"
  22. "ohurlshortener/utils"
  23. "github.com/dchest/captcha"
  24. )
  25. const (
  26. DefaultPrefixKey = "oh_captcha"
  27. )
  28. type CaptchaRedisStore struct {
  29. RedisService *RedisService
  30. Expiration time.Duration
  31. KeyPrefix string
  32. }
  33. func NewRedisStore(rs *RedisService, expiration time.Duration, prefixKey string) (captcha.Store, error) {
  34. s := new(CaptchaRedisStore)
  35. s.RedisService = rs
  36. s.Expiration = expiration
  37. s.KeyPrefix = prefixKey
  38. if utils.EmptyString(s.KeyPrefix) {
  39. s.KeyPrefix = DefaultPrefixKey
  40. }
  41. return s, nil
  42. }
  43. func (s *CaptchaRedisStore) Set(id string, digit []byte) {
  44. key := fmt.Sprintf("%s#%s", s.KeyPrefix, id)
  45. val, err := RedisGetString(key)
  46. if !utils.EmptyString(val) || err != nil {
  47. panic(fmt.Sprintf("RedisSet error for captcha key %s. %s", key, err))
  48. }
  49. RedisSet(key, digit, s.Expiration)
  50. }
  51. func (s *CaptchaRedisStore) Get(id string, clear bool) []byte {
  52. key := fmt.Sprintf("%s#%s", s.KeyPrefix, id)
  53. val, err := RedisGetString(key)
  54. if err != nil {
  55. return nil
  56. }
  57. if clear {
  58. RedisDelete(key)
  59. }
  60. return []byte(val)
  61. }