-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHostForbiddenMiddleware.php
74 lines (66 loc) · 1.97 KB
/
HostForbiddenMiddleware.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
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
namespace WebmanTech\Swagger\Middleware;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
use WebmanTech\Swagger\DTO\ConfigHostForbiddenDTO;
class HostForbiddenMiddleware implements MiddlewareInterface
{
/**
* @var ConfigHostForbiddenDTO
*/
protected $config;
/**
* @param array|ConfigHostForbiddenDTO $config
*/
public function __construct($config = [])
{
if (!$config instanceof ConfigHostForbiddenDTO) {
$config = new ConfigHostForbiddenDTO($config);
}
$this->config = $config;
}
/**
* @inheritDoc
*/
public function process(Request $request, callable $handler): Response
{
if ($this->config->enable) {
[$can, $ip] = $this->checkIp($request);
if (!$can) {
[$can, $host] = $this->checkHost($request);
if (!$can) {
return response("Forbidden for ip({$ip}) and host({$host})", 403);
}
}
}
return $handler($request);
}
private function checkIp(Request $request): array
{
if ($this->config->ip_white_list_intranet === null || $this->config->ip_white_list === null) {
return [true, ''];
}
$ip = $request->getRealIp();
if ($this->config->ip_white_list_intranet && Request::isIntranetIp($ip)) {
return [true, ''];
}
if (in_array($ip, $this->config->ip_white_list)) {
return [true, ''];
}
return [false, $ip];
}
private function checkHost(Request $request): array
{
if ($this->config->host_white_list === null) {
return [true, ''];
}
$host = $request->host();
foreach ($this->config->host_white_list as $needle) {
if ($needle !== '' && strpos($host, $needle) !== false) {
return [true, ''];
}
}
return [false, $host];
}
}