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.

15.5 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { urlToAction } from 'kea-router'

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 { userLogic } from 'scenes/userLogic'

import { membersLogic } from '~/models/membersLogic'
import { OrganizationMemberType, Region, UserType } from '~/types'

import { adminLoginAs } from './adminLoginAs'

export interface ExpiredSessionInfo {
    email: string
    userId: number
    // Captured when the countdown fired so we can later confirm a fresh
    // /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 {
    ticketId: string
    email: string
    region?: Region
    /** True when no server check attests the email. */
    isEmailUnverified?: boolean
    /** The ticket identity a server check attested. The staff lookup uses it in place of the email. */
    verifiedDistinctId?: string
}

export interface AdminLoginUrl {
    region: Region
    url: string
}

// When a ticket's region is unknown (e.g. tickets opened from a Slack channel
// carry no app URL to infer it from), fall back to offering a lookup in each
// production cloud region rather than no link at all.
const ADMIN_LOOKUP_REGIONS: Region[] = [Region.US, Region.EU]

function adminLoginUrlForRegion(region: Region, userQuery: string): string {
    const domain = CLOUD_HOSTNAMES[region]
    return `https://${domain}/admin/posthog/user/?q=${encodeURIComponent(userQuery)}`
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface impersonationNoticeLogicValues {
    me: OrganizationMemberType | null // membersLogic
    members: OrganizationMemberType[] | null // membersLogic
    membersLoading: boolean // membersLogic
    isImpersonationUpgradeInProgress: boolean // userLogic
    user: UserType | null // userLogic
    adminLoginUrls: AdminLoginUrl[]
    expiredSessionInfo: ExpiredSessionInfo | null
    hasOtherMembers: boolean
    isChangingUser: boolean
    isImpersonated: boolean
    isMinimized: boolean
    isReImpersonating: boolean
    isReadOnly: boolean
    isSessionExpired: boolean
    isUpgradeModalOpen: boolean
    orderedMembers: OrganizationMemberType[]
    pageHiddenAt: number | null
    ticketContext: ImpersonationTicketContext | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface impersonationNoticeLogicActions {
    ensureAllMembersLoaded: () => {
        value: true
    } // membersLogic
    loadUser: (resetOnFailure?: boolean | undefined) => {
        resetOnFailure: boolean | undefined
    } // userLogic
    loadUserSuccess: (
        user: UserType | null,
        payload?:
            | {
                  resetOnFailure: boolean | undefined
              }
            | undefined
    ) => {
        payload?: {
            resetOnFailure: boolean | undefined
        }
        user: UserType | null
    } // userLogic
    upgradeImpersonation: (reason: string) => {
        reason: string
    } // userLogic
    upgradeImpersonationSuccess: (
        user: UserType | null,
        payload?:
            | {
                  reason: string
              }
            | undefined
    ) => {
        payload?: {
            reason: string
        }
        user: UserType | null
    } // userLogic
    changeUser: (
        userId: number,
        reason?: string
    ) => {
        reason: string | undefined
        userId: number
    }
    changeUserFailure: (error: string) => {
        error: string
    }
    clearPageHiddenAt: () => {
        value: true
    }
    closeUpgradeModal: () => {
        value: true
    }
    maximize: () => {
        value: true
    }
    minimize: () => {
        value: true
    }
    openUpgradeModal: () => {
        value: true
    }
    reImpersonate: (
        reason: string,
        readOnly: boolean
    ) => {
        readOnly: boolean
        reason: string
    }
    reImpersonateFailure: (error: string) => {
        error: string
    }
    returnToPostHog: () => {
        value: true
    }
    setPageVisible: (visible: boolean) => {
        visible: boolean
    }
    setSessionExpired: (info: ExpiredSessionInfo | null) => {
        info: ExpiredSessionInfo | null
    }
    setTicketContext: (context: ImpersonationTicketContext | null) => {
        context: ImpersonationTicketContext | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface impersonationNoticeLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        isReadOnly: (user: UserType | null) => boolean
        isImpersonated: (user: UserType | null) => boolean
        adminLoginUrls: (ticketContext: ImpersonationTicketContext | null) => AdminLoginUrl[]
        isSessionExpired: (expiredSessionInfo: ExpiredSessionInfo | null) => boolean
        orderedMembers: (
            members: OrganizationMemberType[] | null,
            me: OrganizationMemberType | null,
            user: UserType | null
        ) => OrganizationMemberType[]
        hasOtherMembers: (orderedMembers: OrganizationMemberType[], user: UserType | null) => boolean
    }
}

export type impersonationNoticeLogicType = MakeLogicType<
    impersonationNoticeLogicValues,
    impersonationNoticeLogicActions,
    Record<string, any>,
    impersonationNoticeLogicMeta
>

export const impersonationNoticeLogic = kea<impersonationNoticeLogicType>([
    path(['layout', 'navigation', 'ImpersonationNotice', 'impersonationNoticeLogic']),

    connect(() => ({
        values: [
            userLogic,
            ['user', 'isImpersonationUpgradeInProgress'],
            membersLogic,
            ['members', 'membersLoading', 'me'],
        ],
        actions: [
            userLogic,
            ['upgradeImpersonation', 'upgradeImpersonationSuccess', 'loadUser', 'loadUserSuccess'],
            membersLogic,
            ['ensureAllMembersLoaded'],
        ],
    })),

    actions({
        minimize: true,
        maximize: true,
        openUpgradeModal: true,
        closeUpgradeModal: true,
        setPageVisible: (visible: boolean) => ({ visible }),
        clearPageHiddenAt: true,
        setTicketContext: (context: ImpersonationTicketContext | null) => ({ context }),
        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,
    }),

    reducers({
        isMinimized: [
            false,
            {
                minimize: () => true,
                maximize: () => false,
            },
        ],
        isUpgradeModalOpen: [
            false,
            {
                openUpgradeModal: () => true,
                closeUpgradeModal: () => false,
            },
        ],
        pageHiddenAt: [
            null as number | null,
            {
                // Store timestamp when page becomes hidden - used to work out if we
                // should auto expand when page regains focus
                setPageVisible: (state, { visible }) => (visible ? state : Date.now()),
                clearPageHiddenAt: () => null,
            },
        ],
        ticketContext: [
            null as ImpersonationTicketContext | null,
            {
                setTicketContext: (_, { context }) => context,
            },
        ],
        expiredSessionInfo: [
            null as ExpiredSessionInfo | null,
            {
                setSessionExpired: (_, { info }) => info,
            },
        ],
        isReImpersonating: [
            false,
            {
                reImpersonate: () => true,
                reImpersonateFailure: () => false,
                setSessionExpired: () => false,
            },
        ],
        isChangingUser: [
            false,
            {
                changeUser: () => true,
                changeUserFailure: () => false,
            },
        ],
    }),

    selectors({
        isReadOnly: [(s) => [s.user], (user: UserType | null): boolean => user?.is_impersonated_read_only ?? true],
        isImpersonated: [(s) => [s.user], (user: UserType | null): boolean => user?.is_impersonated ?? false],
        adminLoginUrls: [
            (s) => [s.ticketContext],
            (ticketContext: ImpersonationTicketContext | null): AdminLoginUrl[] => {
                // The admin user search matches a distinct ID as well as an email.
                const userQuery = ticketContext?.verifiedDistinctId || ticketContext?.email
                if (!ticketContext || !userQuery) {
                    return []
                }
                const regions = ticketContext.region ? [ticketContext.region] : ADMIN_LOOKUP_REGIONS
                return regions.map((region) => ({
                    region,
                    url: adminLoginUrlForRegion(region, userQuery),
                }))
            },
        ],
        isSessionExpired: [(s) => [s.expiredSessionInfo], (info: ExpiredSessionInfo | null): boolean => info !== null],
        // Current user (via me) is shown in place among members, so their row appears before members load.
        orderedMembers: [
            (s) => [s.members, s.me, s.user],
            (
                members: OrganizationMemberType[] | null,
                me: OrganizationMemberType | null,
                user: UserType | null
            ): OrganizationMemberType[] => {
                const others = (members ?? []).filter((member) => member.user.uuid !== user?.uuid)
                return [...(me ? [me] : []), ...others].sort((a, b) => {
                    if (a.level !== b.level) {
                        return b.level - a.level // higher levels first
                    }
                    const nameComparison = fullName(a.user).localeCompare(fullName(b.user))
                    return nameComparison !== 0 ? nameComparison : a.user.uuid.localeCompare(b.user.uuid)
                })
            },
        ],
        hasOtherMembers: [
            (s) => [s.orderedMembers, s.user],
            (orderedMembers: OrganizationMemberType[], user: UserType | null): boolean =>
                orderedMembers.some((member) => member.user.uuid !== user?.uuid),
        ],
    }),

    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()
            }
        },
        reImpersonate: async ({ reason, readOnly }) => {
            const { expiredSessionInfo } = values
            if (!expiredSessionInfo) {
                return
            }

            try {
                await adminLoginAs({ userId: expiredSessionInfo.userId, reason, readOnly })
                actions.loadUser()
            } catch (e) {
                const errorMessage = e instanceof Error ? e.message : 'Failed to re-impersonate'
                lemonToast.error(errorMessage)
                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) {
                return
            }
            if (!user?.is_impersonated || !user.is_impersonated_until) {
                return
            }
            // Only dismiss if the fresh `is_impersonated_until` is strictly after the
            // one we saw when the countdown fired — otherwise the server is echoing
            // back the same stale session that already expired.
            const newUntil = dayjs(user.is_impersonated_until)
            const renewed = expiredSessionInfo.isImpersonatedUntil
                ? newUntil.isAfter(expiredSessionInfo.isImpersonatedUntil)
                : newUntil.isAfter(dayjs())
            if (renewed) {
                actions.setSessionExpired(null)
                lemonToast.success('Impersonation session renewed')
            }
        },
        setPageVisible: async ({ visible }) => {
            if (!visible) {
                return
            }
            if (values.expiredSessionInfo) {
                // Probe /api/users/@me/ directly rather than dispatching loadUser:
                // loadUser's failure path sets user=null, which would unmount the
                // app and the overlay along with it. On success we hand the fetched
                // user to loadUserSuccess ourselves so userLogic stays in sync.
                try {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use usersRetrieve() from '~/generated/core/api' instead.
                    const freshUser = await api.get<UserType>('api/users/@me/')
                    if (freshUser?.is_impersonated) {
                        actions.loadUserSuccess(freshUser)
                    }
                } catch {
                    // 401 or network error — overlay stays; user will pick an action.
                }
            }
            const { pageHiddenAt } = values
            actions.clearPageHiddenAt()
            // Auto-maximize when window regains focus to ensure staff
            // users are reminded they are impersonating a customer
            // Only trigger if away for more than 30 seconds though to
            // avoid being annoying if quickly switching between windows
            if (values.isMinimized && pageHiddenAt) {
                const secondsAway = (Date.now() - pageHiddenAt) / 1000
                if (secondsAway > 30) {
                    actions.maximize()
                }
            }
        },
    })),

    urlToAction(({ actions, values }) => ({
        '*': (_params, _searchParams, _hashParams, { pathname }) => {
            if (values.ticketContext && !pathname.startsWith('/support/tickets/')) {
                actions.setTicketContext(null)
            }
        },
    })),
])