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(impersonation): add change user to the impersonation tray (#66384)

Xander1231bb9c6853
diff --git a/ee/admin/loginas_views.py b/ee/admin/loginas_views.py
index 02c4b07537b6..008d574608b0 100644
--- a/ee/admin/loginas_views.py
+++ b/ee/admin/loginas_views.py
@@ -1,14 +1,19 @@
import json
-from django.http import Http404, JsonResponse
+from django.http import Http404, HttpResponseRedirect, JsonResponse
from django.views.decorators.http import require_http_methods
import posthoganalytics
+from loginas import settings as la_settings
from loginas.utils import is_impersonated_session
from loginas.views import user_login as loginas_user_login
from posthog.helpers.impersonation import get_original_user_from_session
-from posthog.middleware import IMPERSONATION_READ_ONLY_SESSION_KEY, is_read_only_impersonation
+from posthog.middleware import (
+ IMPERSONATION_READ_ONLY_SESSION_KEY,
+ IMPERSONATION_REASON_SESSION_KEY,
+ is_read_only_impersonation,
+)
from posthog.models import User
@@ -16,10 +21,28 @@ def loginas_user(request, user_id):
staff_user = request.user
response = loginas_user_login(request, user_id)
- if is_impersonated_session(request):
+ # loginas redirects to LOGIN_REDIRECT only when the impersonation actually started; a rejected
+ # attempt (empty reason, failed CAN_LOGIN_AS) redirects back to the referer without touching the
+ # session. Gate the mutations on success so a rejected re-impersonation can't change the active
+ # session's mode or reason.
+ login_succeeded = (
+ isinstance(response, HttpResponseRedirect)
+ and response.url == la_settings.LOGIN_REDIRECT
+ and is_impersonated_session(request)
+ )
+
+ if login_succeeded:
is_read_only = request.POST.get("read_only") != "false"
if is_read_only:
request.session[IMPERSONATION_READ_ONLY_SESSION_KEY] = True
+ elif IMPERSONATION_READ_ONLY_SESSION_KEY in request.session:
+ # Re-impersonating the same user keeps the existing session (Django only flushes on a
+ # user change), so clear a prior read-only flag to honor the mode requested here.
+ del request.session[IMPERSONATION_READ_ONLY_SESSION_KEY]
+
+ # Persist the reason server-side so it survives both Django-admin and in-app starts,
+ # and can be surfaced to the frontend (autofill).
+ request.session[IMPERSONATION_REASON_SESSION_KEY] = request.POST.get("reason", "")
target_user = User.objects.filter(id=user_id).first()
posthoganalytics.capture(
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 9931bb9c4368..f9dfcce630ca 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -3482,6 +3482,11 @@ export interface UserApi {
readonly is_impersonated_until: string | null
/** @nullable */
readonly is_impersonated_read_only: boolean | null
+ /**
+ * The reason the operator gave when the current impersonation session started (or was last up/downgraded). Null when not impersonating.
+ * @nullable
+ */
+ readonly is_impersonated_reason: string | null
/** @nullable */
readonly sensitive_session_expires_at: string | null
readonly team: TeamBasicApi
@@ -3584,6 +3589,11 @@ export interface PatchedUserApi {
readonly is_impersonated_until?: string | null
/** @nullable */
readonly is_impersonated_read_only?: boolean | null
+ /**
+ * The reason the operator gave when the current impersonation session started (or was last up/downgraded). Null when not impersonating.
+ * @nullable
+ */
+ readonly is_impersonated_reason?: string | null
/** @nullable */
readonly sensitive_session_expires_at?: string | null
readonly team?: TeamBasicApi
diff --git a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationNotice.tsx b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationNotice.tsx
index ed021fa8a433..7624d90839ed 100644
--- a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationNotice.tsx
+++ b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationNotice.tsx
@@ -3,16 +3,20 @@ import './ImpersonationNotice.scss'
import { useActions, useValues } from 'kea'
import { useEffect, useRef, useState } from 'react'
-import { IconCollapse, IconEllipsis, IconWarning } from '@posthog/icons'
-import { LemonButton, LemonCheckbox, LemonMenu, Tooltip } from '@posthog/lemon-ui'
+import { IconChevronDown, IconCollapse, IconEllipsis, IconWarning } from '@posthog/icons'
+import { LemonButton, LemonCheckbox, LemonMenu, LemonTag, Tooltip } from '@posthog/lemon-ui'
import { DraggableWithSnapZones, DraggableWithSnapZonesRef } from 'lib/components/DraggableWithSnapZones'
import { dayjs } from 'lib/dayjs'
import { usePageVisibility } from 'lib/hooks/usePageVisibility'
import { IconDragHandle } from 'lib/lemon-ui/icons'
import { cn } from 'lib/utils/css-classes'
+import { membershipLevelToName } from 'lib/utils/permissioning'
+import { capitalizeFirstLetter, fullName } from 'lib/utils/strings'
import { userLogic } from 'scenes/userLogic'
+import { OrganizationMemberType } from '~/types'
+
import { AdminLoginButtons } from './AdminLoginButtons'
import {
AdminLoginUrl,
@@ -22,6 +26,21 @@ import {
} from './impersonationNoticeLogic'
import { ImpersonationReasonModal } from './ImpersonationReasonModal'
+// One row in the "Change user" dropdown: name on top, email beneath in muted text, level pill on the right.
+function ChangeUserMenuItemLabel({ member }: { member: OrganizationMemberType }): JSX.Element {
+ return (
+ <span className="flex items-center gap-2 justify-between w-full">
+ <span className="flex flex-col">
+ <span>{fullName(member.user)}</span>
+ <span className="text-xs text-muted">{member.user.email}</span>
+ </span>
+ <LemonTag>
+ {capitalizeFirstLetter(membershipLevelToName.get(member.level) ?? `unknown (${member.level})`)}
+ </LemonTag>
+ </span>
+ )
+}
+
function CountDown({ datetime, callback }: { datetime: dayjs.Dayjs; callback?: () => void }): JSX.Element {
const [now, setNow] = useState(() => dayjs())
const { isVisible: isPageVisible } = usePageVisibility()
@@ -91,6 +110,7 @@ function ImpersonationExpiredOverlay({ expiredSessionInfo }: { expiredSessionInf
description={`Your session impersonating ${expiredSessionInfo.email} has expired.`}
confirmText="Re-impersonate"
loading={isReImpersonating}
+ initialReason={expiredSessionInfo.reason ?? ''}
onConfirm={(reason) => reImpersonate(reason, readOnly)}
cancelButton={{
label: 'Return to admin',
@@ -118,9 +138,40 @@ function ImpersonationExpiredOverlay({ expiredSessionInfo }: { expiredSessionInf
function ImpersonationNoticeContent(): JSX.Element {
const { user, userLoading } = useValues(userLogic)
const { logout, loadUser } = useActions(userLogic)
- const { isReadOnly, isUpgradeModalOpen, isImpersonationUpgradeInProgress } = useValues(impersonationNoticeLogic)
- const { closeUpgradeModal, upgradeImpersonation, setSessionExpired, returnToPostHog } =
- useActions(impersonationNoticeLogic)
+ const {
+ isReadOnly,
+ isUpgradeModalOpen,
+ isImpersonationUpgradeInProgress,
+ changeableMembers,
+ isChangingUser,
+ membersLoading,
+ } = useValues(impersonationNoticeLogic)
+ const {
+ closeUpgradeModal,
+ upgradeImpersonation,
+ setSessionExpired,
+ returnToPostHog,
+ changeUser,
+ ensureAllMembersLoaded,
+ } = useActions(impersonationNoticeLogic)
+
+ // The user the operator picked to switch to; drives the confirm-reason modal.
+ const [pendingUserId, setPendingUserId] = useState<number | null>(null)
+
+ // The reason given when impersonation of the current user started (persisted server-side),
+ // used to pre-fill the change-user and upgrade modals.
+ const storedReason = user?.is_impersonated_reason
+
+ const changeUserItems =
+ changeableMembers.length === 0
+ ? [{ label: membersLoading ? 'Loading…' : 'No other members', disabledReason: ' ' }]
+ : changeableMembers.map((member) => ({
+ key: member.user.uuid,
+ label: <ChangeUserMenuItemLabel member={member} />,
+ disabledReason: isChangingUser ? 'Switching user…' : undefined,
+ // Always confirm via the modal (reason pre-filled) rather than switching silently.
+ onClick: () => setPendingUserId(member.user.id),
+ }))
const handleSessionExpired = (): void => {
if (user) {
@@ -128,6 +179,7 @@ function ImpersonationNoticeContent(): JSX.Element {
email: user.email,
userId: user.id,
isImpersonatedUntil: user.is_impersonated_until ?? null,
+ reason: user.is_impersonated_reason ?? null,
})
}
}
@@ -155,6 +207,20 @@ function ImpersonationNoticeContent(): JSX.Element {
<LemonButton type="secondary" size="small" onClick={() => loadUser()} loading={userLoading}>
Refresh
</LemonButton>
+ <LemonMenu
+ items={changeUserItems}
+ onVisibilityChange={(visible) => visible && ensureAllMembersLoaded()}
+ >
+ <LemonButton
+ type="secondary"
+ size="small"
+ sideIcon={<IconChevronDown />}
+ loading={isChangingUser}
+ tooltip="Change user"
+ >
+ User
+ </LemonButton>
+ </LemonMenu>
<LemonButton
type="secondary"
status="danger"
@@ -183,8 +249,24 @@ function ImpersonationNoticeContent(): JSX.Element {
description="Read-write mode allows you to make changes on behalf of the user. Please provide a reason for this upgrade."
confirmText="Upgrade"
loading={isImpersonationUpgradeInProgress}
+ initialReason={storedReason ?? ''}
/>
)}
+ <ImpersonationReasonModal
+ isOpen={pendingUserId !== null}
+ onClose={() => setPendingUserId(null)}
+ onConfirm={(reason) => {
+ if (pendingUserId !== null) {
+ changeUser(pendingUserId, reason)
+ }
+ setPendingUserId(null)
+ }}
+ title="Change impersonated user"
+ description="Provide a reason for impersonating this user."
+ confirmText="Switch user"
+ loading={isChangingUser}
+ initialReason={storedReason ?? ''}
+ />
</>
)
}
diff --git a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.test.tsx b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.test.tsx
new file mode 100644
index 000000000000..e7b41b1d2f50
--- /dev/null
+++ b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.test.tsx
@@ -0,0 +1,47 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import { ImpersonationReasonModal } from './ImpersonationReasonModal'
+
+describe('ImpersonationReasonModal', () => {
+ afterEach(cleanup)
+
+ it('pre-fills the reason input with the initial reason', () => {
+ render(
+ <ImpersonationReasonModal
+ inline
+ isOpen
+ onConfirm={jest.fn()}
+ title="Upgrade to read-write impersonation"
+ initialReason="support ticket #123"
+ />
+ )
+
+ expect(screen.getByDisplayValue('support ticket #123')).toBeInTheDocument()
+ })
+
+ it('starts empty when no initial reason is provided', () => {
+ render(<ImpersonationReasonModal inline isOpen onConfirm={jest.fn()} title="Change impersonated user" />)
+
+ expect(screen.getByPlaceholderText('e.g., Customer support request #12345')).toHaveValue('')
+ })
+
+ it('confirms with the pre-filled reason without re-typing', () => {
+ const onConfirm = jest.fn()
+ render(
+ <ImpersonationReasonModal
+ inline
+ isOpen
+ onConfirm={onConfirm}
+ title="Upgrade to read-write impersonation"
+ confirmText="Upgrade"
+ initialReason="support ticket #123"
+ />
+ )
+
+ fireEvent.click(screen.getByText('Upgrade'))
+
+ expect(onConfirm).toHaveBeenCalledWith('support ticket #123')
+ })
+})
diff --git a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.tsx b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.tsx
index b666ecd0f023..48e5937024b9 100644
--- a/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.tsx
+++ b/frontend/src/layout/navigation/ImpersonationNotice/ImpersonationReasonModal.tsx
@@ -1,4 +1,4 @@
-import { ReactNode, useId, useState } from 'react'
+import { ReactNode, useEffect, useId, useState } from 'react'
import { LemonButton, LemonInput, LemonModal, SideAction } from '@posthog/lemon-ui'
@@ -24,6 +24,9 @@ export interface ImpersonationReasonModalProps {
closable?: boolean
// Renders inline rather than in a portal — used by Storybook to capture snapshots.
inline?: boolean
+ // Pre-fills the reason field each time the modal opens (e.g. the upgrade flow reuses
+ // the original impersonation reason).
+ initialReason?: string
}
export function ImpersonationReasonModal({
@@ -38,16 +41,25 @@ export function ImpersonationReasonModal({
cancelButton,
closable = true,
inline = false,
+ initialReason = '',
}: ImpersonationReasonModalProps): JSX.Element {
- const [reason, setReason] = useState('')
+ const [reason, setReason] = useState(initialReason)
const reasonInputId = useId()
+ // Reset to the initial reason whenever the modal opens so each open starts from a
+ // clean, auto-filled state without clobbering edits while it's open.
+ useEffect(() => {
+ if (isOpen) {
+ setReason(initialReason)
+ }
+ }, [isOpen, initialReason])
+
const handleConfirm = (): void => {
onConfirm(reason)
}
const handleClose = (): void => {
- setReason('')
+ setReason(initialReason)
onClose?.()
}
diff --git a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts
index 8bf50f047440..8cf3fd4a0399 100644
--- a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts
+++ b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts
@@ -1,15 +1,22 @@
-import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'
+import {
+ MOCK_DEFAULT_BASIC_USER,
+ MOCK_DEFAULT_ORGANIZATION,
+ MOCK_DEFAULT_ORGANIZATION_MEMBER,
+ MOCK_DEFAULT_USER,
+} from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
import { lemonToast } from '@posthog/lemon-ui'
+import { OrganizationMembershipLevel } from 'lib/constants'
+import { membersLogic } from 'scenes/organization/membersLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { userLogic } from 'scenes/userLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { Region, UserType } from '~/types'
+import { OrganizationMemberType, Region, UserType } from '~/types'
import { impersonationNoticeLogic } from './impersonationNoticeLogic'
@@ -35,6 +42,28 @@ const MOCK_IMPERSONATED_USER: UserType = {
},
}
+function mockMember(
+ firstName: string,
+ level: OrganizationMembershipLevel,
+ id: number,
+ uuid: string
+): OrganizationMemberType {
+ return {
+ ...MOCK_DEFAULT_ORGANIZATION_MEMBER,
+ id: `member-${id}`,
+ user: {
+ ...MOCK_DEFAULT_BASIC_USER,
+ id,
+ uuid,
+ first_name: firstName,
+ last_name: '',
+ distinct_id: `distinct-${id}`,
+ email: `${firstName.toLowerCase()}@example.com`,
+ },
+ level,
+ }
+}
+
describe('impersonationNoticeLogic', () => {
let logic: ReturnType<typeof impersonationNoticeLogic.build>
@@ -43,6 +72,7 @@ describe('impersonationNoticeLogic', () => {
get: {
'/api/users/@me/': () => [200, MOCK_DEFAULT_USER],
'/admin/auth_check': () => [200, {}],
+ '/api/organizations/:org/members/': () => [200, { results: [], count: 0 }],
},
post: {
'/admin/login/user/:id/': () => [200, {}],
@@ -50,6 +80,7 @@ describe('impersonationNoticeLogic', () => {
})
initKeaTests()
userLogic.mount()
+ membersLogic.mount()
logic = impersonationNoticeLogic()
logic.mount()
})
@@ -651,4 +682,162 @@ describe('impersonationNoticeLogic', () => {
expect(lemonToast.success).not.toHaveBeenCalled()
})
})
+
+ describe('changeableMembers selector', () => {
+ it('groups by power descending then names A→Z, excluding the impersonated user', async () => {
+ userLogic.actions.loadUserSuccess(MOCK_IMPERSONATED_USER)
+
+ // MOCK_IMPERSONATED_USER shares MOCK_DEFAULT_USER's uuid, so this member must be excluded.
+ const impersonatedSelf = mockMember('Self', OrganizationMembershipLevel.Owner, 1, MOCK_DEFAULT_USER.uuid)
+
+ membersLogic.actions.loadAllMembersSuccess([
+ mockMember('Zara', OrganizationMembershipLevel.Owner, 10, 'uuid-zara'),
+ mockMember('Anna', OrganizationMembershipLevel.Owner, 11, 'uuid-anna'),
+ mockMember('Yvonne', OrganizationMembershipLevel.Admin, 12, 'uuid-yvonne'),
+ mockMember('Bob', OrganizationMembershipLevel.Admin, 13, 'uuid-bob'),
+ mockMember('Xavier', OrganizationMembershipLevel.Member, 14, 'uuid-xavier'),
+ mockMember('Cara', OrganizationMembershipLevel.Member, 15, 'uuid-cara'),
+ impersonatedSelf,
+ ])
+
+ const names = logic.values.changeableMembers.map((member) => member.user.first_name)
+ expect(names).toEqual(['Anna', 'Zara', 'Bob', 'Yvonne', 'Cara', 'Xavier'])
+ })
+
+ it('returns an empty list when members have not loaded', async () => {
+ await expectLogic(logic).toMatchValues({ changeableMembers: [] })
+ })
+ })
+
+ describe('changeUser listener', () => {
+ function mockLocationReload(): { reload: jest.Mock; restore: () => void } {
+ const originalLocation = window.location
+ const reload = jest.fn()
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: { ...originalLocation, reload },
+ })
+ return {
+ reload,
+ restore: () =>
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: originalLocation,
+ }),
+ }
+ }
+
+ it.each([
+ { readOnly: true, expected: 'true' },
+ { readOnly: false, expected: 'false' },
+ ])('sends read_only=$expected matching the current mode', async ({ readOnly, expected }) => {
+ userLogic.actions.loadUserSuccess({
+ ...MOCK_IMPERSONATED_USER,
+ is_impersonated_read_only: readOnly,
+ })
+
+ const fetchSpy = jest.spyOn(globalThis, 'fetch')
+ const { reload, restore } = mockLocationReload()
+
+ useMocks({
+ get: {
+ '/admin/auth_check': () => [200, {}],
+ '/api/users/@me/': () => [200, MOCK_IMPERSONATED_USER],
+ },
+ post: {
+ '/admin/login/user/:id/': () => [200, {}],
+ },
+ })
+
+ try {
+ await expectLogic(logic, () => {
+ logic.actions.changeUser(456, 'support ticket #123')
+ }).toFinishAllListeners()
+
+ const loginCall = fetchSpy.mock.calls.find(
+ ([url]) => typeof url === 'string' && url.includes('/admin/login/user/456/')
+ )
+ expect(loginCall).toBeTruthy()
+ const body = new URLSearchParams(loginCall![1]?.body as string)
+ expect(body.get('reason')).toBe('support ticket #123')
+ expect(body.get('read_only')).toBe(expected)
+ expect(reload).toHaveBeenCalled()
+ } finally {
+ restore()
+ fetchSpy.mockRestore()
+ }
+ })
+
+ it('uses an explicitly passed reason over the persisted one', async () => {
+ userLogic.actions.loadUserSuccess({ ...MOCK_IMPERSONATED_USER, is_impersonated_reason: 'persisted reason' })
+
+ const fetchSpy = jest.spyOn(globalThis, 'fetch')
+ const { restore } = mockLocationReload()
+
+ try {
+ await expectLogic(logic, () => {
+ logic.actions.changeUser(456, 'fresh reason')
+ }).toFinishAllListeners()
+
+ const loginCall = fetchSpy.mock.calls.find(
+ ([url]) => typeof url === 'string' && url.includes('/admin/login/user/456/')
+ )
+ const body = new URLSearchParams(loginCall![1]?.body as string)
+ expect(body.get('reason')).toBe('fresh reason')
+ } finally {
+ restore()
+ fetchSpy.mockRestore()
+ }
+ })
+
+ it('does not call the endpoint when no reason is available', async () => {
+ userLogic.actions.loadUserSuccess(MOCK_IMPERSONATED_USER)
+ const fetchSpy = jest.spyOn(globalThis, 'fetch')
+
+ await expectLogic(logic, () => {
+ logic.actions.changeUser(456)
+ })
+ .toDispatchActions(['changeUserFailure'])
+ .toFinishAllListeners()
+ .toMatchValues({ isChangingUser: false })
+
+ const loginCall = fetchSpy.mock.calls.find(
+ ([url]) => typeof url === 'string' && url.includes('/admin/login/user/')
+ )
+ expect(loginCall).toBeUndefined()
+ expect(lemonToast.error).toHaveBeenCalled()
+ fetchSpy.mockRestore()
+ })
+
+ it('shows an error toast and resets state on failure', async () => {
+ userLogic.actions.loadUserSuccess(MOCK_IMPERSONATED_USER)
+
+ const { reload, restore } = mockLocationReload()
+
+ useMocks({
+ get: {
+ '/admin/auth_check': () => [200, {}],
+ },
+ post: {
+ '/admin/login/user/:id/': () => [403, { detail: 'Forbidden' }],
+ },
+ })
+
+ try {
+ await expectLogic(logic, () => {
+ logic.actions.changeUser(456, 'support ticket #123')
+ })
+ .toDispatchActions(['changeUserFailure'])
+ .toFinishAllListeners()
+ .toMatchValues({ isChangingUser: false })
+
+ expect(lemonToast.error).toHaveBeenCalled()
+ expect(reload).not.toHaveBeenCalled()
+ } finally {
+ restore()
+ }
+ })
+ })
})
diff --git a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.ts b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.ts
index 61442e385d29..7d9ef8852a09 100644
--- a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.ts
+++ b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.ts
@@ -6,9 +6,11 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { CLOUD_HOSTNAMES } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
+import { fullName } from 'lib/utils/strings'
+import { membersLogic } from 'scenes/organization/membersLogic'
import { userLogic } from 'scenes/userLogic'
-import { Region, UserType } from '~/types'
+import { OrganizationMemberType, Region, UserType } from '~/types'
import { adminLoginAs } from './adminLoginAs'
import type { impersonationNoticeLogicType } from './impersonationNoticeLogicType'
@@ -20,6 +22,9 @@ export interface ExpiredSessionInfo {
// /api/users/@me/ response represents an actual renewal, not the same
// already-expired session echoing back.
isImpersonatedUntil: string | null
+ // Snapshotted at expiry so the re-impersonate modal can pre-fill it; the live
+ // user object may change while the overlay is open.
+ reason?: string | null
}
export interface ImpersonationTicketContext {
@@ -47,8 +52,13 @@ export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([
path(['layout', 'navigation', 'ImpersonationNotice', 'impersonationNoticeLogic']),
connect(() => ({
- values: [userLogic, ['user', 'isImpersonationUpgradeInProgress']],
- actions: [userLogic, ['upgradeImpersonation', 'upgradeImpersonationSuccess', 'loadUser', 'loadUserSuccess']],
+ values: [userLogic, ['user', 'isImpersonationUpgradeInProgress'], membersLogic, ['members', 'membersLoading']],
+ actions: [
+ userLogic,
+ ['upgradeImpersonation', 'upgradeImpersonationSuccess', 'loadUser', 'loadUserSuccess'],
+ membersLogic,
+ ['ensureAllMembersLoaded'],
+ ],
})),
actions({
@@ -62,6 +72,8 @@ export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([
setSessionExpired: (info: ExpiredSessionInfo | null) => ({ info }),
reImpersonate: (reason: string, readOnly: boolean) => ({ reason, readOnly }),
reImpersonateFailure: (error: string) => ({ error }),
+ changeUser: (userId: number, reason?: string) => ({ userId, reason }),
+ changeUserFailure: (error: string) => ({ error }),
returnToPostHog: true,
}),
@@ -109,6 +121,13 @@ export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([
setSessionExpired: () => false,
},
],
+ isChangingUser: [
+ false,
+ {
+ changeUser: () => true,
+ changeUserFailure: () => false,
+ },
+ ],
}),
selectors({
@@ -128,6 +147,29 @@ export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([
},
],
isSessionExpired: [(s) => [s.expiredSessionInfo], (info: ExpiredSessionInfo | null): boolean => info !== null],
+ changeableMembers: [
+ (s) => [s.members, s.user],
+ (members: OrganizationMemberType[] | null, user: UserType | null): OrganizationMemberType[] => {
+ if (!members) {
+ return []
+ }
+ return members
+ .filter((member) => member.user.uuid !== user?.uuid)
+ .slice()
+ .sort((a, b) => {
+ // Higher-power levels first (Owner > Admin > Member).
+ if (a.level !== b.level) {
+ return b.level - a.level
+ }
+ // Then names A→Z within each level group.
+ const nameComparison = fullName(a.user).localeCompare(fullName(b.user))
+ if (nameComparison !== 0) {
+ return nameComparison
+ }
+ return a.user.uuid.localeCompare(b.user.uuid)
+ })
+ },
+ ],
}),
listeners(({ actions, values }) => ({
@@ -156,6 +198,26 @@ export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([
actions.reImpersonateFailure(errorMessage)
}
},
+ changeUser: async ({ userId, reason }) => {
+ // The confirm modal guarantees a non-empty reason, but guard anyway so we never
+ // POST an empty one (the backend rejects it).
+ const resolvedReason = reason?.trim()
+ if (!resolvedReason) {
+ lemonToast.error('A reason is required to change user')
+ actions.changeUserFailure('A reason is required to change user')
+ return
+ }
+
+ try {
+ await adminLoginAs({ userId, reason: resolvedReason, readOnly: values.isReadOnly })
+ // Full reload so org/project/scene state resets for the newly impersonated user.
+ window.location.reload()
+ } catch (e) {
+ const errorMessage = e instanceof Error ? e.message : 'Failed to change user'
+ lemonToast.error(errorMessage)
+ actions.changeUserFailure(errorMessage)
+ }
+ },
loadUserSuccess: ({ user }) => {
const { expiredSessionInfo } = values
if (!expiredSessionInfo) {
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 4cf8eedb3867..a4f61ebdeb06 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -354,6 +354,7 @@ export interface UserType extends UserBaseType {
is_impersonated: boolean
is_impersonated_until?: string
is_impersonated_read_only?: boolean
+ is_impersonated_reason?: string | null
sensitive_session_expires_at: string
organization: OrganizationType | null
team: TeamBasicType | null
diff --git a/posthog/api/user.py b/posthog/api/user.py
index 8603fcd07a0c..b1932d6c41f3 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -78,7 +78,11 @@ from posthog.exceptions_capture import capture_exception
from posthog.helpers.email_utils import EmailNormalizer, validate_display_name
from posthog.helpers.session_cache import SessionCache
from posthog.helpers.two_factor_session import has_passkeys, set_two_factor_verified_in_session
-from posthog.middleware import get_impersonated_session_expires_at, is_read_only_impersonation
+from posthog.middleware import (
+ IMPERSONATION_REASON_SESSION_KEY,
+ get_impersonated_session_expires_at,
+ is_read_only_impersonation,
+)
from posthog.models import OrganizationInvite, Team, User, UserScenePersonalisation
from posthog.models.onboarding_delegation import cancel_pending_delegation, clear_delegation_state
from posthog.models.organization import Organization, OrganizationMembership
@@ -196,6 +200,9 @@ class UserSerializer(serializers.ModelSerializer):
is_impersonated = serializers.SerializerMethodField()
is_impersonated_until = serializers.SerializerMethodField()
is_impersonated_read_only = serializers.SerializerMethodField()
+ is_impersonated_reason = serializers.SerializerMethodField(
+ help_text="The reason the operator gave when the current impersonation session started (or was last up/downgraded). Null when not impersonating."
+ )
sensitive_session_expires_at = serializers.SerializerMethodField()
is_2fa_enabled = serializers.SerializerMethodField()
has_social_auth = serializers.SerializerMethodField()
@@ -277,6 +284,7 @@ class UserSerializer(serializers.ModelSerializer):
"is_impersonated",
"is_impersonated_until",
"is_impersonated_read_only",
+ "is_impersonated_reason",
"sensitive_session_expires_at",
"team",
"organization",
@@ -321,6 +329,7 @@ class UserSerializer(serializers.ModelSerializer):
"is_impersonated",
"is_impersonated_until",
"is_impersonated_read_only",
+ "is_impersonated_reason",
"sensitive_session_expires_at",
"team",
"organization",
@@ -372,6 +381,11 @@ class UserSerializer(serializers.ModelSerializer):
return None
return is_read_only_impersonation(self.context["request"])
+ def get_is_impersonated_reason(self, _) -> Optional[str]:
+ if "request" not in self.context or not is_impersonated_session(self.context["request"]):
+ return None
+ return self.context["request"].session.get(IMPERSONATION_REASON_SESSION_KEY) or None
+
def get_sensitive_session_expires_at(self, instance: User) -> Optional[str]:
if "request" not in self.context:
return None
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 7b64ba551ea3..3b5bd555a3e2 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -1354,6 +1354,11 @@ class ActiveOrganizationMiddleware:
# Session key used to mark an impersonation session as read-only
IMPERSONATION_READ_ONLY_SESSION_KEY = "impersonation_read_only"
+# Session key holding the reason the operator gave when impersonation started (or was
+# up/downgraded). Persisted server-side so the reason survives both Django-admin and
+# in-app starts and can be surfaced to the frontend and the activity log.
+IMPERSONATION_REASON_SESSION_KEY = "impersonation_reason"
+
def is_read_only_impersonation(request: HttpRequest) -> bool:
"""Check if the current session is a read-only impersonation session."""
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 7bbeed55c0d1..785cee01aa8f 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -830,6 +830,31 @@ class TestImpersonationReadOnlyMiddleware(APIBaseTest):
response = self.client.get(f"/api/projects/{self.team.id}/dashboards/")
assert response.status_code == 200
+ def test_reimpersonating_same_user_read_write_clears_read_only(self):
+ self.login_as_other_user_read_only()
+ assert self.client.get("/api/users/@me/").json()["is_impersonated_read_only"] is True
+
+ # Re-impersonating the same user reuses the session (Django only flushes on a user change),
+ # so the start must clear the prior read-only flag instead of silently forcing read-only.
+ self.login_as_other_user()
+ assert self.client.get("/api/users/@me/").json()["is_impersonated_read_only"] is False
+
+ def test_rejected_reimpersonation_preserves_read_only_and_reason(self):
+ self.login_as_other_user_read_only()
+ assert self.client.get("/api/users/@me/").json()["is_impersonated_read_only"] is True
+
+ # An empty reason is rejected by loginas without changing the session (it redirects back to
+ # the referer). The rejected attempt must not clear the active read-only flag or its reason.
+ self.client.post(
+ reverse("loginas-user-login", kwargs={"user_id": self.other_user.id}),
+ data={"read_only": "false", "reason": ""},
+ HTTP_REFERER="/some/page",
+ )
+
+ user = self.client.get("/api/users/@me/").json()
+ assert user["is_impersonated_read_only"] is True
+ assert user["is_impersonated_reason"] == "Test read-only impersonation"
+
@parameterized.expand(
[
("query", "query/", {"query": {"kind": "EventsQuery", "select": ["event"]}}),
@@ -1469,6 +1494,10 @@ class TestUpgradeImpersonation(APIBaseTest):
user_response = self.client.get("/api/users/@me/")
assert user_response.json()["is_impersonated_read_only"] is False
+ def test_start_exposes_reason_on_user_api(self):
+ self.login_as_read_only()
+ assert self.client.get("/api/users/@me/").json()["is_impersonated_reason"] == "Initial read-only impersonation"
+
def test_upgrade_returns_404_when_not_impersonated(self):
response = self.client.post(
reverse("impersonation-upgrade"),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a93ccf595172..a9e0fa54d0e4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -39113,6 +39113,11 @@ export namespace Schemas {
readonly is_impersonated_until: string | null;
/** @nullable */
readonly is_impersonated_read_only: boolean | null;
+ /**
+ * The reason the operator gave when the current impersonation session started (or was last up/downgraded). Null when not impersonating.
+ * @nullable
+ */
+ readonly is_impersonated_reason: string | null;
/** @nullable */
readonly sensitive_session_expires_at: string | null;
readonly team: TeamBasic;
@@ -46484,6 +46489,11 @@ export namespace Schemas {
readonly is_impersonated_until?: string | null;
/** @nullable */
readonly is_impersonated_read_only?: boolean | null;
+ /**
+ * The reason the operator gave when the current impersonation session started (or was last up/downgraded). Null when not impersonating.
+ * @nullable
+ */
+ readonly is_impersonated_reason?: string | null;
/** @nullable */
readonly sensitive_session_expires_at?: string | null;
readonly team?: TeamBasic;