Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
19 / 19 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| AccessList | |
100.00% |
19 / 19 |
|
100.00% |
1 / 1 |
10 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
19 / 19 |
|
100.00% |
1 / 1 |
10 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace Miniframe\Middleware; |
| 4 | |
| 5 | use Miniframe\Core\AbstractMiddleware; |
| 6 | use Miniframe\Core\Config; |
| 7 | use Miniframe\Core\HostMatch; |
| 8 | use Miniframe\Core\Request; |
| 9 | use Miniframe\Response\ForbiddenResponse; |
| 10 | use RuntimeException; |
| 11 | |
| 12 | class AccessList extends AbstractMiddleware |
| 13 | { |
| 14 | /** |
| 15 | * Validates a user IP towards an allow/deny list. |
| 16 | * |
| 17 | * @param Request $request Reference to the Request object. |
| 18 | * @param Config $config Reference to the Config object. |
| 19 | */ |
| 20 | public function __construct(Request $request, Config $config) |
| 21 | { |
| 22 | parent::__construct($request, $config); |
| 23 | |
| 24 | // Do we have an IP address? |
| 25 | $validateIp = $request->getServer('REMOTE_ADDR'); |
| 26 | if (!is_string($validateIp)) { |
| 27 | return; |
| 28 | } |
| 29 | |
| 30 | // Determine the order |
| 31 | $order = 'deny,allow'; |
| 32 | if ($this->config->has('accesslist', 'order')) { |
| 33 | $orderValue = $this->config->get('accesslist', 'order'); |
| 34 | if (!is_string($orderValue)) { |
| 35 | throw new RuntimeException('Invalid order value: ' . var_export($orderValue, true)); |
| 36 | } |
| 37 | $order = preg_replace('/[\s]+/', '', strtolower($orderValue)); |
| 38 | } |
| 39 | |
| 40 | if ($order == 'deny,allow') { |
| 41 | // First, all Deny directives are evaluated; if any match, the request is denied unless it also matches an |
| 42 | // Allow directive. Any requests which do not match any Allow or Deny directives are permitted. |
| 43 | if ( |
| 44 | (new HostMatch())->matchList($config, 'accesslist', 'deny', $validateIp) !== false |
| 45 | && (new HostMatch())->matchList($config, 'accesslist', 'allow', $validateIp) !== true |
| 46 | ) { |
| 47 | throw new ForbiddenResponse(); |
| 48 | } |
| 49 | } elseif ($order == 'allow,deny') { |
| 50 | // First, all Allow directives are evaluated; at least one must match, or the request is rejected. Next, |
| 51 | // all Deny directives are evaluated. If any matches, the request is rejected. Last, any requests which do |
| 52 | // not match an Allow or a Deny directive are denied by default. |
| 53 | if ( |
| 54 | !( |
| 55 | (new HostMatch())->matchList($config, 'accesslist', 'allow', $validateIp) === true |
| 56 | && (new HostMatch())->matchList($config, 'accesslist', 'deny', $validateIp) !== true |
| 57 | ) |
| 58 | ) { |
| 59 | throw new ForbiddenResponse(); |
| 60 | } |
| 61 | } else { |
| 62 | throw new \RuntimeException('Invalid order: ' . $order); |
| 63 | } |
| 64 | } |
| 65 | } |