RateLimiter.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. /**
  3. * @package Grav\Plugin\Login
  4. *
  5. * @copyright Copyright (C) 2014 - 2021 RocketTheme, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Plugin\Login;
  9. /**
  10. * Class RateLimiter
  11. * @package Grav\Plugin\Login\RateLimiter
  12. */
  13. class RateLimiter
  14. {
  15. /** @var LoginCache */
  16. protected $cache;
  17. /** @var int */
  18. protected $maxCount;
  19. /** @var int */
  20. protected $interval;
  21. /**
  22. * RateLimiter constructor.
  23. * @param string $context
  24. * @param int $maxCount
  25. * @param int|null $interval
  26. */
  27. public function __construct($context, $maxCount, $interval)
  28. {
  29. $this->cache = new LoginCache($context, (int)$interval * 60);
  30. $this->maxCount = (int) $maxCount;
  31. $this->interval = (int) $interval;
  32. }
  33. /**
  34. * @return int
  35. */
  36. public function getInterval()
  37. {
  38. return $this->interval;
  39. }
  40. /**
  41. * Check if user has hit rate limiter. Remember to use registerRateLimitedAction() before doing the check.
  42. *
  43. * @param string $key
  44. * @param string $type
  45. * @return bool
  46. */
  47. public function isRateLimited($key, $type = 'username')
  48. {
  49. if (!$key || !$this->interval) {
  50. return false;
  51. }
  52. return $this->maxCount && \count($this->getAttempts($key, $type)) > $this->maxCount;
  53. }
  54. /**
  55. *
  56. *
  57. * @param string $key
  58. * @param string $type
  59. * @return array
  60. */
  61. public function getAttempts($key, $type = 'username')
  62. {
  63. return (array) $this->cache->get($type . $key, []);
  64. }
  65. /**
  66. * Register rate limited action.
  67. *
  68. * @param string $key
  69. * @param string $type
  70. * @return $this
  71. */
  72. public function registerRateLimitedAction($key, $type = 'username')
  73. {
  74. if ($key && $this->interval) {
  75. $tries = (array)$this->cache->get($type . $key, []);
  76. $tries[] = time();
  77. $this->cache->set($type . $key, $tries);
  78. }
  79. return $this;
  80. }
  81. /**
  82. * Reset the user rate limit counter.
  83. *
  84. * @param string $key
  85. * @param string $type
  86. * @return $this
  87. */
  88. public function resetRateLimit($key, $type = 'username')
  89. {
  90. if ($key) {
  91. $this->cache->delete($type . $key);
  92. }
  93. return $this;
  94. }
  95. }