123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- <?php
- namespace app\common\util;
- class ThrottlesUtil
- {
- private $limitEnabled = true;
- private $limitTime = 1*60;
- private $maxAttempts = 5;
- private $lockTime = 30*60;
- private $pre = "<|login|>";
- public function __construct($config = [])
- {
- if(isset($config['time'])){
- $this->limitTime = (int)$config['time'];
- }
- if(isset($config['attempts'])){
- $this->maxAttempts = (int)$config['attempts'];
- }
- if(isset($config['lock'])){
- $this->lockTime = (int)$config['lock'];
- }
- if(isset($config['enabled'])){
- $this->limitEnabled = $config['enabled'];
- }
- }
-
- public function tooManyAttempts($account,$pre = 'throttles'){
- if(!$this->limitEnabled){
- return false;
- }
- $key = $pre.$this->pre.$account;
-
- if (cache($key.':lockout')) {
- return true;
- }
-
- if ($this->attempts($account,$pre) > $this->maxAttempts) {
-
- cache($key.':lockout',time() + $this->lockTime, $this->lockTime);
-
- $this->resetAttempts($key);
- return true;
- }
- return false;
- }
-
- public function attempts($account,$pre = 'throttles'){
- $key = $pre.$this->pre.$account;
- $times = cache($key);
- $ndata = [];
- $count = 0;
- $curTime = time();
- if($times){
- $data = json_decode($times,true);
- if(!empty($data)){
- $count = count($data);
- foreach ($data as $k=>$v){
- if($curTime - $v < $this->limitTime){
- $ndata[] = $v;
- }
- }
- }
- }
- $ndata[] = $curTime;
- cache($key,json_encode($ndata),$this->limitTime);
- return $count + 1;
- }
-
- public function resetAttempts($account,$pre = 'throttles'){
- $key = $pre.$this->pre.$account;
- cache($key,NULL);
- cache($key.':lockout',NULL);
- }
- }
|