opnform/app/Http/Middleware/CustomDomainRestriction.php

60 lines
1.9 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Http\Middleware;
use App\Http\Requests\Workspace\CustomDomainRequest;
use App\Models\Forms\Form;
use App\Models\Workspace;
use Closure;
use Illuminate\Database\Eloquent\Builder;
2024-02-23 10:54:12 +00:00
use Illuminate\Http\Request;
class CustomDomainRestriction
{
2024-02-23 10:54:12 +00:00
public const CUSTOM_DOMAIN_HEADER = 'x-custom-domain';
/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next)
{
2024-02-23 10:54:12 +00:00
if (! $request->hasHeader(self::CUSTOM_DOMAIN_HEADER) || ! config('custom-domains.enabled')) {
return $next($request);
}
$customDomain = $request->header(self::CUSTOM_DOMAIN_HEADER);
2024-02-23 10:54:12 +00:00
if (! preg_match(CustomDomainRequest::CUSTOM_DOMAINS_REGEX, $customDomain)) {
return response()->json([
'success' => false,
'message' => 'Invalid domain',
2024-01-12 14:43:28 +00:00
'error' => 'invalid_domain',
], 420);
}
// Check if domain is different from current domain
$notionFormsDomain = parse_url(config('app.url'))['host'];
if ($customDomain == $notionFormsDomain) {
return $next($request);
}
// Check if domain is known
2024-02-23 10:54:12 +00:00
if (! $workspaces = Workspace::whereJsonContains('custom_domains', $customDomain)->get()) {
return response()->json([
'success' => false,
'message' => 'Unknown domain',
2024-01-12 14:43:28 +00:00
'error' => 'invalid_domain',
], 420);
}
$workspacesIds = $workspaces->pluck('id')->toArray();
Workspace::addGlobalScope('domain-restricted', function (Builder $builder) use ($workspacesIds) {
$builder->whereIn('id', $workspacesIds);
});
Form::addGlobalScope('domain-restricted', function (Builder $builder) use ($workspacesIds) {
$builder->whereIn('workspace_id', $workspacesIds);
});
return $next($request);
}
}