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.3 KB
Raw Blame
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 { lazyLoaders, loaders } from 'kea-loaders'

import { lemonToast } from '@posthog/lemon-ui'

import api from 'lib/api'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { userLogic } from 'scenes/userLogic'

import { usersTwoFactorStatusRetrieve } from '~/generated/core/api'
import type { TwoFactorStatusApi } from '~/generated/core/api.schemas'
import { membersLogic } from '~/models/membersLogic'

import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { PreflightStatus, UserType } from '../../../types'

export interface TwoFactorForm {
    token: string
}

export interface TwoFactorLogicProps {
    onSuccess?: () => void
}

// The 2FA and SSO fields are absent until the app context's full stage arrives, and absent is not false.
function mustSetUpTwoFactor(user: UserType | null): boolean {
    return (
        !!user?.organization?.enforce_2fa &&
        user.is_2fa_enabled === false &&
        user.has_sso_enforcement === false &&
        !user.is_impersonated &&
        !user.has_social_auth
    )
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface twoFactorLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    preflight: PreflightStatus | null // preflightLogic
    user: UserType | null // userLogic
    canSwitchOrg: boolean
    forceOpenTwoFactorSetupModal: boolean
    generalError: {
        code: string
        detail: string
    } | null
    generatingCodes: {
        backup_codes: string[]
    } | null
    generatingCodesLoading: boolean
    is2FAEnabled: boolean
    isBackupCodesModalOpen: boolean
    isDisable2FAModalOpen: boolean
    isTokenSubmitting: boolean
    isTokenValid: boolean
    isTwoFactorSetupModalOpen: boolean
    setupCallState: {
        isOngoing: boolean
    }
    showTokenErrors: boolean
    startSetup: {
        secret: string
        success: boolean
    } | null
    startSetupLoading: boolean
    status: TwoFactorStatusApi | null
    statusLoadFailed: boolean
    statusLoading: boolean
    token: {
        token: string
    }
    tokenAllErrors: Record<string, any>
    tokenChanged: boolean
    tokenErrors: DeepPartialMap<
        {
            token: string
        },
        ValidationErrorType
    >
    tokenHasErrors: boolean
    tokenManualErrors: Record<string, any>
    tokenTouched: boolean
    tokenTouches: Record<string, boolean>
    tokenValidationErrors: DeepPartialMap<
        {
            token: string
        },
        ValidationErrorType
    >
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface twoFactorLogicActions {
    loadAllMembers: () => {
        value: true
    } // membersLogic
    addFullStageUserFieldsSuccess: (
        user: UserType | null,
        payload?:
            | {
                  fields: Partial<UserType>
              }
            | undefined
    ) => {
        payload?: {
            fields: Partial<UserType>
        }
        user: UserType | null
    } // userLogic
    loadUser: (resetOnFailure?: boolean | undefined) => {
        resetOnFailure: boolean | undefined
    } // userLogic
    clearGeneralError: () => {
        value: true
    }
    closeTwoFactorSetupModal: () => {
        value: true
    }
    disable2FA: () => {
        value: true
    }
    generateBackupCodes: () => {
        value: true
    }
    generateBackupCodesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    generateBackupCodesSuccess: (
        generatingCodes: {
            backup_codes: string[]
        } | null,
        payload?: {
            value: true
        }
    ) => {
        generatingCodes: {
            backup_codes: string[]
        } | null
        payload?: {
            value: true
        }
    }
    loadStatus: () => {
        value: true
    }
    loadStatusFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadStatusSuccess: (
        status: TwoFactorStatusApi,
        payload?: {
            value: true
        }
    ) => {
        status: TwoFactorStatusApi
        payload?: {
            value: true
        }
    }
    openTwoFactorSetupModal: (forceOpen?: boolean) => {
        forceOpen: boolean | undefined
    }
    openTwoFactorSetupModalFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    openTwoFactorSetupModalSuccess: (
        startSetup: {
            secret: string
            success: boolean
        } | null,
        payload?: {
            forceOpen: boolean | undefined
        }
    ) => {
        startSetup: {
            secret: string
            success: boolean
        } | null
        payload?: {
            forceOpen: boolean | undefined
        }
    }
    resetToken: (values?: { token: string }) => {
        values?: {
            token: string
        }
    }
    setGeneralError: (
        code: string,
        detail: string
    ) => {
        code: string
        detail: string
    }
    setSetupCallOngoing: (ongoing: boolean) => {
        ongoing: boolean
    }
    setTokenManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setTokenValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setTokenValues: (
        values: DeepPartial<{
            token: string
        }>
    ) => {
        values: DeepPartial<{
            token: string
        }>
    }
    submitToken: () => {
        value: boolean
    }
    submitTokenFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitTokenRequest: (token: { token: string }) => {
        token: {
            token: string
        }
    }
    submitTokenSuccess: (token: { token: string }) => {
        token: {
            token: string
        }
    }
    toggleBackupCodesModal: (open: boolean) => {
        open: boolean
    }
    toggleDisable2FAModal: (open: boolean) => {
        open: boolean
    }
    touchTokenField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface twoFactorLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        is2FAEnabled: (status: TwoFactorStatusApi | null) => boolean
        canSwitchOrg: (user: UserType | null) => boolean
    }
}

export type twoFactorLogicType = MakeLogicType<
    twoFactorLogicValues,
    twoFactorLogicActions,
    TwoFactorLogicProps,
    twoFactorLogicMeta
>

export const twoFactorLogic = kea<twoFactorLogicType>([
    path(['scenes', 'authentication', 'two-factor-setup', 'twoFactorLogic']),
    props({} as TwoFactorLogicProps),
    connect(() => ({
        values: [preflightLogic, ['preflight'], featureFlagLogic, ['featureFlags'], userLogic, ['user']],
        actions: [userLogic, ['loadUser', 'addFullStageUserFieldsSuccess'], membersLogic, ['loadAllMembers']],
    })),
    actions({
        setGeneralError: (code: string, detail: string) => ({ code, detail }),
        clearGeneralError: true,
        loadStatus: true,
        generateBackupCodes: true,
        disable2FA: true,
        openTwoFactorSetupModal: (forceOpen?: boolean) => ({ forceOpen }),
        closeTwoFactorSetupModal: true,
        toggleDisable2FAModal: (open: boolean) => ({ open }),
        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,
            {
                openTwoFactorSetupModal: () => true,
                closeTwoFactorSetupModal: () => false,
            },
        ],
        forceOpenTwoFactorSetupModal: [
            false,
            {
                openTwoFactorSetupModal: (_, { forceOpen }) => !!forceOpen,
                closeTwoFactorSetupModal: () => false,
            },
        ],
        isDisable2FAModalOpen: [
            false,
            {
                toggleDisable2FAModal: (_, { open }) => open,
            },
        ],
        isBackupCodesModalOpen: [
            false,
            {
                toggleBackupCodesModal: (_, { open }) => open,
                // New codes replace the old ones, so a result that lands after close reopens the modal. The
                // user sees them once, and closing again clears them.
                generateBackupCodesSuccess: () => true,
            },
        ],
        generatingCodes: [
            null as { backup_codes: string[] } | null,
            {
                // The backend only returns codes when it generates them, so they leave memory with the modal.
                toggleBackupCodesModal: (state, { open }) => (open ? state : null),
            },
        ],
        generalError: [
            null as { code: string; detail: string } | null,
            {
                setGeneralError: (_, error) => error,
                clearGeneralError: () => null,
            },
        ],
        setupCallState: [
            { isOngoing: false } as { isOngoing: boolean },
            {
                setSetupCallOngoing: (_, { ongoing }) => ({ isOngoing: ongoing }),
                startSetupSuccess: (state) => ({ ...state, isOngoing: false }),
                startSetupFailure: (state) => ({ ...state, isOngoing: false }),
                closeTwoFactorSetupModal: (state) => ({ ...state, isOngoing: false }),
            },
        ],
    }),
    selectors({
        is2FAEnabled: [(s) => [s.status], (status: TwoFactorStatusApi | null): boolean => !!status?.is_enabled],
        canSwitchOrg: [
            (s) => [s.user],
            (user: null | import('../../../types').UserType): boolean => (user?.organizations || []).length > 1,
        ],
    }),
    loaders(({ values, actions }) => ({
        startSetup: [
            null as { secret: string; success: boolean } | null,
            {
                openTwoFactorSetupModal: async (_, breakpoint) => {
                    const { isOngoing } = values.setupCallState

                    if (isOngoing) {
                        return values.startSetup
                    }

                    // We need this to prevent triggering the setup API call multiple times, which breaks the flow
                    actions.setSetupCallOngoing(true)

                    breakpoint()
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. usersTwoFactorStartSetupRetrieve() from '~/generated/core/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                    const response = await api.get('api/users/@me/two_factor_start_setup/')
                    return response
                },
            },
        ],
        generatingCodes: [
            null as { backup_codes: string[] } | null,
            {
                generateBackupCodes: async () => {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. usersTwoFactorBackupCodesCreate() from '~/generated/core/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                    return await api.create<any>('api/users/@me/two_factor_backup_codes/')
                },
            },
        ],
    })),
    forms(({ actions }) => ({
        token: {
            defaults: { token: '' },
            errors: ({ token }) => ({
                token: !token ? 'Please enter a token to continue' : undefined,
            }),
            submit: async ({ token }, breakpoint) => {
                breakpoint()
                try {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. usersTwoFactorValidateCreate() from '~/generated/core/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                    return await api.create<any>('api/users/@me/two_factor_validate/', { token })
                } catch (e) {
                    const { code, detail } = e as Record<string, any>
                    actions.setGeneralError(code, detail)
                    throw e
                }
            },
        },
    })),
    listeners(({ props, actions, values }) => ({
        addFullStageUserFieldsSuccess: ({ user }) => {
            if (mustSetUpTwoFactor(user)) {
                actions.openTwoFactorSetupModal(true)
            }
        },
        submitTokenSuccess: () => {
            lemonToast.success('2FA method added successfully')
            actions.loadStatus()
            props.onSuccess?.()
        },
        disable2FA: async () => {
            try {
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. usersTwoFactorDisableCreate() from '~/generated/core/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                await api.create<any>('api/users/@me/two_factor_disable/')
                lemonToast.success('2FA disabled successfully. The page will reload.')
                actions.loadStatus()

                // Reload to avoid breaking calls on the page if enforce_2fa=True
                setTimeout(() => {
                    window.location.reload()
                }, 3000)
            } catch (e) {
                const { code, detail } = e as Record<string, any>
                actions.setGeneralError(code, detail)
                throw e
            }
        },
        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
            actions.resetToken()
        },
    })),

    afterMount(({ actions, values }) => {
        if (mustSetUpTwoFactor(values.user)) {
            actions.openTwoFactorSetupModal(true)
        }
    }),
])