forked from codeigniter4/shield
/
AuthRates.php
61 lines (54 loc) · 1.79 KB
/
AuthRates.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
declare(strict_types=1);
namespace CodeIgniter\Shield\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Shield\Auth;
/**
* Auth Rate-Limiting Filter.
*
* Provides rated limiting intended for Auth routes.
*/
class AuthRates implements FilterInterface
{
/**
* Intened for use on auth form pages to restrict the number
* of attempts that can be generated. Restricts it to 10 attempts
* per minute, which is what auth0 uses.
*
* @see https://auth0.com/docs/troubleshoot/customer-support/operational-policies/rate-limit-policy/database-connections-rate-limits
*
* @param array|null $arguments
*
* @return RedirectResponse|void
*/
public function before(RequestInterface $request, $arguments = null)
{
if (! $request instanceof IncomingRequest) {
return;
}
$throttler = service('throttler');
// Restrict an IP address to no more than 10 requests
// per minute on any auth-form pages (login, register, forgot, etc).
if ($throttler->check(md5($request->getIPAddress()), 10, MINUTE, 1) === false) {
return service('response')->setStatusCode(
429,
$message = lang('Auth.throttled', [$throttler->getTokenTime()])
);
}
}
/**
* We don't have anything to do here.
*
* @param Response|ResponseInterface $response
* @param array|null $arguments
*/
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null): void
{
// Nothing required
}
}