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.

9.3 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'

import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import {
    isValidVerificationCode,
    normalizeVerificationCode,
    verificationCodeErrorMessage,
} from 'scenes/authentication/shared/verificationCode'
import { userLogic } from 'scenes/userLogic'

import type { UserType } from '~/types'

// Each resend increases the wait before the next one. After the last resend the modal
// offers support instead.
export const RESEND_COOLDOWNS_SECONDS = [30, 60]
export const MAX_RESENDS = 2

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface emailChangeVerificationLogicValues {
    user: UserType | null // userLogic
    modalOpen: boolean
    resendCooldown: number
    resendResult: boolean | null
    resendResultLoading: boolean
    resendsUsed: number
    verificationCode: string
    verificationCodeError: string | null
    verificationResult: {
        success: boolean
    } | null
    verificationResultLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface emailChangeVerificationLogicActions {
    loadUser: (resetOnFailure?: boolean | undefined) => {
        resetOnFailure: boolean | undefined
    } // userLogic
    closeModal: () => {
        value: true
    }
    emailChangeStaged: () => {
        value: true
    }
    openModal: () => {
        value: true
    }
    resendCode: () => {
        value: true
    }
    resendCodeFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    resendCodeSuccess: (
        resendResult: boolean | null,
        payload?: {
            value: true
        }
    ) => {
        resendResult: boolean | null
        payload?: {
            value: true
        }
    }
    resendLimitReached: () => {
        value: true
    }
    setVerificationCode: (code: string) => {
        code: string
    }
    setVerificationCodeError: (error: string | null) => {
        error: string | null
    }
    startResendCooldown: (seconds: number) => {
        seconds: number
    }
    submitVerificationCode: () => {
        value: true
    }
    submitVerificationCodeFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    submitVerificationCodeSuccess: (
        verificationResult: {
            success: true
        } | null,
        payload?: {
            value: true
        }
    ) => {
        verificationResult: {
            success: true
        } | null
        payload?: {
            value: true
        }
    }
    tickResendCooldown: () => {
        value: true
    }
}

export type emailChangeVerificationLogicType = MakeLogicType<
    emailChangeVerificationLogicValues,
    emailChangeVerificationLogicActions
>

export const emailChangeVerificationLogic = kea<emailChangeVerificationLogicType>([
    path(['scenes', 'settings', 'user', 'emailChangeVerificationLogic']),
    connect(() => ({
        values: [userLogic, ['user']],
        actions: [userLogic, ['loadUser']],
    })),
    actions({
        openModal: true,
        closeModal: true,
        emailChangeStaged: true,
        setVerificationCode: (code: string) => ({ code }),
        setVerificationCodeError: (error: string | null) => ({ error }),
        submitVerificationCode: true,
        resendCode: true,
        resendLimitReached: true,
        startResendCooldown: (seconds: number) => ({ seconds }),
        tickResendCooldown: true,
    }),
    reducers({
        modalOpen: [
            false,
            {
                openModal: () => true,
                closeModal: () => false,
            },
        ],
        verificationCode: [
            '',
            {
                setVerificationCode: (_, { code }) => code,
                openModal: () => '',
            },
        ],
        verificationCodeError: [
            null as string | null,
            {
                setVerificationCode: () => null,
                submitVerificationCode: () => null,
                setVerificationCodeError: (_, { error }) => error,
                openModal: () => null,
            },
        ],
        resendsUsed: [
            0,
            {
                emailChangeStaged: () => 0,
                resendCodeSuccess: (state, { resendResult }) => (resendResult ? state + 1 : state),
                // A throttled response means the backend budget is spent, whatever this
                // session counted.
                resendLimitReached: () => MAX_RESENDS,
            },
        ],
        resendCooldown: [
            0,
            {
                startResendCooldown: (_, { seconds }) => seconds,
                tickResendCooldown: (state) => Math.max(0, state - 1),
            },
        ],
    }),
    loaders(({ actions, values }) => ({
        verificationResult: [
            null as { success: boolean } | null,
            {
                submitVerificationCode: async () => {
                    const uuid = values.user?.uuid
                    const code = normalizeVerificationCode(values.verificationCode)
                    if (!uuid) {
                        return null
                    }
                    if (!isValidVerificationCode(code)) {
                        actions.setVerificationCodeError('Enter the 6-digit code from your email.')
                        return null
                    }
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. usersVerifyEmailCreate() 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(`api/users/verify_email/`, { uuid, code })
                        actions.closeModal()
                        lemonToast.success('Email address verified.')
                        actions.loadUser()
                        return { success: true }
                    } catch (e: any) {
                        actions.setVerificationCodeError(verificationCodeErrorMessage(e))
                        return null
                    }
                },
            },
        ],
        resendResult: [
            null as boolean | null,
            {
                resendCode: async () => {
                    const uuid = values.user?.uuid
                    if (!uuid || values.resendCooldown > 0 || values.resendsUsed >= MAX_RESENDS) {
                        return null
                    }
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. usersRequestEmailVerificationCreate() 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(`api/users/request_email_verification/`, { uuid })
                        lemonToast.success('We sent a new code to the address pending verification.')
                        return true
                    } catch (e: any) {
                        if (e.code === 'throttled') {
                            actions.resendLimitReached()
                            lemonToast.error('You have requested a new code too many times. Please try again later.')
                        } else {
                            lemonToast.error('Requesting a new code failed. Please try again later.')
                        }
                        return false
                    }
                },
            },
        ],
    })),
    listeners(({ actions, values, cache }) => ({
        emailChangeStaged: () => {
            actions.openModal()
            actions.startResendCooldown(RESEND_COOLDOWNS_SECONDS[0])
        },
        resendCodeSuccess: ({ resendResult }) => {
            if (resendResult && values.resendsUsed < MAX_RESENDS) {
                actions.startResendCooldown(RESEND_COOLDOWNS_SECONDS[values.resendsUsed] ?? 60)
            }
        },
        startResendCooldown: () => {
            cache.disposables.add(
                () => {
                    const intervalId = setInterval(() => actions.tickResendCooldown(), 1000)
                    return () => clearInterval(intervalId)
                },
                'resendCooldown',
                // Keep counting while the user reads their inbox in another tab.
                { pauseOnPageHidden: false }
            )
        },
        tickResendCooldown: () => {
            if (values.resendCooldown <= 0) {
                cache.disposables.dispose('resendCooldown')
            }
        },
    })),
    subscriptions(({ actions }) => ({
        // The form submit action fires before the API response lands. Watch the user object
        // instead: a new pending_email means a change was staged and the code was sent.
        user: (user: UserType | null, oldUser: UserType | null) => {
            if (user?.pending_email && oldUser && oldUser.pending_email !== user.pending_email) {
                actions.emailChangeStaged()
            }
        },
    })),
])