Commit 74322593 by Qiang Xue

added support for rate limiting.

parent 9a23e313
......@@ -14,7 +14,7 @@ In particular, Yii provides support for the following aspects regarding RESTful
* Authorization;
* Support for HATEOAS;
* Caching via `yii\web\HttpCache`;
* Rate limiting: TBD
* Rate limiting;
* Searching and filtering: TBD
* Testing: TBD
* Automatic generation of API documentation: TBD
......
......@@ -11,6 +11,7 @@ use Yii;
use yii\web\Response;
use yii\web\UnauthorizedHttpException;
use yii\web\UnsupportedMediaTypeHttpException;
use yii\web\TooManyRequestsHttpException;
use yii\web\VerbFilter;
/**
......@@ -116,6 +117,7 @@ class Controller extends \yii\web\Controller
{
if (parent::beforeAction($action)) {
$this->authenticate();
$this->checkRateLimit($action);
return true;
} else {
return false;
......@@ -201,7 +203,6 @@ class Controller extends \yii\web\Controller
}
}
if (!isset($accessToken) || !Yii::$app->getUser()->loginByAccessToken($accessToken)) {
if (!isset($accessToken, $authType)) {
$authType = is_array($this->authType) ? reset($this->authType) : $this->authType;
......@@ -214,6 +215,19 @@ class Controller extends \yii\web\Controller
}
/**
* Ensures the rate limit is not exceeded.
* You may override this method to log the API usage and make sure the rate limit is not exceeded.
* If exceeded, you should throw a [[TooManyRequestsHttpException]], and you may also send some HTTP headers,
* such as `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`,
* to explain the rate limit information.
* @param \yii\base\Action $action the action to be executed
* @throws TooManyRequestsHttpException if the rate limit is exceeded.
*/
protected function checkRateLimit($action)
{
}
/**
* Serializes the specified data.
* The default implementation will create a serializer based on the configuration given by [[serializer]].
* It then uses the serializer to serialize the given data.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment