: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(frontend): load two factor status only when needed (#106257)
Paul D'Ambra6503af836ab1
diff --git a/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.test.ts b/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.test.tsindex 6545f97f2ebc..9b916eb0cb84 100644--- a/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.test.ts+++ b/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.test.ts@@ -6,6 +6,70 @@ import { initKeaTests } from '~/test/init'import { twoFactorLogic } from './twoFactorLogic'describe('twoFactorLogic', () => {+ it('loads the 2FA status on first read of status, not on mount', async () => {+ const statusRequest = jest.fn(() => [200, { is_enabled: true, backup_codes_remaining: 3 }])+ useMocks({ get: { '/api/users/@me/two_factor_status/': statusRequest } })+ initKeaTests()+ const logic = twoFactorLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(statusRequest).not.toHaveBeenCalled()++ await expectLogic(logic, () => {+ void logic.values.status+ }).toDispatchActions(['loadStatusSuccess'])++ expect(statusRequest).toHaveBeenCalledTimes(1)+ expect(logic.values.status).toMatchObject({ is_enabled: true, backup_codes_remaining: 3 })+ })++ it('flags a failed status load and clears the flag when a retry succeeds', async () => {+ const statusRequest = jest+ .fn()+ .mockReturnValueOnce([500, {}])+ .mockReturnValue([200, { is_enabled: false, backup_codes_remaining: 0 }])+ useMocks({ get: { '/api/users/@me/two_factor_status/': statusRequest } })+ initKeaTests()+ const logic = twoFactorLogic()+ logic.mount()++ await expectLogic(logic, () => {+ void logic.values.status+ }).toDispatchActions(['loadStatusFailure'])+ expect(logic.values).toMatchObject({ status: null, statusLoadFailed: true })++ await expectLogic(logic, () => {+ logic.actions.loadStatus()+ }).toDispatchActions(['loadStatusSuccess'])+ expect(logic.values.statusLoadFailed).toBe(false)+ })++ it('shows the new backup code count after generating codes without refetching the status', async () => {+ const statusRequest = jest.fn(() => [200, { is_enabled: true, backup_codes_remaining: 1 }])+ useMocks({+ get: { '/api/users/@me/two_factor_status/': statusRequest },+ post: {+ '/api/users/@me/two_factor_backup_codes/': () => [200, { backup_codes: ['c0ffee01', 'c0ffee02'] }],+ },+ })+ initKeaTests()+ const logic = twoFactorLogic()+ logic.mount()+ // Reading the status is what loads it, as the 2FA settings do.+ await expectLogic(logic, () => {+ void logic.values.status+ }).toDispatchActions(['loadStatusSuccess'])++ await expectLogic(logic, () => {+ logic.actions.generateBackupCodes()+ })+ .toDispatchActions(['generateBackupCodesSuccess'])+ .toFinishAllListeners()++ expect(logic.values.status?.backup_codes_remaining).toBe(2)+ expect(statusRequest).toHaveBeenCalledTimes(1)+ })+it('never keeps generated backup codes hidden behind a closed modal', async () => {let respond: () => void = () => {}const responded = new Promise<void>((resolve) => (respond = resolve))diff --git a/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.ts b/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.tsindex f6d0a0ff030f..3a69adbdd2a8 100644--- a/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.ts+++ b/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.ts@@ -1,7 +1,7 @@import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, props, reducers, selectors } from 'kea'import { forms } from 'kea-forms'import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'-import { loaders } from 'kea-loaders'+import { lazyLoaders, loaders } from 'kea-loaders'import { lemonToast } from '@posthog/lemon-ui'@@ -11,6 +11,7 @@ import { membersLogic } from 'scenes/organization/membersLogic'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { userLogic } from 'scenes/userLogic'+import { usersTwoFactorStatusRetrieve } from '~/generated/core/api'import type { TwoFactorStatusApi } from '~/generated/core/api.schemas'import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'@@ -55,6 +56,7 @@ export interface twoFactorLogicValues {} | nullstartSetupLoading: booleanstatus: TwoFactorStatusApi | null+ statusLoadFailed: booleanstatusLoading: booleantoken: {token: string@@ -268,7 +270,26 @@ export const twoFactorLogic = kea<twoFactorLogicType>([toggleBackupCodesModal: (open: boolean) => ({ open }),setSetupCallOngoing: (ongoing: boolean) => ({ ongoing }),}),+ // GlobalModals mounts this logic on every page, so the status loads on first read instead of on mount.+ lazyLoaders(() => ({+ status: [+ null as TwoFactorStatusApi | null,+ {+ loadStatus: async () => {+ return await usersTwoFactorStatusRetrieve('@me')+ },+ },+ ],+ })),reducers({+ statusLoadFailed: [+ false,+ {+ loadStatus: () => false,+ loadStatusSuccess: () => false,+ loadStatusFailure: () => true,+ },+ ],isTwoFactorSetupModalOpen: [false,{@@ -321,21 +342,6 @@ export const twoFactorLogic = kea<twoFactorLogicType>([closeTwoFactorSetupModal: (state) => ({ ...state, isOngoing: false }),},],- status: [- null as TwoFactorStatusApi | null,- {- loadStatusSuccess: (_, { status }) => status,- generateBackupCodesSuccess: (state, { generatingCodes }) => {- if (!state) {- return null- }- return {- ...state,- backup_codes_remaining: generatingCodes?.backup_codes.length ?? state.backup_codes_remaining,- }- },- },- ],}),selectors({is2FAEnabled: [(s) => [s.status], (status: TwoFactorStatusApi | null): boolean => !!status?.is_enabled],@@ -365,15 +371,6 @@ export const twoFactorLogic = kea<twoFactorLogicType>([},},],- status: [- null as TwoFactorStatusApi | null,- {- loadStatus: async () => {- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use usersTwoFactorStatusRetrieve() from '~/generated/core/api' instead.- return await api.get<TwoFactorStatusApi>('api/users/@me/two_factor_status/')- },- },- ],generatingCodes: [null as { backup_codes: string[] } | null,{@@ -403,7 +400,7 @@ export const twoFactorLogic = kea<twoFactorLogicType>([},},})),- listeners(({ props, actions }) => ({+ listeners(({ props, actions, values }) => ({submitTokenSuccess: () => {lemonToast.success('2FA method added successfully')actions.loadStatus()@@ -426,8 +423,14 @@ export const twoFactorLogic = kea<twoFactorLogicType>([throw e}},- generateBackupCodesSuccess: () => {+ generateBackupCodesSuccess: ({ generatingCodes }) => {lemonToast.success('Backup codes generated successfully')+ if (values.status && generatingCodes) {+ actions.loadStatusSuccess({+ ...values.status,+ backup_codes_remaining: generatingCodes.backup_codes.length,+ })+ }},closeTwoFactorSetupModal: () => {// Clear the form when closing the modal@@ -436,8 +439,6 @@ export const twoFactorLogic = kea<twoFactorLogicType>([})),afterMount(({ actions, values }) => {- actions.loadStatus()-if (values.user &&values.user.organization?.enforce_2fa &&diff --git a/frontend/src/scenes/settings/user/TwoFactorSettings.tsx b/frontend/src/scenes/settings/user/TwoFactorSettings.tsxindex 584c3245f944..189f975e8155 100644--- a/frontend/src/scenes/settings/user/TwoFactorSettings.tsx+++ b/frontend/src/scenes/settings/user/TwoFactorSettings.tsx@@ -1,7 +1,15 @@import { useActions, useValues } from 'kea'import { IconCheckCircle, IconCopy, IconInfo, IconWarning } from '@posthog/icons'-import { LemonButton, LemonModal, LemonSwitch, Tooltip, lemonToast } from '@posthog/lemon-ui'+import {+ LemonBanner,+ LemonButton,+ LemonModal,+ LemonSkeleton,+ LemonSwitch,+ Tooltip,+ lemonToast,+} from '@posthog/lemon-ui'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { twoFactorLogic } from 'scenes/authentication/two-factor-setup/twoFactorLogic'@@ -11,8 +19,14 @@ import { userLogic } from 'scenes/userLogic'import { UserType } from '~/types'export function TwoFactorSettings(): JSX.Element {- const { status, isDisable2FAModalOpen, isBackupCodesModalOpen, generatingCodes, generatingCodesLoading } =- useValues(twoFactorLogic)+ const {+ status,+ statusLoadFailed,+ isDisable2FAModalOpen,+ isBackupCodesModalOpen,+ generatingCodes,+ generatingCodesLoading,+ } = useValues(twoFactorLogic)const { updateUser } = useActions(userLogic)const { loadMemberUpdates } = useActions(membersLogic)@@ -30,9 +44,22 @@ export function TwoFactorSettings(): JSX.Element {loadMemberUpdates()}- const hasTotp = status?.has_totp ?? false- const hasPasskeys = status?.has_passkeys ?? false- const passkeysEnabled = status?.passkeys_enabled_for_2fa ?? false+ if (!status) {+ return statusLoadFailed ? (+ <LemonBanner type="error" action={{ children: 'Retry', onClick: () => loadStatus() }}>+ Couldn't load your 2FA settings.+ </LemonBanner>+ ) : (+ <div className="space-y-2">+ <LemonSkeleton className="h-6 w-40" />+ <LemonSkeleton className="h-32 w-full" />+ </div>+ )+ }++ const hasTotp = status.has_totp+ const hasPasskeys = status.has_passkeys+ const passkeysEnabled = status.passkeys_enabled_for_2fareturn (<div className="flex flex-col items-start space-y-4">@@ -95,7 +122,7 @@ export function TwoFactorSettings(): JSX.Element {</>) : (<p>- {status?.backup_codes_remaining+ {status.backup_codes_remaining? `You have ${status.backup_codes_remaining} unused backup ${status.backup_codes_remaining === 1 ? 'code' : 'codes'}. Backup codes are only shown once, when you generate them. Generate new codes to replace them.`: "You don't have any unused backup codes. Generate codes to sign in if you lose access to your authentication device."}</p>@@ -105,7 +132,7 @@ export function TwoFactorSettings(): JSX.Element {onClick={() => generateBackupCodes()}loading={generatingCodesLoading}>- {status?.backup_codes_remaining ? 'Generate new codes' : 'Generate backup codes'}+ {status.backup_codes_remaining ? 'Generate new codes' : 'Generate backup codes'}</LemonButton></div></LemonModal>@@ -114,7 +141,7 @@ export function TwoFactorSettings(): JSX.Element {<div className="space-y-1">{/* 2FA Status Indicator */}<div className="mb-4 flex items-center deprecated-space-x-2">- {status?.is_enabled ? (+ {status.is_enabled ? (<><IconCheckCircle color="green" className="text-xl" /><span className="font-medium">2FA enabled</span>