1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace DavidePastore\Slim\RestrictRoute; |
4
|
|
|
|
5
|
|
|
use Respect\Validation\Validator as v; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* RestrictRoute for Slim. |
9
|
|
|
*/ |
10
|
|
|
class RestrictRoute |
11
|
|
|
{ |
12
|
|
|
protected $options = [ |
13
|
|
|
'ip' => null, |
14
|
|
|
]; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Create new RestrictRoute service provider. |
18
|
|
|
* |
19
|
|
|
* @param array $options |
20
|
|
|
*/ |
21
|
6 |
|
public function __construct(array $options = []) |
22
|
|
|
{ |
23
|
6 |
|
$this->options = array_merge($this->options, $options); |
24
|
6 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* RestrictRoute middleware invokable class. |
28
|
|
|
* |
29
|
|
|
* @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request |
30
|
|
|
* @param \Psr\Http\Message\ResponseInterface $response PSR7 response |
31
|
|
|
* @param callable $next Next middleware |
32
|
|
|
* |
33
|
|
|
* @return \Psr\Http\Message\ResponseInterface |
34
|
|
|
*/ |
35
|
6 |
|
public function __invoke($request, $response, $next) |
36
|
|
|
{ |
37
|
6 |
|
$ipAddress = $request->getAttribute('ip_address'); |
38
|
6 |
|
if ($this->options['ip']) { |
39
|
6 |
|
if (is_array($this->options['ip'])) { |
40
|
2 |
|
$isAllowed = false; |
41
|
2 |
|
foreach ($this->options['ip'] as $range) { |
42
|
2 |
|
if (v::ip($range)->validate($ipAddress)) { |
43
|
2 |
|
$isAllowed = true; |
44
|
|
|
} |
45
|
|
|
} |
46
|
2 |
|
if ($isAllowed === false) { |
47
|
2 |
|
return $response->withStatus(401); |
48
|
|
|
} |
49
|
4 |
|
} elseif (!v::ip($this->options['ip'])->validate($ipAddress)) { |
50
|
2 |
|
return $response->withStatus(401); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
3 |
|
return $next($request, $response); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Get the options array. |
59
|
|
|
* |
60
|
|
|
* @return array |
61
|
|
|
*/ |
62
|
1 |
|
public function getOptions() |
63
|
|
|
{ |
64
|
1 |
|
return $this->options; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Set the options array. |
69
|
|
|
* |
70
|
|
|
* @param array $options The options array. |
71
|
|
|
*/ |
72
|
1 |
|
public function setOptions($options) |
73
|
|
|
{ |
74
|
1 |
|
$this->options = $options; |
75
|
1 |
|
} |
76
|
|
|
} |
77
|
|
|
|