From a306f1e972c75b5a6c72985eed17aadb941e9665 Mon Sep 17 00:00:00 2001 From: lukinovec Date: Tue, 3 Mar 2026 12:28:42 +0100 Subject: [PATCH] Test that `stopImpersonating()` can keep the user authenticated --- tests/TenantUserImpersonationTest.php | 41 +++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/tests/TenantUserImpersonationTest.php b/tests/TenantUserImpersonationTest.php index e252ddc7..2e9b3c3a 100644 --- a/tests/TenantUserImpersonationTest.php +++ b/tests/TenantUserImpersonationTest.php @@ -148,6 +148,47 @@ test('tenant user can be impersonated on a tenant path', function () { ->assertRedirect('/login'); }); +test('stopImpersonating can keep the user authenticated', function() { + makeLoginRoute(); + + Route::middleware(InitializeTenancyByPath::class)->prefix('/{tenant}')->group(getRoutes(false)); + + $tenant = Tenant::create([ + 'id' => 'acme', + 'tenancy_db_name' => 'db' . Str::random(16), + ]); + + migrateTenants(); + + $user = $tenant->run(function () { + return ImpersonationUser::create([ + 'name' => 'Joe', + 'email' => 'joe@local', + 'password' => bcrypt('secret'), + ]); + }); + + // Impersonate the user + $token = tenancy()->impersonate($tenant, $user->id, '/acme/dashboard'); + + pest()->get('/acme/impersonate/' . $token->token) + ->assertRedirect('/acme/dashboard'); + + expect(UserImpersonation::isImpersonating())->toBeTrue(); + + // Stop impersonating without logging out + UserImpersonation::stopImpersonating(false); + + // The impersonation session key should be cleared + expect(UserImpersonation::isImpersonating())->toBeFalse(); + expect(session('tenancy_impersonation_guard'))->toBeNull(); + + // The user should still be authenticated + pest()->get('/acme/dashboard') + ->assertSuccessful() + ->assertSee('You are logged in as Joe'); +}); + test('tokens have a limited ttl', function () { Route::middleware(InitializeTenancyByDomain::class)->group(getRoutes());