create(['email' => 'c@imp.test', 'name' => 'Imp Kunde']); $this->actingAs($admin, 'operator') ->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 auto-link an existing portal account while an operator is signed in', function () { // assertNotAdmin() used to check whether the row it found WAS an operator // — structurally impossible now, since operators are not rows in this // table at all. What is left to guard is the moment rather than the row: // ensureUser() must not silently attach a `users` row to a customer while // the caller is an operator. User::factory()->create(['email' => 'ops@imp.test']); $customer = Customer::factory()->create(['email' => 'ops@imp.test']); $this->actingAs(Operator::factory()->role('Owner')->create(), 'operator'); 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'); });