-
Notifications
You must be signed in to change notification settings - Fork 11
/
IpRateLimiter.php
61 lines (48 loc) · 1.43 KB
/
IpRateLimiter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
namespace ethercreative\ratelimiter;
use Yii;
/**
* Class IpRateLimiter
*
* @package ethercreative\ratelimiter
*/
class IpRateLimiter extends \yii\filters\RateLimiter
{
/**
* @var boolean whether to separate rate limiting between non and authenticated users
*/
public $separateRates = true;
/**
* @var integer the maximum number of allowed requests
*/
public $rateLimit;
/**
* @var integer the time period for the rates to apply to
*/
public $timePeriod;
/**
* @inheritdoc
*/
public function beforeAction($action)
{
$user = $this->user;
if ($this->separateRates) {
$user = $user ?: (Yii::$app->getUser() ? Yii::$app->getUser()->getIdentity(false) : null);
}
/** @var IpRateLimitInterface $identityClass */
$identityClass = Yii::$app->getUser()->identityClass;
$user = $user ?: $identityClass::findByIp(Yii::$app->getRequest()->getUserIP(), $this->rateLimit,
$this->timePeriod);
if ($user instanceof IpRateLimitInterface) {
Yii::trace('Check rate limit', __METHOD__);
$this->checkRateLimit(
$user,
$this->request ?: Yii::$app->getRequest(),
$this->response ?: Yii::$app->getResponse(),
$action
);
return true;
}
return parent::beforeAction($action);
}
}