mailwolt/app/Http/Middleware/ValidateHost.php

45 lines
1.2 KiB
PHP

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class ValidateHost
{
public function handle(Request $request, Closure $next): Response
{
$host = $request->getHost();
if ($this->isAllowed($host)) {
return $next($request);
}
abort(404);
}
private function isAllowed(string $host): bool
{
// Always allow localhost and loopback (health checks, artisan, etc.)
if (in_array($host, ['localhost', '127.0.0.1', '::1'], true)) {
return true;
}
$base = config('mailwolt.domain.base');
$uiSub = config('mailwolt.domain.ui');
$mtaSub = config('mailwolt.domain.mail');
$wmHost = config('mailwolt.domain.webmail_host');
$allowed = array_filter([
$wmHost,
$uiSub && $base ? "{$uiSub}.{$base}" : null,
$mtaSub && $base ? "{$mtaSub}.{$base}" : null,
// APP_HOST as fallback (e.g. during setup before domains are saved)
parse_url(config('app.url'), PHP_URL_HOST) ?: null,
]);
return in_array($host, $allowed, true);
}
}