Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat: Return to PostHog on log out from impersonation (#63933)

Luke Belton7ec18300033f
diff --git a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationNotice.tsx b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationNotice.tsx
index 040ee47ae509..30fba5ed814b 100644
--- a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationNotice.tsx
+++ b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationNotice.tsx
@@ -95,7 +95,7 @@ function LoginAsContent({
function ImpersonationExpiredOverlay({ expiredSessionInfo }: { expiredSessionInfo: ExpiredSessionInfo }): JSX.Element {
const { isReImpersonating } = useValues(impersonationNoticeLogic)
- const { reImpersonate } = useActions(impersonationNoticeLogic)
+ const { reImpersonate, returnToPostHog } = useActions(impersonationNoticeLogic)
const [readOnly, setReadOnly] = useState(true)
@@ -114,6 +114,16 @@ function ImpersonationExpiredOverlay({ expiredSessionInfo }: { expiredSessionInf
onClick: () => {
window.location.href = '/admin/'
},
+ sideAction: {
+ dropdown: {
+ placement: 'top-end',
+ overlay: (
+ <LemonButton fullWidth onClick={() => returnToPostHog()}>
+ Return to PostHog
+ </LemonButton>
+ ),
+ },
+ },
}}
>
<LemonCheckbox checked={readOnly} onChange={setReadOnly} label="Read-only mode (recommended)" />
@@ -125,7 +135,8 @@ function ImpersonationNoticeContent(): JSX.Element {
const { user, userLoading } = useValues(userLogic)
const { logout, loadUser } = useActions(userLogic)
const { isReadOnly, isUpgradeModalOpen, isImpersonationUpgradeInProgress } = useValues(impersonationNoticeLogic)
- const { closeUpgradeModal, upgradeImpersonation, setSessionExpired } = useActions(impersonationNoticeLogic)
+ const { closeUpgradeModal, upgradeImpersonation, setSessionExpired, returnToPostHog } =
+ useActions(impersonationNoticeLogic)
const handleSessionExpired = (): void => {
if (user) {
@@ -160,8 +171,23 @@ function ImpersonationNoticeContent(): JSX.Element {
<LemonButton type="secondary" size="small" onClick={() => loadUser()} loading={userLoading}>
Refresh
</LemonButton>
- <LemonButton type="secondary" status="danger" size="small" onClick={() => logout()}>
- Log out
+ <LemonButton
+ type="secondary"
+ status="danger"
+ size="small"
+ onClick={() => logout()}
+ sideAction={{
+ dropdown: {
+ placement: 'top-end',
+ overlay: (
+ <LemonButton fullWidth size="small" onClick={() => returnToPostHog()}>
+ Log out to PostHog
+ </LemonButton>
+ ),
+ },
+ }}
+ >
+ Log out to admin
</LemonButton>
</div>
{isReadOnly && (
diff --git a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.stories.tsx b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.stories.tsx
index c4aeb8944072..70b595794d89 100644
--- a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.stories.tsx
+++ b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.stories.tsx
@@ -1,6 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
-import { LemonCheckbox } from '@posthog/lemon-ui'
+import { LemonButton, LemonCheckbox } from '@posthog/lemon-ui'
import { ImpersonationReasonModal } from './ImpersonationReasonModal'
@@ -33,7 +33,21 @@ export const SessionExpiredReImpersonation: Story = {
description={`Your session impersonating ${IMPERSONATED_EMAIL} has expired.`}
confirmText="Re-impersonate"
closable={false}
- cancelButton={{ label: 'Return to admin', status: 'danger', onClick: noop }}
+ cancelButton={{
+ label: 'Return to admin',
+ status: 'danger',
+ onClick: noop,
+ sideAction: {
+ dropdown: {
+ placement: 'top-end',
+ overlay: (
+ <LemonButton fullWidth onClick={noop}>
+ Return to PostHog
+ </LemonButton>
+ ),
+ },
+ },
+ }}
inline
>
<LemonCheckbox checked onChange={noop} label="Read-only mode (recommended)" />
diff --git a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.tsx b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.tsx
index abf84abbd546..b666ecd0f023 100644
--- a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.tsx
+++ b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.tsx
@@ -1,11 +1,12 @@
import { ReactNode, useId, useState } from 'react'
-import { LemonButton, LemonInput, LemonModal } from '@posthog/lemon-ui'
+import { LemonButton, LemonInput, LemonModal, SideAction } from '@posthog/lemon-ui'
export interface ImpersonationReasonModalCancelButton {
label: string
status?: 'default' | 'danger'
onClick: () => void
+ sideAction?: SideAction
}
export interface ImpersonationReasonModalProps {
@@ -65,7 +66,12 @@ export function ImpersonationReasonModal({
footer={
<>
{cancel && (
- <LemonButton type="secondary" status={cancel.status} onClick={cancel.onClick}>
+ <LemonButton
+ type="secondary"
+ status={cancel.status}
+ onClick={cancel.onClick}
+ sideAction={cancel.sideAction}
+ >
{cancel.label}
</LemonButton>
)}
diff --git a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts
index 85d27a3216e0..368004c954e5 100644
--- a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts
+++ b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts
@@ -254,6 +254,31 @@ describe('impersonationNoticeLogic', () => {
})
})
+ describe('returnToPostHog listener', () => {
+ it('navigates to the loginas logout endpoint with next pointing back to the app', async () => {
+ const originalLocation = window.location
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: { ...originalLocation, href: originalLocation.href },
+ })
+
+ try {
+ await expectLogic(logic, () => {
+ logic.actions.returnToPostHog()
+ }).toFinishAllListeners()
+
+ expect(window.location.href).toBe('/admin/logout/?next=%2F')
+ } finally {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: originalLocation,
+ })
+ }
+ })
+ })
+
describe('loadUserSuccess listener', () => {
it('clears expired session when user is impersonated', async () => {
logic.actions.setSessionExpired({ email: '[email protected]', userId: 123, isImpersonatedUntil: null })
diff --git a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.ts b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.ts
index 34c4bd462851..7bd8b4b5175b 100644
--- a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.ts
+++ b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.ts
@@ -55,6 +55,7 @@ export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([
setSessionExpired: (info: ExpiredSessionInfo | null) => ({ info }),
reImpersonate: (reason: string, readOnly: boolean) => ({ reason, readOnly }),
reImpersonateFailure: (error: string) => ({ error }),
+ returnToPostHog: true,
}),
reducers({
@@ -119,6 +120,11 @@ export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([
}),
listeners(({ actions, values }) => ({
+ returnToPostHog: () => {
+ // Restore the original staff login (via the loginas logout endpoint) and
+ // land back in the PostHog app rather than the Django admin.
+ window.location.href = `/admin/logout/?next=${encodeURIComponent('/')}`
+ },
upgradeImpersonationSuccess: () => {
if (values.isUpgradeModalOpen && !values.isReadOnly) {
actions.closeUpgradeModal()
diff --git a/posthog/middleware.py b/posthog/middleware.py
index e1dd4d77b969..d78ce48d6542 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -23,7 +23,7 @@ from django.shortcuts import redirect
from django.urls import Resolver404, resolve
from django.utils.cache import add_never_cache_headers
from django.utils.deprecation import MiddlewareMixin
-from django.utils.http import http_date
+from django.utils.http import http_date, url_has_allowed_host_and_scheme
import structlog
import posthoganalytics
@@ -1442,12 +1442,18 @@ class ImpersonationBlockedPathsMiddleware:
def impersonated_session_logout(request: HttpRequest) -> HttpResponse:
"""
- Log out of an impersonated session and redirect back to the
+ Log out of an impersonated session. Redirects to a safe `next` target when
+ provided (e.g. `/` to return to the PostHog app), otherwise back to the
impersonated user's admin change page.
"""
+ next_url = request.GET.get("next")
+ safe_next = (
+ next_url if next_url and url_has_allowed_host_and_scheme(next_url, allowed_hosts={request.get_host()}) else None
+ )
+
if not is_impersonated_session(request):
- return redirect("/admin/")
+ return redirect(safe_next or "/admin/")
impersonated_user_pk = request.user.pk
restore_original_login(request)
- return redirect(f"/admin/posthog/user/{impersonated_user_pk}/change/")
+ return redirect(safe_next or f"/admin/posthog/user/{impersonated_user_pk}/change/")
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index ce50de2fdf64..7bbeed55c0d1 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -708,6 +708,56 @@ class TestAutoLogoutImpersonateMiddleware(APIBaseTest):
assert res.status_code == 200
assert res.json()["email"] == "[email protected]"
+ @parameterized.expand(
+ [
+ # A safe `next` lets staff return straight to the PostHog app.
+ ("safe_next", "?next=/", "/"),
+ # No `next` keeps the default admin change-page redirect.
+ ("no_next", "", None),
+ # Unsafe `next` values are ignored, falling back to the admin default.
+ ("unsafe_scheme_relative", "?next=//evil.com/path", None),
+ ("unsafe_absolute_url", "?next=https://evil.com", None),
+ ]
+ )
+ def test_loginas_logout_redirect(self, _name, query_suffix, expected_location):
+ """The loginas logout endpoint redirects to a safe `next` when given, otherwise to the admin change page."""
+ now = datetime.now()
+ with freeze_time(now):
+ self.login_as_other_user()
+
+ res = self.client.get(f"/admin/logout/{query_suffix}")
+ assert res.status_code == 302
+ assert res.headers["Location"] == (expected_location or f"/admin/posthog/user/{self.other_user.id}/change/")
+
+ # Verify we're back to the original staff user
+ res = self.client.get("/api/users/@me")
+ assert res.status_code == 200
+ assert res.json()["email"] == "[email protected]"
+
+ def test_loginas_logout_with_next_returns_to_app_after_expiry(self):
+ """Even when the session has expired server-side, `next` survives the middleware
+ bounce so staff still land back in the PostHog app."""
+ now = datetime.now()
+ with freeze_time(now):
+ self.login_as_other_user()
+
+ with freeze_time(now + timedelta(seconds=35)):
+ # First hit: the auto-logout middleware restores the original login and
+ # bounces back to the same path, preserving ?next=/.
+ res = self.client.get("/admin/logout/?next=/")
+ assert res.status_code == 302
+ assert res.headers["Location"] == "/admin/logout/?next=/"
+
+ # Second hit: no longer an impersonated session, so the view honors `next`.
+ res = self.client.get("/admin/logout/?next=/")
+ assert res.status_code == 302
+ assert res.headers["Location"] == "/"
+
+ # Verify we're back to the original staff user
+ res = self.client.get("/api/users/@me")
+ assert res.status_code == 200
+ assert res.json()["email"] == "[email protected]"
+
@override_settings(IMPERSONATION_TIMEOUT_SECONDS=100)
@override_settings(IMPERSONATION_IDLE_TIMEOUT_SECONDS=20)