antispam.go 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. package antispam
  2. import (
  3. "fmt"
  4. "time"
  5. "go-common/library/cache/redis"
  6. "go-common/library/ecode"
  7. "go-common/library/log"
  8. bm "go-common/library/net/http/blademaster"
  9. "github.com/pkg/errors"
  10. )
  11. const (
  12. _prefixRate = "r_%d_%s_%d"
  13. _prefixTotal = "t_%d_%s_%d"
  14. // antispam
  15. _defSecond = 1
  16. _defHour = 1
  17. )
  18. // Antispam is a antispam instance.
  19. type Antispam struct {
  20. redis *redis.Pool
  21. conf *Config
  22. }
  23. // Config antispam config.
  24. type Config struct {
  25. On bool // switch on/off
  26. Second int // every N second allow N requests.
  27. N int // one unit allow N requests.
  28. Hour int // every N hour allow M requests.
  29. M int // one winodw allow M requests.
  30. Redis *redis.Config
  31. }
  32. func (c *Config) validate() error {
  33. if c == nil {
  34. return errors.New("antispam: empty config")
  35. }
  36. if c.Second < _defSecond {
  37. return errors.New("antispam: invalid Second")
  38. }
  39. if c.Hour < _defHour {
  40. return errors.New("antispam: invalid Hour")
  41. }
  42. return nil
  43. }
  44. // New new a antispam service.
  45. func New(c *Config) (s *Antispam) {
  46. if err := c.validate(); err != nil {
  47. panic(err)
  48. }
  49. s = &Antispam{
  50. redis: redis.NewPool(c.Redis),
  51. }
  52. s.Reload(c)
  53. return s
  54. }
  55. // Reload reload antispam config.
  56. func (s *Antispam) Reload(c *Config) {
  57. if err := c.validate(); err != nil {
  58. log.Error("Failed to reload antispam: %+v", err)
  59. return
  60. }
  61. s.conf = c
  62. }
  63. // Rate antispam by user + path.
  64. func (s *Antispam) Rate(c *bm.Context, second, count int) (err error) {
  65. mid, ok := c.Get("mid")
  66. if !ok {
  67. return
  68. }
  69. curSecond := int(time.Now().Unix())
  70. burst := curSecond - curSecond%second
  71. key := rateKey(mid.(int64), c.Request.URL.Path, burst)
  72. return s.antispam(c, key, second, count)
  73. }
  74. // Total antispam by user + path.
  75. func (s *Antispam) Total(c *bm.Context, hour, count int) (err error) {
  76. second := hour * 3600
  77. mid, ok := c.Get("mid")
  78. if !ok {
  79. return
  80. }
  81. curHour := int(time.Now().Unix() / 3600)
  82. burst := curHour - curHour%hour
  83. key := totalKey(mid.(int64), c.Request.URL.Path, burst)
  84. return s.antispam(c, key, second, count)
  85. }
  86. func (s *Antispam) antispam(c *bm.Context, key string, interval, count int) error {
  87. conn := s.redis.Get(c)
  88. defer conn.Close()
  89. incred, err := redis.Int64(conn.Do("INCR", key))
  90. if err != nil {
  91. return nil
  92. }
  93. if incred == 1 {
  94. conn.Do("EXPIRE", key, interval)
  95. }
  96. if incred > int64(count) {
  97. return ecode.LimitExceed
  98. }
  99. return nil
  100. }
  101. func rateKey(mid int64, path string, burst int) string {
  102. return fmt.Sprintf(_prefixRate, mid, path, burst)
  103. }
  104. func totalKey(mid int64, path string, burst int) string {
  105. return fmt.Sprintf(_prefixTotal, mid, path, burst)
  106. }
  107. func (s *Antispam) ServeHTTP(ctx *bm.Context) {
  108. if err := s.Rate(ctx, s.conf.Second, s.conf.N); err != nil {
  109. ctx.JSON(nil, ecode.LimitExceed)
  110. ctx.Abort()
  111. return
  112. }
  113. if err := s.Total(ctx, s.conf.Hour, s.conf.M); err != nil {
  114. ctx.JSON(nil, ecode.LimitExceed)
  115. ctx.Abort()
  116. return
  117. }
  118. }
  119. // Handler is antispam handle.
  120. func (s *Antispam) Handler() bm.HandlerFunc {
  121. return s.ServeHTTP
  122. }