mirror of
https://github.com/archtechx/tenancy.git
synced 2025-12-13 01:34:02 +00:00
Central routes without Route::domain(), configurable tenant/central routes by default for domain/subdomain identification, allow accessing central routes in early identification for path & request data middleware (#3)
* Update url binding bootstrapper test * Fix parent::temporarySignedRoute() call * Add universal route tests for all identification types * Improve determineContextFromRequest() * Add setting `TenancyUrlGenerator::$prefixRouteNames` to true in TSP stub * Delete seemingly redundant test (making one route universal won't make all routes universal in any case) * Use collection syntax in ReregisterUniversalRoutes * Improve comments * Add domain identification MW annotation * Update condition in GloballyUsable * Set `tenancy.bootstrappers` instead of adding the bootstrappers using `tenancy.bootstrappers.x`, move test * Revert GloballyUsable condition change * Delete assigning bootstrappers to tenancy.bootstrappers.x * Exclude cache prefixing bootstrapper from the initial configuration * Fix test * Unset bypass parameter * Set static kernel identification-related properties in TestCase * Update bootstrapper name in annotation * Move unset() into a condition * Update TenancyUrlGenerator condition * Set static properties without instantiating Tenancy * Fix unsetting bypass parameter * formatting changes * add a comment * improve docblock * add docblock to TenancyUrlGenerator [ci skip] * docblock changes [ci skip] * Update TenancyUrlGenerator (rename variable, allow bypassing prefixing temporarySignedRoute name) * Improve determineContextFromRequest * Only return the new url generator instance when extending 'url' in UrlBindingBootstrapper * Check route's MW groups for the path ID MW * Remove extra imports from config * Rename MiddlewareContext to Context, add condition for skipping ID MW * Set only the needed bootstrappers in TestCase * Fix code style (php-cs-fixer) * Remove condition * Use correct return type * Fix PHPStan issue * Update comment * Check for tenant parameter instead of prefix * Update shouldBeSkipped condition for universal routes * Don't remove the 'universal' MW group after route re-registration, update test * Fix code style (php-cs-fixer) * Fix typo * Add test for mixing placement of access prevention and identification MW * Add test for mixing placement of access prevention and identification MW * Update docblock * Add setting the session and key resolvers in UrlBindingBootstrapper (required with LW file uploads) * Update stub * Update variable name in route reregistering action * Add trailing comma * Fix code style (php-cs-fixer) * Require routes using path identification to be flagged as tenant in order to be recognized as tenant routes * Add tenant flag while re-registering routes * Update determineContextFromRequest condition (wip) * Fix code style (php-cs-fixer) * Update the middleware context logic so that universal routes have to be flagged as tenant instead of just having ID MW * Update path identification condition * Fix re-registering the LW localized route (add 'tenant' MW) * Update docblock * Simplify LW route re-registration * Add comment * Update comment * Simplify determineContextFromRequest, add comment * Improve stub * Add skipRoute method + test * Fix typo * Update assets/TenancyServiceProvider.stub.php * Update src/Concerns/DealsWithEarlyIdentification.php * Fix typo Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com> * Improve comment * Update test structure * Restructure Fortify test * code style * Fix typo * Update ReregisterUniversalRoutes annotation * Only prefix route name if it wasn't already prefixed * Add todo@docs * Delete `Tenancy::$kernelAccessPreventionSkipped` and related logic * Delete test tenant cleanup * Test MW group unpacking, restructure and improve test * Test that tenancy isn't initialized after visiting a central route with the tenant parameter * Delete "in both central and tenant contexts" from test names * Test that re-registering works with controllers too * Set misc route properties during re-registering * Determine context instead of guessing, update universal route tests * Use randomly generated tenant ID instead of hardcoding `acme` * Remove setting route validators * Rename and update determine context method, add comments * Update ForgetTenantParameter annotation * Add comment * Delete comment, delete variable assignment * Update early domain identification test * Improve domain identification tests (test defaulting accurately) * Improve readability * Simplify domain early ID test * Use randomly generated tenant instead of 'acme' * Simplify request data ID test, use random tenant instead of 'acme' * Simplify defaulting domain identification test * Use RouteFacade alias for the Route facade, improve test code * Add defaulting to the request data and path ID tests * Merge path identification tenant parameter removal tests, clean up * Correct wording Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com> * Delete debugging things from UniversalRouteTest * Update annotation * Add `// Creates a matrix` * Improve comment wording * Add MiddlewareUsableWithUniversalRoutes, refactor code accordingly * Fix code style (php-cs-fixer) * Delete debugging leftovers * Delete unused import * Update universal route GloballyUsable condition * Don't implement the universal route interface in access prevention MW * Check if request host is in the central domains in domain ID MW * Test universal routes with domain identification without access prevent MW * Test that universal routes work only with identification MW implementing the universal route interface * Fix code style (php-cs-fixer) * Rename GloballyUsable to UsableWithEarlyIdentification * Fix annotation * Update requestHasTenant annotations * Update comment * Add `with()` comments * Add with() comments where missing * Rename interface, update/add comments * Rename exception, update its default message * Fix code style (php-cs-fixer) * Fix interface name * Delete redundant code from subdomain ID MW * Change domainOrSubdomain ID MW so that instead of passing the identification to other MWs, it happens in the domainOrSubdomain MW * Test domainOrSubdomain identification with universal routes * Fix code style (php-cs-fixer) * Rename universal routes interface * Fix code style (php-cs-fixer) * Try explaining forgetting the tenant parameter better * update interface name reference * uncouple example from query parameters * Update ForgetTenantParameter.php * Update ForgetTenantParameter annotation * Check both routeHasMiddleware and routeHasIdentificationMiddleware in the route MW detection test * Hardcode tenant subdomain * Delete redundant event listening code * Delete unused imports * Delete misuse of `tenancy()->getMiddlewareContext()` from conditions * Delete unused variable * Update comment * Correct request data identification test (defaulting) * Fix defaulting in path id test * Move default route context configuration in domian id test * Rename and update the tenant parameter test * Delete extra tenant parameter test * Use `tenant-domain.test` instead of `127.0.0.2` * Add `default_to_universal_routes` config key * Deal with defaulting to universal routes in the reregistering action * Update logic to make defaulting to universal routes possible * Test defaulting to universal routes * Fix code style (php-cs-fixer) * Delete extra tests * Delete "without access prevention" from datasets * Add defaulting to universal routes to datasets * Override universal flag by central/tenant flag * Add universal flag overriding test * Update "a route can be universal in both route modes" so that the name corresponds with the tested thing * Ignore the PHPStan error * Reset `InitializeTenancyByPath::$onFail` in PathIdentificationTest * Simplify expression * Use 'Tenancy (not) initialized.' in instead of `tenant()?->getTenantKey()` for better assertions * Properly test removing tenant parameter * Reset static properties in tests * Correct comments in EarlyIdentificationTest * Add comment * Add detail to annotation * Throw exception if payload isn't string or null in request data ID MW * Fix code style (php-cs-fixer) * Delete static `$kernelIdentificationSkipped` property, use `$request->attributes` instead * Use 'default_route_mode' instead of 'default_to_tenant/universal_routes' * Fix code style (php-cs-fixer) * Make path identification MW, tenantParameterName and tenantRouteNamePrefix configurable in ReregisterUniversalRoutes * Delete unused import * Add `$passTenantParameterToRoute` to TenancyUrlGenerator * Use `$passTenantParameterToRoute` in BootstrapperTest * Bypass tenant parameter passing * Improve TenancyUrlGenerator so that both ID methods work * Fix code style (php-cs-fixer) * Improve TenancyUrlGenerator readability * Add modifyBehavior() to TenancyUrlGenerator * Fix code style (php-cs-fixer) * Improve comment * Toggle route name prefixing in path/request data ID MW (route-level identification) * Fix code style (php-cs-fixer) * Add path identification MW config key, add `getTenantParameterName()` to ForgetTenantParameter * Fix code style (php-cs-fixer) * Fix modifyBehavior and routeBehaviorModificationBypassed * Add type to `$parameters` parameter * Split modifyBehavior into two methods, don't pass name and parameters by reference * Update UrlBindingBootstrapper annotation * Correct naming in tests (request data -> query string identification) * Add info to annotation * Pass arrays to the behavior modification methods instead of `mixed` * Fix default value of static property in Fortify bootstrapper * Fix code style (php-cs-fixer) * Correct annotation * Enable prefixing routes directly using path identification MW * Test re-registration of routes with path ID MW * Prefix names of routes directly using path ID MW * Fix code style (php-cs-fixer) * Add Livewire v3 integration example to TSP stub * Prefix route name only if it's not prefixed already * Rename ReregisterUniversalRoutes to ReregisterRoutesAsTenant * Fix code style (php-cs-fixer) * Improve ReregisterRoutesAsTenant * Add/update TenancyUrlGenerator docblocks * Update action name in comments/test names * Update reregister action annotation * Delete unused imports * Improve comments * Make method protected * Improve TenancyUrlGenerator code * Test bypass parameter removal * Fix comment * Update annotation * Improve shouldReregisterRoute * Fix typo, delete redundant comment * Improve skipRoute * Improve shouldBeSkipped * Add and test `$passTenantParameterToRoutes` * add a comment * Fix typo in comment * Pass array as $parameters in prepareRouteInputs * Make path_identification_middleware an array * Fix code style (php-cs-fixer) * Fix ReregisterRouteAsTenant * Move tenantParameterName and tenantRouteNamePrefix getting to PathIdentificationManager * Make PathIdentificationManager properties `Closure|null` * Fix code style (php-cs-fixer) * Fix PathIdentificationManager * Update comments * Use foreach for dataset definition * Extract repetitive inGlobalStack and routeHasMiddleware calls * Refactor PathIdentificationManager * Update TenancyUrlGenerator annotation * Add $skippedRoutes, refactor ReregisterRoutesAsTenant * Improve reregisterRoute * Update re-register action annotation * update test name * Make PathIdentificationManager methods static again, update comments * Add test comment * Update ForgetTenantParameter annotation * Improve route re-registration condition, add comment * Change "re-register" to "clone" * minor code improvements --------- Co-authored-by: lukinovec <lukinovec@gmail.com> Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com> Co-authored-by: PHP CS Fixer <phpcsfixer@example.com>
This commit is contained in:
parent
bd9bbe8b41
commit
1d0ca27bc8
53 changed files with 2668 additions and 271 deletions
|
|
@ -6,11 +6,15 @@ namespace Stancl\Tenancy\Middleware;
|
|||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification;
|
||||
use Stancl\Tenancy\Concerns\UsableWithUniversalRoutes;
|
||||
use Stancl\Tenancy\Resolvers\DomainTenantResolver;
|
||||
use Stancl\Tenancy\Tenancy;
|
||||
|
||||
class InitializeTenancyByDomain extends IdentificationMiddleware
|
||||
class InitializeTenancyByDomain extends IdentificationMiddleware implements UsableWithUniversalRoutes
|
||||
{
|
||||
use UsableWithEarlyIdentification;
|
||||
|
||||
public static ?Closure $onFail = null;
|
||||
|
||||
public function __construct(
|
||||
|
|
@ -22,6 +26,11 @@ class InitializeTenancyByDomain extends IdentificationMiddleware
|
|||
/** @return \Illuminate\Http\Response|mixed */
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
if ($this->shouldBeSkipped(tenancy()->getRoute($request))) {
|
||||
// Allow accessing central route in kernel identification
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if (in_array($request->getHost(), config('tenancy.central_domains', []), true)) {
|
||||
// Always bypass tenancy initialization when host is in central domains
|
||||
return $next($request);
|
||||
|
|
@ -33,4 +42,13 @@ class InitializeTenancyByDomain extends IdentificationMiddleware
|
|||
$request->getHost()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Domain identification request has a tenant if it's
|
||||
* not hitting a domain specifically defined as central in the config.
|
||||
*/
|
||||
public function requestHasTenant(Request $request): bool
|
||||
{
|
||||
return ! in_array($request->host(), config('tenancy.central_domains'));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,19 +5,52 @@ declare(strict_types=1);
|
|||
namespace Stancl\Tenancy\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Exception;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Str;
|
||||
use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification;
|
||||
|
||||
class InitializeTenancyByDomainOrSubdomain
|
||||
class InitializeTenancyByDomainOrSubdomain extends InitializeTenancyBySubdomain
|
||||
{
|
||||
use UsableWithEarlyIdentification;
|
||||
|
||||
/** @return \Illuminate\Http\Response|mixed */
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
if ($this->isSubdomain($request->getHost())) {
|
||||
return app(InitializeTenancyBySubdomain::class)->handle($request, $next);
|
||||
} else {
|
||||
return app(InitializeTenancyByDomain::class)->handle($request, $next);
|
||||
if ($this->shouldBeSkipped(tenancy()->getRoute($request))) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if (in_array($request->getHost(), config('tenancy.central_domains', []), true)) {
|
||||
// Always bypass tenancy initialization when host is in central domains
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
$domain = $request->getHost();
|
||||
|
||||
if ($this->isSubdomain($domain)) {
|
||||
$domain = $this->makeSubdomain($domain);
|
||||
|
||||
if (is_object($domain) && $domain instanceof Exception) {
|
||||
$onFail = static::$onFail ?? function ($e) {
|
||||
throw $e;
|
||||
};
|
||||
|
||||
return $onFail($domain, $request, $next);
|
||||
}
|
||||
|
||||
// If a Response instance was returned, we return it immediately.
|
||||
if (is_object($domain) && $domain instanceof Response) {
|
||||
return $domain;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->initializeTenancy(
|
||||
$request,
|
||||
$next,
|
||||
$domain
|
||||
);
|
||||
}
|
||||
|
||||
protected function isSubdomain(string $hostname): bool
|
||||
|
|
|
|||
|
|
@ -6,17 +6,25 @@ namespace Stancl\Tenancy\Middleware;
|
|||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Route;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification;
|
||||
use Stancl\Tenancy\Concerns\UsableWithUniversalRoutes;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\Events\InitializingTenancy;
|
||||
use Stancl\Tenancy\Exceptions\RouteIsMissingTenantParameterException;
|
||||
use Stancl\Tenancy\Resolvers\PathTenantResolver;
|
||||
use Stancl\Tenancy\RouteMode;
|
||||
use Stancl\Tenancy\Tenancy;
|
||||
use Stancl\Tenancy\TenancyUrlGenerator;
|
||||
|
||||
class InitializeTenancyByPath extends IdentificationMiddleware
|
||||
/**
|
||||
* @see Stancl\Tenancy\Listeners\ForgetTenantParameter
|
||||
*/
|
||||
class InitializeTenancyByPath extends IdentificationMiddleware implements UsableWithUniversalRoutes
|
||||
{
|
||||
use UsableWithEarlyIdentification;
|
||||
|
||||
public static ?Closure $onFail = null;
|
||||
|
||||
public function __construct(
|
||||
|
|
@ -28,12 +36,19 @@ class InitializeTenancyByPath extends IdentificationMiddleware
|
|||
/** @return \Illuminate\Http\Response|mixed */
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
$route = $this->route($request);
|
||||
$route = tenancy()->getRoute($request);
|
||||
|
||||
// Only initialize tenancy if tenant is the first parameter
|
||||
if ($this->shouldBeSkipped($route)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// Used with *route-level* identification, takes precedence over what may have been configured for global stack middleware
|
||||
TenancyUrlGenerator::$prefixRouteNames = true;
|
||||
|
||||
// Only initialize tenancy if the route has the tenant parameter.
|
||||
// We don't want to initialize tenancy if the tenant is
|
||||
// simply injected into some route controller action.
|
||||
if ($route->parameterNames()[0] === PathTenantResolver::tenantParameterName()) {
|
||||
if (in_array(PathTenantResolver::tenantParameterName(), $route->parameterNames())) {
|
||||
$this->setDefaultTenantForRouteParametersWhenInitializingTenancy();
|
||||
|
||||
return $this->initializeTenancy(
|
||||
|
|
@ -46,25 +61,6 @@ class InitializeTenancyByPath extends IdentificationMiddleware
|
|||
}
|
||||
}
|
||||
|
||||
protected function route(Request $request): Route
|
||||
{
|
||||
/** @var ?Route $route */
|
||||
$route = $request->route();
|
||||
|
||||
if (! $route) {
|
||||
// Create a fake $route instance that has enough information for this middleware's needs
|
||||
$route = new Route($request->method(), $request->getUri(), []);
|
||||
/**
|
||||
* getPathInfo() returns the path except the root domain.
|
||||
* We fetch the first parameter because tenant parameter is *always* first.
|
||||
*/
|
||||
$route->parameters[PathTenantResolver::tenantParameterName()] = explode('/', ltrim($request->getPathInfo(), '/'))[0];
|
||||
$route->parameterNames[] = PathTenantResolver::tenantParameterName();
|
||||
}
|
||||
|
||||
return $route;
|
||||
}
|
||||
|
||||
protected function setDefaultTenantForRouteParametersWhenInitializingTenancy(): void
|
||||
{
|
||||
Event::listen(InitializingTenancy::class, function (InitializingTenancy $event) {
|
||||
|
|
@ -76,4 +72,19 @@ class InitializeTenancyByPath extends IdentificationMiddleware
|
|||
]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Path identification request has a tenant if the middleware context is tenant.
|
||||
*
|
||||
* With path identification, we can just check the MW context because we're re-registering the universal routes,
|
||||
* and the routes are flagged with the 'tenant' MW group (= their MW context is tenant).
|
||||
*
|
||||
* With other identification middleware, we have to determine the context differently because we only have one
|
||||
* truly universal route available ('truly universal' because with path identification, applying 'universal' to a route just means that
|
||||
* it should get re-registered, whereas with other ID MW, it means that the route you apply the 'universal' flag to will be accessible in both contexts).
|
||||
*/
|
||||
public function requestHasTenant(Request $request): bool
|
||||
{
|
||||
return tenancy()->getMiddlewareContext(tenancy()->getRoute($request)) === RouteMode::TENANT;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,11 +6,17 @@ namespace Stancl\Tenancy\Middleware;
|
|||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification;
|
||||
use Stancl\Tenancy\Concerns\UsableWithUniversalRoutes;
|
||||
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByRequestDataException;
|
||||
use Stancl\Tenancy\Resolvers\RequestDataTenantResolver;
|
||||
use Stancl\Tenancy\Tenancy;
|
||||
use Stancl\Tenancy\TenancyUrlGenerator;
|
||||
|
||||
class InitializeTenancyByRequestData extends IdentificationMiddleware
|
||||
class InitializeTenancyByRequestData extends IdentificationMiddleware implements UsableWithUniversalRoutes
|
||||
{
|
||||
use UsableWithEarlyIdentification;
|
||||
|
||||
public static string $header = 'X-Tenant';
|
||||
public static string $cookie = 'X-Tenant';
|
||||
public static string $queryParameter = 'tenant';
|
||||
|
|
@ -25,6 +31,14 @@ class InitializeTenancyByRequestData extends IdentificationMiddleware
|
|||
/** @return \Illuminate\Http\Response|mixed */
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
if ($this->shouldBeSkipped(tenancy()->getRoute($request))) {
|
||||
// Allow accessing central route in kernel identification
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// Used with *route-level* identification, takes precedence over what may have been configured for global stack middleware
|
||||
TenancyUrlGenerator::$prefixRouteNames = false;
|
||||
|
||||
if ($request->method() !== 'OPTIONS') {
|
||||
return $this->initializeTenancy($request, $next, $this->getPayload($request));
|
||||
}
|
||||
|
|
@ -32,19 +46,30 @@ class InitializeTenancyByRequestData extends IdentificationMiddleware
|
|||
return $next($request);
|
||||
}
|
||||
|
||||
protected function getPayload(Request $request): ?string
|
||||
protected function getPayload(Request $request): string|null
|
||||
{
|
||||
$payload = null;
|
||||
|
||||
if (static::$header && $request->hasHeader(static::$header)) {
|
||||
$payload = $request->header(static::$header);
|
||||
} elseif (static::$queryParameter && $request->has(static::$queryParameter)) {
|
||||
$payload = $request->get(static::$queryParameter);
|
||||
} elseif (static::$cookie && $request->hasCookie(static::$cookie)) {
|
||||
$payload = $request->cookie(static::$cookie);
|
||||
} else {
|
||||
$payload = null;
|
||||
}
|
||||
|
||||
/** @var ?string $payload */
|
||||
return $payload;
|
||||
if (is_string($payload) || is_null($payload)) {
|
||||
return $payload;
|
||||
}
|
||||
|
||||
throw new TenantCouldNotBeIdentifiedByRequestDataException($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the request has the tenant payload.
|
||||
*/
|
||||
public function requestHasTenant(Request $request): bool
|
||||
{
|
||||
return (bool) $this->getPayload($request);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,10 +9,13 @@ use Exception;
|
|||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Str;
|
||||
use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification;
|
||||
use Stancl\Tenancy\Exceptions\NotASubdomainException;
|
||||
|
||||
class InitializeTenancyBySubdomain extends InitializeTenancyByDomain
|
||||
{
|
||||
use UsableWithEarlyIdentification;
|
||||
|
||||
/**
|
||||
* The index of the subdomain fragment in the hostname
|
||||
* split by `.`. 0 for first fragment, 1 if you prefix
|
||||
|
|
@ -27,6 +30,11 @@ class InitializeTenancyBySubdomain extends InitializeTenancyByDomain
|
|||
/** @return Response|mixed */
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
if ($this->shouldBeSkipped(tenancy()->getRoute($request))) {
|
||||
// Allow accessing central route in kernel identification
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if (in_array($request->getHost(), config('tenancy.central_domains', []), true)) {
|
||||
// Always bypass tenancy initialization when host is in central domains
|
||||
return $next($request);
|
||||
|
|
|
|||
|
|
@ -7,11 +7,23 @@ namespace Stancl\Tenancy\Middleware;
|
|||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Route;
|
||||
use Illuminate\Support\Facades\Route as Router;
|
||||
use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification;
|
||||
use Stancl\Tenancy\Context;
|
||||
use Stancl\Tenancy\RouteMode;
|
||||
|
||||
// todo come up with a better name
|
||||
/**
|
||||
* todo come up with a better name.
|
||||
*
|
||||
* Prevents accessing central domains in the tenant context/tenant domains in the central context.
|
||||
* The access isn't prevented if the request is trying to access a route flagged as 'universal',
|
||||
* or if this middleware should be skipped.
|
||||
*
|
||||
* @see UsableWithEarlyIdentification – more info about the skipping part
|
||||
*/
|
||||
class PreventAccessFromUnwantedDomains
|
||||
{
|
||||
use UsableWithEarlyIdentification;
|
||||
|
||||
/**
|
||||
* Set this property if you want to customize the on-fail behavior.
|
||||
*/
|
||||
|
|
@ -20,14 +32,14 @@ class PreventAccessFromUnwantedDomains
|
|||
/** @return \Illuminate\Http\Response|mixed */
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
/** @var Route $route */
|
||||
$route = $request->route();
|
||||
$route = tenancy()->getRoute($request);
|
||||
$routeIsUniversal = tenancy()->routeHasMiddleware($route, 'universal') || config('tenancy.default_route_mode') === RouteMode::UNIVERSAL;
|
||||
|
||||
if ($this->routeHasMiddleware($route, 'universal')) {
|
||||
if ($this->shouldBeSkipped($route) || $routeIsUniversal) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if (in_array($request->getHost(), config('tenancy.central_domains'), true)) {
|
||||
if ($this->accessingTenantRouteFromCentralDomain($request, $route) || $this->accessingCentralRouteFromTenantDomain($request, $route)) {
|
||||
$abortRequest = static::$abortRequest ?? function () {
|
||||
abort(404);
|
||||
};
|
||||
|
|
@ -38,24 +50,23 @@ class PreventAccessFromUnwantedDomains
|
|||
return $next($request);
|
||||
}
|
||||
|
||||
protected function routeHasMiddleware(Route $route, string $middleware): bool
|
||||
protected function accessingTenantRouteFromCentralDomain(Request $request, Route $route): bool
|
||||
{
|
||||
/** @var array $routeMiddleware */
|
||||
$routeMiddleware = $route->middleware();
|
||||
return tenancy()->getMiddlewareContext($route) === RouteMode::TENANT // Current route's middleware context is tenant
|
||||
&& $this->isCentralDomain($request); // The request comes from a domain that IS present in the configured `tenancy.central_domains`
|
||||
}
|
||||
|
||||
if (in_array($middleware, $routeMiddleware, true)) {
|
||||
return true;
|
||||
}
|
||||
protected function accessingCentralRouteFromTenantDomain(Request $request, Route $route): bool
|
||||
{
|
||||
return tenancy()->getMiddlewareContext($route) === RouteMode::CENTRAL // Current route's middleware context is central
|
||||
&& ! $this->isCentralDomain($request); // The request comes from a domain that ISN'T present in the configured `tenancy.central_domains`
|
||||
}
|
||||
|
||||
// Loop one level deep and check if the route's middleware
|
||||
// groups have the searched middleware group inside them
|
||||
$middlewareGroups = Router::getMiddlewareGroups();
|
||||
foreach ($route->gatherMiddleware() as $inner) {
|
||||
if (! $inner instanceof Closure && isset($middlewareGroups[$inner]) && in_array($middleware, $middlewareGroups[$inner], true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
/**
|
||||
* Check if the request's host name is present in the configured `tenancy.central_domains`.
|
||||
*/
|
||||
protected function isCentralDomain(Request $request): bool
|
||||
{
|
||||
return in_array($request->getHost(), config('tenancy.central_domains'), true);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue