1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-13 05:24:03 +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:
Abrar Ahmad 2023-08-03 03:23:26 +05:00 committed by GitHub
parent bd9bbe8b41
commit 1d0ca27bc8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
53 changed files with 2668 additions and 271 deletions

View file

@ -0,0 +1,144 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Concerns;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Illuminate\Routing\Router;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Route as RouteFacade;
use Stancl\Tenancy\Context;
use Stancl\Tenancy\RouteMode;
// todo1 Name maybe DealsWithMiddlewareContexts?
trait DealsWithEarlyIdentification
{
/**
* Get route's middleware context (tenant or central).
* The context is determined by the route's middleware.
*
* If the route has the 'central' middleware, the context is central.
* If the route has the 'tenant' middleware, or any tenancy identification middleware, the context is tenant.
*
* If the route doesn't have any of the mentioned middleware,
* the context is determined by the `tenancy.default_route_mode` config.
*/
public static function getMiddlewareContext(Route $route): RouteMode
{
if (static::routeHasMiddleware($route, 'central')) {
return RouteMode::CENTRAL;
}
$defaultRouteMode = config('tenancy.default_route_mode');
$routeIsUniversal = $defaultRouteMode === RouteMode::UNIVERSAL || static::routeHasMiddleware($route, 'universal');
// If a route has identification middleware AND the route isn't universal, don't consider the context tenant
if (static::routeHasMiddleware($route, 'tenant') || static::routeHasIdentificationMiddleware($route) && ! $routeIsUniversal) {
return RouteMode::TENANT;
}
return $defaultRouteMode;
}
/**
* Get middleware of the passed route (without controller middleware and middleware from the global stack).
*
* First, get the surface-level route middleware (`$route->middleware()`).
* The surface-level middleware could contain middleware groups,
* and to accurately get all the specific middleware, we need to unpack them.
* The unpacked middleware groups could also have middleware groups inside them,
* so we further unpack these, three times.
*
* For example, a route has a 'surface' middleware group.
* The 'surface' group has a 'first-level' group, and that group has a 'second-level' group (three middleware group layers).
* The 'second-level' group has a specific middleware (e.g. SomeMiddleware).
* Using the getRouteMiddleware method on that route will get you all the middleware the route has, including SomeMiddleware.
*
* Note that the unpacking doesn't go further than three layers if 'second-level' had 'third-level' that would have ThirdLevelMiddleware,
* the middleware returned by this method won't include ThirdLevelMiddleware because the 'third-level' group won't get unpacked.
*/
public static function getRouteMiddleware(Route $route): array
{
$routeMiddleware = $route->middleware();
$middlewareGroups = RouteFacade::getMiddlewareGroups();
$unpackGroupMiddleware = function (array $middleware) use ($middlewareGroups) {
$innerMiddleware = [];
foreach ($middleware as $inner) {
if (! $inner instanceof Closure && isset($middlewareGroups[$inner])) {
$innerMiddleware = Arr::wrap($middlewareGroups[$inner]);
}
}
return $innerMiddleware;
};
return array_unique(array_merge(
$routeMiddleware,
$firstLevelUnpackedGroupMiddleware = $unpackGroupMiddleware($routeMiddleware),
$thirdLevelUnpackedGroupMiddleware = $unpackGroupMiddleware($firstLevelUnpackedGroupMiddleware),
$unpackGroupMiddleware($thirdLevelUnpackedGroupMiddleware)
));
}
/**
* Check if the passed route has the passed middleware
* three layers deep explained in the annotation of getRouteMiddleware().
*/
public static function routeHasMiddleware(Route $route, string $middleware): bool
{
return in_array($middleware, static::getRouteMiddleware($route));
}
/**
* Check if a route has identification middleware.
*/
public static function routeHasIdentificationMiddleware(Route $route): bool
{
foreach (static::getRouteMiddleware($route) as $middleware) {
if (in_array($middleware, static::middleware())) {
return true;
}
}
return false;
}
/**
* Check if a route uses domain identification.
*/
public static function routeHasDomainIdentificationMiddleware(Route $route): bool
{
$routeMiddleware = static::getRouteMiddleware($route);
foreach (config('tenancy.identification.domain_identification_middleware') as $middleware) {
if (in_array($middleware, $routeMiddleware)) {
return true;
}
}
return false;
}
/**
* Obtain route from the passed request.
* If the route isn't directly available on the request,
* find the route that matches the passed request.
*/
public function getRoute(Request $request): Route
{
/** @var ?Route $route */
$route = $request->route();
if (! $route) {
/** @var Router $router */
$router = app(Router::class);
$route = $router->getRoutes()->match($request);
}
return $route;
}
}

View file

@ -18,7 +18,7 @@ trait DealsWithTenantSymlinks
*
* @return Collection<string, string>
*/
protected static function possibleTenantSymlinks(Tenant $tenant): Collection
protected function possibleTenantSymlinks(Tenant $tenant): Collection
{
$diskUrls = config('tenancy.filesystem.url_override');
$disks = config('tenancy.filesystem.root_override');
@ -41,7 +41,7 @@ trait DealsWithTenantSymlinks
}
/** Determine if the provided path is an existing symlink. */
protected static function symlinkExists(string $link): bool
protected function symlinkExists(string $link): bool
{
return file_exists($link) && is_link($link);
}

View file

@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Concerns;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Stancl\Tenancy\Context;
use Stancl\Tenancy\Exceptions\MiddlewareNotUsableWithUniversalRoutesException;
use Stancl\Tenancy\Middleware\IdentificationMiddleware;
use Stancl\Tenancy\Middleware\PreventAccessFromUnwantedDomains;
use Stancl\Tenancy\RouteMode;
/**
* This trait provides methods that check if a middleware's execution should be skipped.
* This is primarily used to ensure that kernel identification is skipped when the route has
* identification middleware (= route-level identification is prioritized over kernel identification).
*
* When using kernel domain identification, you'll most likely also use the PreventAccessFromUnwantedDomains middleware in the global stack.
* PreventAccessFromUnwantedDomains isn't an identification middleware, but we have to skip it too,
* e.g. when using the MW in the global stack and at the same time, we're using route-level identification.
*
* You need to use this trait directly on each identification middleware it can't be used in a base class that's extended.
* The inGlobalStack() method checks for the specific middleware the trait is used on (`static::class`).
*/
trait UsableWithEarlyIdentification
{
/**
* Skip middleware if the route is universal and uses path identification or if the route is universal and the context should be central.
* Universal routes using path identification should get re-registered using ReregisterRoutesAsTenant.
*
* @see \Stancl\Tenancy\Actions\CloneRoutesAsTenant
*/
protected function shouldBeSkipped(Route $route): bool
{
$routeMiddleware = tenancy()->getRouteMiddleware($route);
$universalFlagUsed = in_array('universal', $routeMiddleware);
$defaultToUniversalRoutes = config('tenancy.default_route_mode') === RouteMode::UNIVERSAL;
// Route is universal only if it doesn't have the central/tenant flag
$routeIsUniversal = ($universalFlagUsed || $defaultToUniversalRoutes) &&
! (in_array('central', $routeMiddleware) || in_array('tenant', $routeMiddleware));
if ($routeIsUniversal && $this instanceof IdentificationMiddleware) {
/** @phpstan-ignore-next-line */
throw_unless($this instanceof UsableWithUniversalRoutes, MiddlewareNotUsableWithUniversalRoutesException::class);
return $this->determineUniversalRouteContextFromRequest(request()) === Context::CENTRAL;
}
// If the middleware is not in the global stack (= it's used directly on the route)
// And the route isn't universal, don't skip it
if (! static::inGlobalStack()) {
return false;
}
// Now that we're sure the MW isn't used in the global MW stack, we determine whether to skip it
if ($this instanceof PreventAccessFromUnwantedDomains) {
// Skip access prevention if the route directly uses a non-domain identification middleware
return tenancy()->routeHasIdentificationMiddleware($route) && ! tenancy()->routeHasDomainIdentificationMiddleware($route);
}
return $this->shouldIdentificationMiddlewareBeSkipped($route);
}
protected function determineUniversalRouteContextFromRequest(Request $request): Context
{
$route = tenancy()->getRoute($request);
// Check if this is the identification middleware the route should be using
// Route-level identification middleware is prioritized
$middlewareUsed = tenancy()->routeHasMiddleware($route, static::class) || ! tenancy()->routeHasIdentificationMiddleware($route) && static::inGlobalStack();
/** @var UsableWithUniversalRoutes $this */
return $middlewareUsed && $this->requestHasTenant($request) ? Context::TENANT : Context::CENTRAL;
}
protected function shouldIdentificationMiddlewareBeSkipped(Route $route): bool
{
if (! static::inGlobalStack()) {
return false;
}
$request = app(Request::class);
if (! $request->attributes->get('_tenancy_kernel_identification_skipped')) {
if (
// Skip identification if the current route is central
// The route is central if defaulting is set to central and the route isn't flagged as tenant or it doesn't have identification middleware
tenancy()->getMiddlewareContext($route) === RouteMode::CENTRAL
// Don't skip identification if the central route is considered universal
&& (config('tenancy.default_route_mode') !== RouteMode::UNIVERSAL || ! tenancy()->routeHasMiddleware($route, 'universal'))
) {
return true;
}
// Skip kernel identification if the route uses route-level identification
if (tenancy()->routeHasIdentificationMiddleware($route)) {
// Remember that it was attempted to identify a tenant using kernel identification
// By making the $kernelIdentificationSkipped property of the current Tenancy instance true
// So that the next identification middleware gets executed (= route-level identification MW doesn't get skipped)
$request->attributes->set('_tenancy_kernel_identification_skipped', true);
// Skip kernel identification so that route-level identification middleware can get used
return true;
}
}
return false;
}
public static function inGlobalStack(): bool
{
return app(Kernel::class)->hasMiddleware(static::class);
}
}

View file

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Concerns;
use Illuminate\Http\Request;
/**
* Identification middleware has to implement this in order to make universal routes work with it,.
*/
interface UsableWithUniversalRoutes
{
/**
* Determine if the tenant is present in the incoming request.
*
* Because universal routes can be in any context (central/tenant),
* we use this to determine the context. We can't just check for
* the route's middleware to determine the route's context.
*
* For example, route '/foo' has the 'universal' and InitializeTenancyByRequestData middleware.
* When visiting the route, we should determine the context by the presence of the tenant payload.
* The context is tenant if the tenant parameter is present (e.g. '?tenant=foo'), otherwise the context is central.
*/
public function requestHasTenant(Request $request): bool;
}