1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-12 09:34:04 +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

@ -2,83 +2,214 @@
declare(strict_types=1);
use Illuminate\Support\Arr;
use Illuminate\Routing\Route;
use Stancl\Tenancy\RouteMode;
use Stancl\Tenancy\Tests\Etc\Tenant;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Route;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomainOrSubdomain;
use Illuminate\Support\Facades\Route as RouteFacade;
use Stancl\Tenancy\Actions\CloneRoutesAsTenant;
use Stancl\Tenancy\Middleware\InitializeTenancyByPath;
use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
use Stancl\Tenancy\Middleware\InitializeTenancyBySubdomain;
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData;
use Stancl\Tenancy\Tests\Etc\EarlyIdentification\Models\Post;
use Stancl\Tenancy\Middleware\PreventAccessFromUnwantedDomains;
use Stancl\Tenancy\Tests\Etc\EarlyIdentification\Controller;
use Stancl\Tenancy\Tests\Etc\Tenant;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomainOrSubdomain;
use Stancl\Tenancy\Tests\Etc\EarlyIdentification\ControllerWithMiddleware;
use Stancl\Tenancy\Tests\Etc\EarlyIdentification\ControllerWithRouteMiddleware;
beforeEach(function () {
config()->set([
'tenancy.token' => 'central-abc123',
'tenancy.test_service_token' => 'token:central',
]);
Event::listen(TenancyInitialized::class, function (TenancyInitialized $event) {
config()->set([
'tenancy.token' => $event->tenancy->tenant->getTenantKey() . '-abc123',
'tenancy.test_service_token' => 'token:' . $event->tenancy->tenant->getTenantKey(),
]);
});
});
test('early identification works with path identification', function () {
app(Kernel::class)->pushMiddleware(InitializeTenancyByPath::class);
test('early identification works with path identification', function (bool $useKernelIdentification, RouteMode $defaultRouteMode) {
$identificationMiddleware = InitializeTenancyByPath::class;
Route::group([
'prefix' => '/{tenant}',
], function () {
Route::get('/foo', [Controller::class, 'index'])->name('foo');
});
Tenant::create([
'id' => 'acme',
]);
$response = pest()->get('/acme/foo')->assertOk();
assertTenancyInitializedInEarlyIdentificationRequest($response->getContent());
// check if default parameter feature is working fine by asserting that the route WITHOUT the tenant parameter
// matches the route WITH the tenant parameter
expect(route('foo'))->toBe(route('foo', ['tenant' => 'acme']));
});
test('early identification works with request data identification', function (string $type) {
app(Kernel::class)->pushMiddleware(InitializeTenancyByRequestData::class);
Route::get('/foo', [Controller::class, 'index'])->name('foo');
$tenant = Tenant::create([
'id' => 'acme',
]);
if ($type === 'header') {
$response = pest()->get('/foo', ['X-Tenant' => $tenant->id])->assertOk();
} elseif ($type === 'queryParameter') {
$response = pest()->get("/foo?tenant=$tenant->id")->assertOk();
if ($useKernelIdentification) {
$controller = ControllerWithMiddleware::class;
app(Kernel::class)->pushMiddleware($identificationMiddleware);
} else {
$controller = ControllerWithRouteMiddleware::class;
RouteFacade::middlewareGroup('tenant', [$identificationMiddleware]);
}
assertTenancyInitializedInEarlyIdentificationRequest($response->getContent());
config(['tenancy.bootstrappers' => [DatabaseTenancyBootstrapper::class]]);
config(['tenancy.default_route_mode' => $defaultRouteMode]);
// Migrate users and comments tables on central connection
pest()->artisan('migrate', [
'--path' => __DIR__ . '/Etc/EarlyIdentification/path/migrations',
'--realpath' => true,
])->assertExitCode(0);
$centralPost = Post::create(['title' => 'central post']);
$centralComment = $centralPost->comments()->create(['comment' => 'central comment']);
/**
* @var Route $tenantRoute
* @var Route $commentTenantRoute
*
* The Route instance is always assigned to this variable
*/
$tenantRoute = null;
$commentTenantRoute = null;
$tenantRouteMiddleware = ['tenant', 'web'];
// If defaulting to tenant routes
// With kernel identification, we make the tenant route have no MW (except 'web')
// And with route-level identification, we make the route have only the identification middleware + 'web'
if ($defaultRouteMode === RouteMode::TENANT) {
$tenantRouteMiddleware = $useKernelIdentification ? ['web'] : [$identificationMiddleware, 'web'];
}
RouteFacade::group([
'middleware' => $tenantRouteMiddleware,
'prefix' => '/{tenant}',
], function () use ($controller, &$tenantRoute, &$commentTenantRoute) {
$tenantRoute = RouteFacade::get('/tenant-route', [$controller, 'index'])->name('tenant-route');
$commentTenantRoute = RouteFacade::get('/{post}/comment/{comment}/edit', [$controller, 'computePost'])->name('comment-tenant-route');
});
RouteFacade::group([
'middleware' => ['central', 'web'],
], function () use ($controller) {
RouteFacade::get('/central/home', function () {
return 'central-home';
});
RouteFacade::get('/{post}/edit', [$controller, 'computePost']);
RouteFacade::get('/{post}/comment/{comment}/edit', [$controller, 'computePost']);
});
$tenant = Tenant::create(['tenancy_db_name' => pest()->randomString()]);
// Migrate users and comments tables on tenant connection
pest()->artisan('tenants:migrate', [
'--path' => __DIR__ . '/Etc/EarlyIdentification/path/migrations',
'--realpath' => true,
])->assertExitCode(0);
tenancy()->initialize($tenant);
$tenantPost = Post::create(['title' => 'tenant post']);
$tenantComment = $tenantPost->comments()->create(['comment' => 'tenant comment']);
tenancy()->end();
// Central routes are accessible and tenancy doesn't get initialized in early identification when the routes get accessed
pest()->get('/central/home')->assertOk();
pest()->get("/{$centralPost->id}/edit")->assertOk()->assertContent('central post');
pest()->get("/{$centralPost->id}/comment/{$centralComment->id}/edit")->assertOk()->assertContent($centralPost->title . '-' . $centralComment->comment);
assertTenancyInitializedInEarlyIdentificationRequest(false);
// Tenant routes are accessible and tenancy gets initialized in early identification when the routes get accessed
pest()->get("/{$tenant->id}/{$tenantPost->id}/comment/{$tenantComment->id}/edit")
->assertOk()
->assertContent($tenantPost->title . '-' . $tenantComment->comment);
assertTenancyInitializedInEarlyIdentificationRequest();
// Tenant routes that use path identification receive the tenant parameter automatically
// (setDefaultTenantForRouteParametersWhenInitializingTenancy() in Stancl\Tenancy\Middleware\InitializeTenancyByPath)
expect(route('tenant-route'))->toBe(route('tenant-route', ['tenant' => $tenant->getTenantKey()]));
})->with([
'using request header parameter' => 'header',
'using request query parameter' => 'queryParameter'
'route-level identification' => false,
'kernel identification' => true,
// Creates a matrix (multiple with())
])->with([
'default to tenant routes' => RouteMode::TENANT,
'default to central routes' => RouteMode::CENTRAL,
]);
// The name of this test is suffixed by the dataset — domain / subdomain / domainOrSubdomain identification
test('early identification works', function (string $middleware, string $domain, string $url) {
app(Kernel::class)->pushMiddleware($middleware);
test('early identification works with request data identification', function (string $type, bool $useKernelIdentification, RouteMode $defaultRouteMode) {
$identificationMiddleware = InitializeTenancyByRequestData::class;
if ($useKernelIdentification) {
$controller = ControllerWithMiddleware::class;
app(Kernel::class)->pushMiddleware($identificationMiddleware);
} else {
$controller = ControllerWithRouteMiddleware::class;
RouteFacade::middlewareGroup('tenant', [$identificationMiddleware]);
}
config(['tenancy.default_route_mode' => $defaultRouteMode]);
$tenantRouteMiddleware = 'tenant';
// If defaulting to tenant routes
// With kernel identification, we make the tenant route have no MW
// And with route-level identification, we make the route have only the identification middleware
if ($defaultRouteMode === RouteMode::TENANT) {
$tenantRouteMiddleware = $useKernelIdentification ? null : $identificationMiddleware;
}
RouteFacade::get('/tenant-route', [$controller, 'index'])->middleware($tenantRouteMiddleware);
RouteFacade::get('/central-route', fn () => 'central route')->middleware($defaultRouteMode === RouteMode::TENANT ? 'central' : null);
$tenantKey = Tenant::create()->getTenantKey();
// Central route is accessible for every $type
pest()->get('/central-route')->assertOk()->assertContent('central route');
$response = match ($type) {
'header' => pest()->get('/tenant-route', ['X-Tenant' => $tenantKey]),
'queryParameter' => pest()->get("/tenant-route?tenant={$tenantKey}"),
'cookie' => pest()->withUnencryptedCookie('X-Tenant', $tenantKey)
->get('/tenant-route'),
};
$response->assertOk()->assertSee('token:' . $tenantKey);
})->with([
'using request header parameter' => 'header',
'using request query parameter' => 'queryParameter',
'using request cookie parameter' => 'cookie',
// Creates a matrix (multiple with())
])->with([
'route-level identification' => false,
'kernel identification' => true,
])->with([
'default to tenant routes' => RouteMode::TENANT,
'default to central routes' => RouteMode::CENTRAL,
]);
test('early identification works with domain identification', function (string $middleware, string $domain, bool $useKernelIdentification, RouteMode $defaultRouteMode) {
config(['tenancy.tenant_model' => Tenant::class]);
config(['tenancy.default_route_mode' => $defaultRouteMode]);
Route::get('/foo', [Controller::class, 'index'])
->middleware(PreventAccessFromUnwantedDomains::class)
->name('foo');
if ($useKernelIdentification) {
$controller = ControllerWithMiddleware::class;
app(Kernel::class)->pushMiddleware($middleware);
app(Kernel::class)->pushMiddleware(PreventAccessFromUnwantedDomains::class);
} else {
$controller = ControllerWithRouteMiddleware::class;
RouteFacade::middlewareGroup('tenant', [$middleware, PreventAccessFromUnwantedDomains::class]);
}
// Tenant route
$tenantRoute = RouteFacade::get('/tenant-route', [$controller, 'index']);
// Central route
$centralRoute = RouteFacade::get('/central-route', function () {
return 'central route';
});
$defaultToTenantRoutes = $defaultRouteMode === RouteMode::TENANT;
// Test defaulting to route mode (central/tenant context)
if ($useKernelIdentification) {
$routeThatShouldReceiveMiddleware = $defaultToTenantRoutes ? $centralRoute : $tenantRoute;
$routeThatShouldReceiveMiddleware->middleware($defaultToTenantRoutes ? 'central' : 'tenant');
} elseif (! $defaultToTenantRoutes) {
$tenantRoute->middleware('tenant');
}
$tenant = Tenant::create();
@ -86,19 +217,173 @@ test('early identification works', function (string $middleware, string $domain,
'domain' => $domain,
]);
$response = pest()->get($url)->assertOk();
if ($domain === 'foo') {
$domain = 'foo.localhost';
}
assertTenancyInitializedInEarlyIdentificationRequest($response->getContent());
pest()->get('http://localhost/central-route')->assertOk()->assertContent('central route'); // Central route is accessible
$response = pest()->get("http://{$domain}/tenant-route");
if ($defaultToTenantRoutes === $useKernelIdentification || $useKernelIdentification) {
$response->assertOk();
assertTenancyInitializedInEarlyIdentificationRequest();
} elseif (! $defaultToTenantRoutes) {
$response->assertNotFound();
assertTenancyInitializedInEarlyIdentificationRequest(false);
}
// Expect tenancy is initialized (or not) for the right tenant at the tenant route
expect($response->getContent())->toBe('token:' . (tenant()?->getTenantKey() ?? 'central'));
})->with([
'domain identification' => ['middleware' => InitializeTenancyByDomain::class, 'domain' => 'foo.test', 'url' => 'http://foo.test/foo'],
'subdomain identification' => ['middleware' => InitializeTenancyBySubdomain::class, 'domain' => 'foo', 'url' => 'http://foo.localhost/foo'],
'domainOrSubdomain identification using domain' => ['middleware' => InitializeTenancyByDomainOrSubdomain::class, 'domain' => 'foo.test', 'url' => 'http://foo.test/foo'],
'domainOrSubdomain identification using subdomain' => ['middleware' => InitializeTenancyByDomainOrSubdomain::class, 'domain' => 'foo', 'url' => 'http://foo.localhost/foo'],
'domain identification' => ['middleware' => InitializeTenancyByDomain::class, 'domain' => 'foo.test'],
'subdomain identification' => ['middleware' => InitializeTenancyBySubdomain::class, 'domain' => 'foo'],
'domainOrSubdomain identification using domain' => ['middleware' => InitializeTenancyByDomainOrSubdomain::class, 'domain' => 'foo.test'],
'domainOrSubdomain identification using subdomain' => ['middleware' => InitializeTenancyByDomainOrSubdomain::class, 'domain' => 'foo'],
// Creates a matrix (multiple with())
])->with([
'route-level identification' => false,
'kernel identification' => true,
])->with([
'default to tenant routes' => RouteMode::TENANT,
'default to central routes' => RouteMode::CENTRAL,
]);
function assertTenancyInitializedInEarlyIdentificationRequest(string|false $string): void
test('the tenant parameter is only removed from tenant routes when using path identification', function (bool $kernelIdentification, bool $pathIdentification) {
if ($kernelIdentification) {
$middleware = $pathIdentification ? InitializeTenancyByPath::class : InitializeTenancyByDomain::class;
app(Kernel::class)->pushMiddleware($middleware);
RouteFacade::get('/{tenant}/central-route', [ControllerWithMiddleware::class, 'routeHasTenantParameter'])
->middleware('central')
->name('central-route');
RouteFacade::get('/{tenant}/tenant-route', [ControllerWithMiddleware::class, 'routeHasTenantParameter'])
->middleware('tenant')
->name('tenant-route');
$tenant = Tenant::create();
$tenantKey = $tenant->getTenantKey();
// Expect route to receive the tenant parameter
$response = pest()->get($tenantKey . '/central-route')->assertOk();
expect((bool) $response->getContent())->toBeTrue();
if ($pathIdentification) {
// Tenant parameter is removed from tenant routes using kernel path identification (Stancl\Tenancy\Listeners\ForgetTenantParameter)
$response = pest()->get($tenantKey . '/tenant-route')->assertOk();
expect((bool) $response->getContent())->toBeFalse();
} else {
// Tenant parameter is not removed from tenant routes using other kernel identification MW
$tenant->domains()->create(['domain' => $domain = $tenantKey . '.localhost']);
$response = pest()->get("http://{$domain}/{$tenantKey}/tenant-route")->assertOk();
expect((bool) $response->getContent())->toBeTrue();
}
} else {
RouteFacade::middlewareGroup('tenant', [$pathIdentification ? InitializeTenancyByPath::class : InitializeTenancyByDomain::class]);
// Route-level identification
RouteFacade::get('/{tenant}/central-route', [ControllerWithMiddleware::class, 'routeHasTenantParameter'])
->middleware('central')
->name('central-route');
RouteFacade::get('/{tenant}/tenant-route', [ControllerWithMiddleware::class, 'routeHasTenantParameter'])
->middleware('tenant')
->name('tenant-route');
$tenant = Tenant::create();
$tenantKey = $tenant->getTenantKey();
if ($pathIdentification) {
// Tenant parameter isn't removed from central routes
$response = pest()->get("http://localhost/{$tenantKey}/central-route")->assertOk();
expect((bool) $response->getContent())->toBeTrue();
// Tenant parameter is removed from tenant routes that are using kernel path identification (in PathTenantResolver)
$response = pest()->get("http://localhost/{$tenantKey}/tenant-route")->assertOk();
expect((bool) $response->getContent())->toBeFalse();
} else {
$tenant->domains()->create(['domain' => $domain = $tenantKey . '.localhost']);
// Tenant parameter is not removed from tenant routes that are using other identification MW
$response = pest()->get("http://{$domain}/{$tenantKey}/tenant-route")->assertOk();
expect((bool) $response->getContent())->toBeTrue();
}
}
})->with([
'kernel path identification' => ['kernelIdentification' => true, 'pathIdentification' => true],
'route-level path identification' => ['kernelIdentification' => false, 'pathIdentification' => true],
'kernel domain identification' => ['kernelIdentification' => true, 'pathIdentification' => false],
'route-level domain identification' => ['kernelIdentification' => false, 'pathIdentification' => false],
]);
test('route level identification is prioritized over kernel identification', function (
string|array $kernelIdentificationMiddleware,
string|array $routeIdentificationMiddleware,
string $routeUri,
string $domainToVisit,
string|null $domain = null,
RouteMode $defaultRouteMode,
) {
$tenant = Tenant::create();
$domainToVisit = str_replace('{tenantKey}', $tenant->getTenantKey(), $domainToVisit);
config(['tenancy.default_route_mode' => $defaultRouteMode]);
if ($domain) {
$tenant->domains()->create(['domain' => str_replace('{tenantKey}', $tenant->getTenantKey(), $domain)]);
}
foreach (Arr::wrap($kernelIdentificationMiddleware) as $identificationMiddleware) {
app(Kernel::class)->pushMiddleware($identificationMiddleware);
}
// We're testing *non-early* route-level identification so that we can assert that early kernel identification got skipped
// Also, ignore the defaulting when the identification MW is applied directly on the route
// The route is automatically considered tenant if it has identification middleware (unless it also has the 'universal' middleware)
RouteFacade::get($routeUri, [ControllerWithMiddleware::class, 'index'])->middleware($routeIdentificationMiddleware);
pest()->get($domainToVisit)->assertOk();
// Kernel (early) identification skipped
expect(app()->make('controllerRunsInTenantContext'))->toBeFalse();
})->with([
'kernel request data identification mw' => ['kernelMiddleware' => InitializeTenancyByRequestData::class],
'kernel path identification mw' => ['kernelMiddleware' => InitializeTenancyByPath::class],
'kernel domain identification mw' => ['kernelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomain::class]],
'kernel subdomain identification mw' => ['kernelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyBySubdomain::class]],
'kernel domainOrSubdomain identification mw using domain' => ['kernelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomainOrSubdomain::class]],
'kernel domainOrSubdomain identification mw using subdomain' => ['kernelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomainOrSubdomain::class]],
// Creates a matrix (multiple with())
])->with([
'route level request data identification mw' => ['routeLevelMiddleware' => InitializeTenancyByRequestData::class, 'routeUri' => '/tenant-route', 'domainToVisit' => 'http://localhost/tenant-route?tenant={tenantKey}', 'domain' => null],
'route level path identification mw' => ['routeLevelMiddleware' => InitializeTenancyByPath::class, 'routeUri' => '/{tenant}/tenant-route', 'domainToVisit' => 'http://localhost/{tenantKey}/tenant-route', 'domain' => null],
'route level domain identification mw' => ['routeLevelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomain::class], 'routeUri' => '/tenant-route', 'domainToVisit' => 'http://{tenantKey}.test/tenant-route', 'domain' => '{tenantKey}.test'],
'route level subdomain identification mw' => ['routeLevelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyBySubdomain::class], 'routeUri' => '/tenant-route', 'domainToVisit' => 'http://{tenantKey}.localhost/tenant-route', 'domain' => '{tenantKey}'],
'route level domainOrSubdomain identification mw using domain' => ['routeLevelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomainOrSubdomain::class], 'routeUri' => '/tenant-route', 'domainToVisit' => 'http://{tenantKey}.test/tenant-route', 'domain' => '{tenantKey}.test'],
'route level domainOrSubdomain identification mw using subdomain' => ['routeLevelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomainOrSubdomain::class], 'routeUri' => '/tenant-route', 'domainToVisit' => 'http://{tenantKey}.localhost/tenant-route', 'domain' => '{tenantKey}'],
])
->with([
'default to tenant routes' => RouteMode::TENANT,
'default to central routes' => RouteMode::CENTRAL,
]);
test('routes with path identification middleware can get prefixed using the reregister action', function() {
$tenantKey = Tenant::create()->getTenantKey();
RouteFacade::get('/home', fn () => tenant()?->getTenantKey())->name('home')->middleware(InitializeTenancyByPath::class);
pest()->get("http://localhost/$tenantKey/home")->assertNotFound();
app(CloneRoutesAsTenant::class)->handle();
pest()->get("http://localhost/$tenantKey/home")->assertOk();
});
function assertTenancyInitializedInEarlyIdentificationRequest(bool $expect = true): void
{
expect($string)->toBe(tenant()->getTenantKey() . '-abc123'); // Assert that the service class returns tenant value
expect(app()->make('additionalMiddlewareRunsInTenantContext'))->toBeTrue(); // Assert that middleware added in the controller constructor runs in tenant context
expect(app()->make('controllerRunsInTenantContext'))->toBeTrue(); // Assert that tenancy is initialized in the controller constructor
expect(app()->make('additionalMiddlewareRunsInTenantContext'))->toBe($expect); // Assert that middleware added in the controller constructor runs in tenant context
expect(app()->make('controllerRunsInTenantContext'))->toBe($expect); // Assert that tenancy is initialized in the controller constructor
}