create(['email' => 'c@imp.test', 'name' => 'Imp Kunde']); $this->actingAs($admin) ->post(route('admin.impersonate', $customer->uuid)) ->assertRedirect(route('dashboard')); $customer->refresh(); expect($customer->user_id)->not->toBeNull() ->and(auth()->id())->toBe($customer->user_id) ->and(session('impersonator_id'))->toBe($admin->id); // Return to the admin session. $this->post(route('impersonate.leave'))->assertRedirect(route('admin.overview')); expect(auth()->id())->toBe($admin->id) ->and(session()->has('impersonator_id'))->toBeFalse(); }); it('reuses an existing portal user with the same email', function () { $existing = User::factory()->create(['email' => 'shared@imp.test', 'is_admin' => false]); $customer = Customer::factory()->create(['email' => 'shared@imp.test']); expect($customer->ensureUser()->id)->toBe($existing->id); expect($customer->fresh()->user_id)->toBe($existing->id); }); it('refuses to link an admin account as a portal login', function () { $adminUser = User::factory()->create(['email' => 'ops@imp.test', 'is_admin' => true]); $customer = Customer::factory()->create(['email' => 'ops@imp.test']); expect(fn () => $customer->ensureUser())->toThrow(RuntimeException::class); expect($customer->fresh()->user_id)->toBeNull(); }); it('forbids a non-admin from impersonating', function () { $user = User::factory()->create(['is_admin' => false]); $customer = Customer::factory()->create(); $this->actingAs($user) ->post(route('admin.impersonate', $customer->uuid)) ->assertForbidden(); }); it('gates impersonation start to authenticated users', function () { $customer = Customer::factory()->create(); $this->post(route('admin.impersonate', $customer->uuid))->assertRedirect('/login'); });