Skip to content

Commit

Permalink
feature: 对 host 的禁用增加 ip 的支持
Browse files Browse the repository at this point in the history
  • Loading branch information
krissss committed Jan 10, 2024
1 parent a20d007 commit 172fd33
Showing 1 changed file with 32 additions and 18 deletions.
50 changes: 32 additions & 18 deletions src/Middleware/HostForbiddenMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,9 @@ class HostForbiddenMiddleware implements MiddlewareInterface
{
protected $config = [
'enable' => true,
'host_white_list_default' => [
// 常规的内网地址允许访问
'127.0.0.1',
'localhost',
'192.168.',
'172.16.',
'10.',
],
'host_white_list' => [],
'ip_white_list_intranet' => true, // 允许所有内网访问
'ip_white_list' => [], // 允许访问的 ip
'host_white_list' => [], // 允许访问的 host
];

public function __construct(array $config = [])
Expand All @@ -36,24 +30,44 @@ public function __construct(array $config = [])
public function process(Request $request, callable $handler): Response
{
if ($this->config['enable']) {
$host = $request->host();
if (!$this->isInWhiteList($host)) {
return response('Forbidden for: ' . $host, 403);
[$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 isInWhiteList(string $host): bool
private function checkIp(Request $request): array
{
$whiteList = array_merge($this->config['host_white_list_default'], $this->config['host_white_list']);
foreach ($whiteList as $needle) {
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 [true, ''];
}
}

return false;
return [false, $host];
}
}

0 comments on commit 172fd33

Please sign in to comment.