From f1738a022975a551a4b642ea65cbec9200961b34 Mon Sep 17 00:00:00 2001 From: Michael Burton Date: Fri, 27 Oct 2017 22:59:20 +0100 Subject: [PATCH] Add ability to throttle by hour or day as well as weeks --- config/throttleable.php | 17 ++++++++++++++++- src/Models/Throttle.php | 10 +++++++--- src/Traits/Throttleable.php | 16 +++++++++++++++- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/config/throttleable.php b/config/throttleable.php index c706264..dc57521 100644 --- a/config/throttleable.php +++ b/config/throttleable.php @@ -1,6 +1,21 @@ 10, - 'expiry_weeks' => 1 + + /** + * The datetime metric to use for expirations + * Available options are hour, day or week. + */ + 'expiry_metric' => 'week', + + /** + * The number of hours, days or weeks to + * keep a throttle valid for. + */ + 'expiry_timelimit' => 1 ]; diff --git a/src/Models/Throttle.php b/src/Models/Throttle.php index 1cf250c..162ee10 100644 --- a/src/Models/Throttle.php +++ b/src/Models/Throttle.php @@ -17,8 +17,11 @@ class Throttle extends Model /** @var int Number of attempts allowed before the user is throttled */ public $attemptLimit; - /** @var int Number of weeks before throttle expires */ - public $expiryWeeks; + /** @var int The Time Metric to use for expiry time limit */ + public $expiryMetric; + + /** @var int Number of Hours, Days or Weeks before throttle expires */ + public $expiryTimeLimit; /** @var bool */ public $timestamps = false; @@ -36,7 +39,8 @@ public function __construct($request, $attemptLimit = null, $expiryWeeks = null) { $this->request = $request; $this->attemptLimit = $attemptLimit ?? config('throttleable.attempt_limit'); - $this->expiryWeeks = $expiryWeeks ?? config('throttleable.expiry_weeks'); + $this->expiryMetric = $expiryMetric ?? config('throttleable.expiry_metric'); + $this->expiryTimeLimit = $expiryTimeLimit ?? config('throttleable.expiry_timelimit'); } } diff --git a/src/Traits/Throttleable.php b/src/Traits/Throttleable.php index f6abd7a..2faae6d 100644 --- a/src/Traits/Throttleable.php +++ b/src/Traits/Throttleable.php @@ -57,7 +57,21 @@ protected function createThrottle() { $this->ip = $this->request->ip(); $this->attempts = 0; - $this->expires_at = Carbon::now()->addWeeks($this->expiryWeeks); + switch ($this->expiryMetric) + { + case 'hour': + $this->expires_at = Carbon::now()->addHours($this->expiryTimeLimit); + break; + + case 'day': + $this->expires_at = Carbon::now()->addDays($this->expiryTimeLimit); + break; + + default: + case 'week': + $this->expires_at = Carbon::now()->addWeeks($this->expiryTimeLimit); + break; + } $this->created_at = Carbon::now(); $throttle = $this->save();