Skip to content

[4.x] UserImpersonation: store auth guard in session, add $logout param to stopImpersonating()#1437

Open
lukinovec wants to merge 11 commits intomasterfrom
stop-impersonating
Open

[4.x] UserImpersonation: store auth guard in session, add $logout param to stopImpersonating()#1437
lukinovec wants to merge 11 commits intomasterfrom
stop-impersonating

Conversation

@lukinovec
Copy link
Copy Markdown
Contributor

@lukinovec lukinovec commented Mar 3, 2026

Potentially breaking change: session('tenancy_impersonating') doesn't work anymore. We're using session('tenancy_impersonation_guard') instead.

The 'tenancy_impersonating' session variable got replaced by 'tenancy_impersonation_guard'. UserImpersonation::stopImpersonating() now calls logout() on the guard retrieved by session()->get('tenancy_impersonation_guard') instead of calling logout() on the current auth guard. Now. if you create the impersonation token with guard 'web', and call UserImpersonation::stopImpersonating(), for example in a route that has the auth:sanctum middleware (= the current guard in that route would be RequestGuard which doesn't even have the logout() method -- not the guard for which the impersonation token was created), the method will correctly log the user out of the 'web' guard using which he was actually authenticated instead of the current guard of the visited route (which doesn't have to be the same guard for which impersonation started).

UserImpersonation::stopImpersonating() now also accepts the $logout parameter, which is true by default. If false is passed, the method just forgets tenancy_impersonation_guard from session without logging out.

Summary by CodeRabbit

  • New Features

    • Impersonation now records which authentication guard was used. Ending impersonation can optionally keep the current session authenticated or log out the impersonation-specific guard; ending impersonation when not active now raises an error.
  • Tests

    • Updated and added tests to validate guard-aware impersonation tracking, optional logout behavior, and isolation of logout between different authentication guards.

…e auth guard in 'tenancy_impersonation_guard'

Also make `stopImpersonating()` able to keep the user logged in.
@codecov
Copy link
Copy Markdown

codecov bot commented Mar 3, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.05%. Comparing base (c32f52c) to head (c252ac4).

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #1437      +/-   ##
============================================
+ Coverage     86.03%   86.05%   +0.01%     
- Complexity     1156     1158       +2     
============================================
  Files           184      184              
  Lines          3381     3385       +4     
============================================
+ Hits           2909     2913       +4     
  Misses          472      472              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@lukinovec lukinovec marked this pull request as ready for review March 11, 2026 17:17
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 12, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2c362865-dc50-4882-93fd-0da99839bcb9

📥 Commits

Reviewing files that changed from the base of the PR and between 3c9d532 and a5f5182.

📒 Files selected for processing (1)
  • src/Features/UserImpersonation.php

📝 Walkthrough

Walkthrough

Replaced the boolean impersonation session flag with storing the impersonation auth guard name; reordered session/token handling in response creation. isImpersonating() checks the guard key. stopImpersonating(bool $logout = true) may log out the stored guard, throws if not impersonating, and clears the guard. Tests updated and expanded.

Changes

Cohort / File(s) Summary
User Impersonation Feature
src/Features/UserImpersonation.php
makeResponse now sets tenancy_impersonation_guard to $token->auth_guard and then deletes the token; isImpersonating() reads tenancy_impersonation_guard; stopImpersonating(bool $logout = true) throws if no guard present, optionally calls auth($guard)->logout(), and always forgets the session key.
Impersonation Tests
tests/TenantUserImpersonationTest.php
Updated assertions to check session('tenancy_impersonation_guard') and $token->auth_guard; added tests for stopImpersonating(false) (end impersonation but keep auth) and for logout behavior targeting the stored guard and subsequent exception when stopping again.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant App
    participant Session
    participant TokenStore
    participant Auth

    Client->>App: request impersonation
    App->>Session: set tenancy_impersonation_guard = token.auth_guard
    App->>TokenStore: delete impersonation token
    App-->>Client: redirect/response

    Client->>App: request stopImpersonating(logout = true/false)
    App->>Session: read guard = tenancy_impersonation_guard
    alt guard exists and logout == true
        App->>Auth: auth(guard).logout()
    end
    App->>Session: forget tenancy_impersonation_guard
    App-->>Client: redirect/response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I stole a guard and tucked it in,
Cleared the token with a gentle grin.
You can leave logged in or take a bow—
The session keeps the secret now.
I hop off, tail twitching, and vow.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main changes: storing the auth guard in session and adding a $logout parameter to stopImpersonating().

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch stop-impersonating

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/Features/UserImpersonation.php`:
- Line 79: The session check and cleanup currently only look for
'tenancy_impersonation_guard', which breaks existing sessions using the legacy
'tenancy_impersonating' key; update the UserImpersonation logic so read
operations (e.g., isImpersonating or the method that returns
session()->has(...)) check for either session key ('tenancy_impersonation_guard'
OR 'tenancy_impersonating'), and update any cleanup/clear method (the method
that forgets/clears the impersonation at line ~93) to remove both keys so legacy
sessions get cleaned up during upgrade; keep writing the new key going forward
but accept and clear the old key for one upgrade cycle.

In `@tests/TenantUserImpersonationTest.php`:
- Around line 153-192: Update the test to cover the case where the current
request guard differs from the stored impersonation guard: after creating the
impersonation (tenancy()->impersonate) and asserting impersonation is active,
simulate a different current guard (for example call Auth::shouldUse('api') or
Auth::guard('api')->loginUsingId($user->id)) while leaving the session key
tenancy_impersonation_guard set to the original guard (e.g. 'web'), then call
UserImpersonation::stopImpersonating(false) and assert impersonation was cleared
(UserImpersonation::isImpersonating() is false and
session('tenancy_impersonation_guard') is null) and that the user remains
authenticated under the current guard and can access the dashboard; reference
tenancy()->impersonate, UserImpersonation::stopImpersonating(false), and the
session key 'tenancy_impersonation_guard' when adding these steps.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 04d2c13e-3479-445b-87f6-cb5505d10f55

📥 Commits

Reviewing files that changed from the base of the PR and between 60dd522 and df44dea.

📒 Files selected for processing (2)
  • src/Features/UserImpersonation.php
  • tests/TenantUserImpersonationTest.php

Comment thread src/Features/UserImpersonation.php
Comment thread tests/TenantUserImpersonationTest.php
Starting impersonation using 'web', then using a different guard and calling UserImpersonation::stopImpersonating() should log out the user from the 'web' guard stored in `session('tenancy_impersonation_guard')`.
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
tests/TenantUserImpersonationTest.php (1)

228-232: ⚠️ Potential issue | 🟠 Major

Switch the active guard before calling stopImpersonating().

auth('test')->loginUsingId($user->id) authenticates that guard, but it does not make test the guard resolved by auth() here. Without Auth::shouldUse('test') (or equivalent), the old auth()->logout() behavior would still log out web, so this test does not actually pin the regression this PR is fixing.

Proposed change
     // Manually log in the user using a different guard
     auth('test')->loginUsingId($user->id);
+    Auth::shouldUse('test');

     // Should log out the user from the guard used for impersonation ('web')
     UserImpersonation::stopImpersonating();
In Laravel, does calling `auth('test')->loginUsingId($id)` change the guard used by subsequent `auth()->logout()` calls, or is `Auth::shouldUse('test')` required to switch the current/default guard?
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/TenantUserImpersonationTest.php` around lines 228 - 232, Test currently
logs in with auth('test')->loginUsingId($user->id) but doesn't switch the active
guard, so stopImpersonating() still operates on the default guard; call
Auth::shouldUse('test') (or Auth::shouldUse($previousGuard) to restore later)
before logging in or before invoking UserImpersonation::stopImpersonating() so
the active guard matches auth('test')->loginUsingId and the test exercises the
logout behavior on the intended guard (reference auth('test')->loginUsingId,
Auth::shouldUse, and UserImpersonation::stopImpersonating).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@tests/TenantUserImpersonationTest.php`:
- Around line 228-232: Test currently logs in with
auth('test')->loginUsingId($user->id) but doesn't switch the active guard, so
stopImpersonating() still operates on the default guard; call
Auth::shouldUse('test') (or Auth::shouldUse($previousGuard) to restore later)
before logging in or before invoking UserImpersonation::stopImpersonating() so
the active guard matches auth('test')->loginUsingId and the test exercises the
logout behavior on the intended guard (reference auth('test')->loginUsingId,
Auth::shouldUse, and UserImpersonation::stopImpersonating).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 48ae8e55-1100-4ba5-bef0-3fa70abe0b8e

📥 Commits

Reviewing files that changed from the base of the PR and between df44dea and 920cb06.

📒 Files selected for processing (1)
  • tests/TenantUserImpersonationTest.php

Originally, we just authenticated the user using a different guard, without actually switching to that guard. Now, we fully switch to the 'test' guard.
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/TenantUserImpersonationTest.php`:
- Around line 194-237: Add a defensive check to
UserImpersonation::stopImpersonating() so it does nothing if there is no stored
tenancy_impersonation_guard in session (i.e. when not impersonating) —
specifically, read the guard via session('tenancy_impersonation_guard') and if
null/empty return early instead of calling auth(null)->logout(); then add the
edge-case test that calls UserImpersonation::stopImpersonating() when
UserImpersonation::isImpersonating() is false to assert the current
authenticated user remains logged in.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 1d8079f0-763a-43ae-969e-d4f2d7021257

📥 Commits

Reviewing files that changed from the base of the PR and between 920cb06 and 1289550.

📒 Files selected for processing (1)
  • tests/TenantUserImpersonationTest.php

Comment thread tests/TenantUserImpersonationTest.php
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/Features/UserImpersonation.php`:
- Around line 88-90: Replace the generic Exception thrown in the
UserImpersonation::isImpersonating check with a specific exception type: create
a new NotImpersonatingException (e.g., class NotImpersonatingException extends
\Exception with the existing message) under the Stancl\Tenancy\Exceptions
namespace, import that exception in src/Features/UserImpersonation.php, and
change the throw in the block that currently calls throw new Exception('Not
currently impersonating any user.'); to throw new NotImpersonatingException();
so callers can catch the specific error.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: bfd17528-30ae-4366-8600-28a387fabe14

📥 Commits

Reviewing files that changed from the base of the PR and between 1289550 and 3c9d532.

📒 Files selected for processing (2)
  • src/Features/UserImpersonation.php
  • tests/TenantUserImpersonationTest.php

Comment thread src/Features/UserImpersonation.php
@lukinovec
Copy link
Copy Markdown
Contributor Author

@coderabbitai resume

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 14, 2026

✅ Actions performed

Reviews resumed.

@lukinovec
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 14, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@lukinovec
Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 14, 2026

✅ Actions performed

Full review triggered.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/Features/UserImpersonation.php`:
- Around line 83-86: Update the docblock for the stopImpersonating method to
accurately document the optional logout behavior: mention the $logout parameter
(bool $logout = true) and clarify that when $logout is false the method will
only forget the impersonation session without logging the user out; include a
short description of both behaviors and the parameter purpose next to the method
signature (stopImpersonating).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: b3c06c11-0bcc-4c6f-8367-3798c71a8362

📥 Commits

Reviewing files that changed from the base of the PR and between 60dd522 and 3c9d532.

📒 Files selected for processing (2)
  • src/Features/UserImpersonation.php
  • tests/TenantUserImpersonationTest.php

Comment thread src/Features/UserImpersonation.php
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/Features/UserImpersonation.php`:
- Around line 98-104: The session cleanup
(session()->forget('tenancy_impersonation_guard')) can be skipped if
auth($guard)->logout() throws; update the impersonation cleanup so that the
logout call is executed inside a try/finally (or try/catch/finally) and
guarantee session()->forget('tenancy_impersonation_guard') runs in the finally
block; catch and optionally log any exception from auth($guard)->logout() (using
your logger) but always clear the session key obtained via
session()->get('tenancy_impersonation_guard') to avoid leaving impersonation
state stuck.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8469df72-6b29-41c0-8459-82986ee98dde

📥 Commits

Reviewing files that changed from the base of the PR and between 3c9d532 and a5f5182.

📒 Files selected for processing (1)
  • src/Features/UserImpersonation.php

Comment thread src/Features/UserImpersonation.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants