RateLimiter.php 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\filters;
  8. use Yii;
  9. use yii\base\ActionFilter;
  10. use yii\web\Request;
  11. use yii\web\Response;
  12. use yii\web\TooManyRequestsHttpException;
  13. /**
  14. * RateLimiter implements a rate limiting algorithm based on the [leaky bucket algorithm](http://en.wikipedia.org/wiki/Leaky_bucket).
  15. *
  16. * You may use RateLimiter by attaching it as a behavior to a controller or module, like the following,
  17. *
  18. * ```php
  19. * public function behaviors()
  20. * {
  21. * return [
  22. * 'rateLimiter' => [
  23. * 'class' => \yii\filters\RateLimiter::className(),
  24. * ],
  25. * ];
  26. * }
  27. * ```
  28. *
  29. * When the user has exceeded his rate limit, RateLimiter will throw a [[TooManyRequestsHttpException]] exception.
  30. *
  31. * Note that RateLimiter requires [[user]] to implement the [[RateLimitInterface]]. RateLimiter will
  32. * do nothing if [[user]] is not set or does not implement [[RateLimitInterface]].
  33. *
  34. * @author Qiang Xue <qiang.xue@gmail.com>
  35. * @since 2.0
  36. */
  37. class RateLimiter extends ActionFilter
  38. {
  39. /**
  40. * @var bool whether to include rate limit headers in the response
  41. */
  42. public $enableRateLimitHeaders = true;
  43. /**
  44. * @var string the message to be displayed when rate limit exceeds
  45. */
  46. public $errorMessage = 'Rate limit exceeded.';
  47. /**
  48. * @var RateLimitInterface the user object that implements the RateLimitInterface.
  49. * If not set, it will take the value of `Yii::$app->user->getIdentity(false)`.
  50. */
  51. public $user;
  52. /**
  53. * @var Request the current request. If not set, the `request` application component will be used.
  54. */
  55. public $request;
  56. /**
  57. * @var Response the response to be sent. If not set, the `response` application component will be used.
  58. */
  59. public $response;
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function init()
  64. {
  65. if ($this->request === null) {
  66. $this->request = Yii::$app->getRequest();
  67. }
  68. if ($this->response === null) {
  69. $this->response = Yii::$app->getResponse();
  70. }
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function beforeAction($action)
  76. {
  77. if ($this->user === null && Yii::$app->getUser()) {
  78. $this->user = Yii::$app->getUser()->getIdentity(false);
  79. }
  80. if ($this->user instanceof RateLimitInterface) {
  81. Yii::debug('Check rate limit', __METHOD__);
  82. $this->checkRateLimit($this->user, $this->request, $this->response, $action);
  83. } elseif ($this->user) {
  84. Yii::info('Rate limit skipped: "user" does not implement RateLimitInterface.', __METHOD__);
  85. } else {
  86. Yii::info('Rate limit skipped: user not logged in.', __METHOD__);
  87. }
  88. return true;
  89. }
  90. /**
  91. * Checks whether the rate limit exceeds.
  92. * @param RateLimitInterface $user the current user
  93. * @param Request $request
  94. * @param Response $response
  95. * @param \yii\base\Action $action the action to be executed
  96. * @throws TooManyRequestsHttpException if rate limit exceeds
  97. */
  98. public function checkRateLimit($user, $request, $response, $action)
  99. {
  100. list($limit, $window) = $user->getRateLimit($request, $action);
  101. list($allowance, $timestamp) = $user->loadAllowance($request, $action);
  102. $current = time();
  103. $allowance += (int) (($current - $timestamp) * $limit / $window);
  104. if ($allowance > $limit) {
  105. $allowance = $limit;
  106. }
  107. if ($allowance < 1) {
  108. $user->saveAllowance($request, $action, 0, $current);
  109. $this->addRateLimitHeaders($response, $limit, 0, $window);
  110. throw new TooManyRequestsHttpException($this->errorMessage);
  111. }
  112. $user->saveAllowance($request, $action, $allowance - 1, $current);
  113. $this->addRateLimitHeaders($response, $limit, $allowance - 1, (int) (($limit - $allowance + 1) * $window / $limit));
  114. }
  115. /**
  116. * Adds the rate limit headers to the response.
  117. * @param Response $response
  118. * @param int $limit the maximum number of allowed requests during a period
  119. * @param int $remaining the remaining number of allowed requests within the current period
  120. * @param int $reset the number of seconds to wait before having maximum number of allowed requests again
  121. */
  122. public function addRateLimitHeaders($response, $limit, $remaining, $reset)
  123. {
  124. if ($this->enableRateLimitHeaders) {
  125. $response->getHeaders()
  126. ->set('X-Rate-Limit-Limit', $limit)
  127. ->set('X-Rate-Limit-Remaining', $remaining)
  128. ->set('X-Rate-Limit-Reset', $reset);
  129. }
  130. }
  131. }