Skip to content

Commit

Permalink
Add ability to throttle by hour or day as well as weeks
Browse files Browse the repository at this point in the history
  • Loading branch information
MadMikeyB committed Oct 27, 2017
1 parent 51e84ed commit f1738a0
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
17 changes: 16 additions & 1 deletion config/throttleable.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
<?php

return [
/**
* Number of attempts permitted to a single
* IP address before being throttled.
*/
'attempt_limit' => 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
];
10 changes: 7 additions & 3 deletions src/Models/Throttle.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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');
}

}
16 changes: 15 additions & 1 deletion src/Traits/Throttleable.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)

This comment has been minimized.

Copy link
@MadMikeyB

MadMikeyB Oct 27, 2017

Author Owner

This could be done more elegantly, feedback welcomed!

{
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();

Expand Down

0 comments on commit f1738a0

Please sign in to comment.