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.

12.4 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'

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

import type { UserType } from '../../../types'

// The success screen's `AuthScene__progress` bar (AuthScene.scss) runs a little longer, so the redirect lands before it fills.
export const VERIFY_EMAIL_REDIRECT_DELAY_MS = 2000

type PostVerifyResponse = {
    success: boolean
    requires_2fa?: boolean
    requires_login?: boolean
    requires_sso?: boolean
}

const resolvePostVerifyDefault = (values: {
    user?: { team?: { has_completed_onboarding_for?: Record<string, boolean> } | null } | null
}): string => {
    if (!values.user) {
        return urls.default()
    }
    const completedMap = values.user.team?.has_completed_onboarding_for ?? {}
    const hasCompletedSomething = Object.values(completedMap).some(Boolean)
    return hasCompletedSomething ? urls.default() : urls.onboarding()
}

const redirectToLogin = (message: string): void => {
    const nextUrl = getRelativeNextPath(router.values.searchParams.next, location)
    lemonToast.success(message)
    router.actions.push(urls.login(), nextUrl ? { next: nextUrl } : {})
}

// A verify success without a session (2FA, blocked member, SSO-enforced domain) routes to
// login with a matching toast. Otherwise the user goes straight into the app.
const redirectAfterVerification = (
    response: PostVerifyResponse,
    values: Parameters<typeof resolvePostVerifyDefault>[0]
): void => {
    const nextUrl = getRelativeNextPath(new URLSearchParams(location.search).get('next'), location)
    const loginMessage = response.requires_2fa
        ? 'Email verified! Please log in with your password to complete two-factor authentication.'
        : response.requires_login
          ? 'Email verified! Log in to continue.'
          : response.requires_sso
            ? 'Email verified! Log in with SSO to continue.'
            : null
    if (loginMessage) {
        redirectToLogin(loginMessage)
        return
    }
    // this url is validated in getRelativeNextPath as either being relative or on the same origin
    // nosemgrep: javascript.browser.security.open-redirect.js-open-redirect
    location.href = nextUrl || resolvePostVerifyDefault(values)
}

export interface VerificationResultType {
    success: boolean
    uuid?: string
}

// Pinned: the deep-link login views send these exact values as the `reason` search param
// (ee/partners/stripe/api/provisioning/constants.py, ee/api/agentic_provisioning/constants.py).
export type VerifyEmailReason = 'stripe_deep_link' | 'partner_deep_link'

const VERIFY_EMAIL_REASONS: VerifyEmailReason[] = ['stripe_deep_link', 'partner_deep_link']

const parseVerifyEmailReason = (value: unknown): VerifyEmailReason | null =>
    VERIFY_EMAIL_REASONS.find((reason) => reason === value) ?? null

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface verifyEmailLogicValues {
    user: UserType | null // userLogic
    newlyRequestedVerificationCode: boolean | null
    newlyRequestedVerificationCodeLoading: boolean
    reason: VerifyEmailReason | null
    uuid: string | null
    verificationCode: string
    verificationCodeError: string | null
    verificationEmailSent: boolean
    verificationResult: VerificationResultType | null
    verificationResultLoading: boolean
    view: 'invalid' | 'pending' | 'success' | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface verifyEmailLogicActions {
    requestVerificationCode: (uuid: string) => {
        uuid: string
    }
    requestVerificationCodeFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    requestVerificationCodeSuccess: (
        newlyRequestedVerificationCode: boolean,
        payload?: {
            uuid: string
        }
    ) => {
        newlyRequestedVerificationCode: boolean
        payload?: {
            uuid: string
        }
    }
    setDeepLinkContext: (
        reason: VerifyEmailReason | null,
        verificationEmailSent: boolean
    ) => {
        reason: VerifyEmailReason | null
        verificationEmailSent: boolean
    }
    setUuid: (uuid: string | null) => {
        uuid: string | null
    }
    setVerificationCode: (code: string) => {
        code: string
    }
    setVerificationCodeError: (error: string | null) => {
        error: string | null
    }
    setView: (view: 'invalid' | 'pending' | 'success' | null) => {
        view: 'invalid' | 'pending' | 'success' | null
    }
    submitVerificationCode: () => {
        value: true
    }
    submitVerificationCodeFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    submitVerificationCodeSuccess: (
        verificationResult: VerificationResultType | null,
        payload?: {
            value: true
        }
    ) => {
        verificationResult: VerificationResultType | null
        payload?: {
            value: true
        }
    }
}

export type verifyEmailLogicType = MakeLogicType<verifyEmailLogicValues, verifyEmailLogicActions>

export const verifyEmailLogic = kea<verifyEmailLogicType>([
    path(['scenes', 'authentication', 'verify-email', 'verifyEmailLogic']),
    connect(() => ({ values: [userLogic, ['user']] })),
    actions({
        setView: (view: 'pending' | 'invalid' | 'success' | null) => ({ view }),
        setUuid: (uuid: string | null) => ({ uuid }),
        setDeepLinkContext: (reason: VerifyEmailReason | null, verificationEmailSent: boolean) => ({
            reason,
            verificationEmailSent,
        }),
        requestVerificationCode: (uuid: string) => ({ uuid }),
        setVerificationCode: (code: string) => ({ code }),
        setVerificationCodeError: (error: string | null) => ({ error }),
        submitVerificationCode: true,
    }),
    loaders(({ actions, values }) => ({
        verificationResult: [
            null as VerificationResultType | null,
            {
                submitVerificationCode: async (_, breakpoint) => {
                    const uuid = values.uuid
                    const code = normalizeVerificationCode(values.verificationCode)
                    if (!uuid) {
                        return values.verificationResult
                    }
                    if (!isValidVerificationCode(code)) {
                        actions.setVerificationCodeError('Enter the 6-digit code from your email.')
                        return values.verificationResult
                    }
                    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.
                        const response = await api.create<PostVerifyResponse>(`api/users/verify_email/`, {
                            uuid,
                            code,
                        })
                        clearPendingVerificationEmail()
                        actions.setView('success')
                        await breakpoint(VERIFY_EMAIL_REDIRECT_DELAY_MS)
                        redirectAfterVerification(response, values)
                        return { success: true, uuid }
                    } catch (e: any) {
                        actions.setVerificationCodeError(verificationCodeErrorMessage(e))
                        return values.verificationResult
                    }
                },
            },
        ],
        newlyRequestedVerificationCode: [
            null as boolean | null,
            {
                requestVerificationCode: async ({ uuid }: { uuid: string }) => {
                    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 your email address. Please check your inbox.')
                        // A resend invalidates the previous code, so drop it and its error (the
                        // setVerificationCode reducer clears the error too). The 6-char field is
                        // otherwise full and blocks typing the freshly sent code.
                        actions.setVerificationCode('')
                        actions.setView('pending')
                        return true
                    } catch (e: any) {
                        // Old link emails reach this page for accounts that are already verified, and
                        // the backend won't send them a code, so login is the only way forward.
                        if (e.code === 'already_verified') {
                            redirectToLogin('Your email is already verified. Log in to continue.')
                            return false
                        }
                        if (e.code === 'throttled') {
                            lemonToast.error('You have requested a new code too many times. Please try again later.')
                            return false
                        }
                        lemonToast.error('Requesting a new code failed. Please try again later or contact support.')
                        return false
                    }
                },
            },
        ],
    })),
    reducers({
        view: [
            null as 'pending' | 'invalid' | 'success' | null,
            {
                setView: (_, { view }) => view,
            },
        ],
        uuid: [
            null as string | null,
            {
                setUuid: (_, { uuid }) => uuid,
            },
        ],
        reason: [
            null as VerifyEmailReason | null,
            {
                setDeepLinkContext: (_, { reason }) => reason,
            },
        ],
        verificationEmailSent: [
            true,
            {
                setDeepLinkContext: (_, { verificationEmailSent }) => verificationEmailSent,
                requestVerificationCodeSuccess: (state, { newlyRequestedVerificationCode }) =>
                    newlyRequestedVerificationCode || state,
            },
        ],
        verificationCode: [
            '',
            {
                setVerificationCode: (_, { code }) => code,
            },
        ],
        verificationCodeError: [
            null as string | null,
            {
                setVerificationCode: () => null,
                submitVerificationCode: () => null,
                setVerificationCodeError: (_, { error }) => error,
            },
        ],
    }),
    urlToAction(({ actions }) => {
        const showCodeEntry = ({ uuid }: { uuid?: string }, searchParams: Record<string, any>): void => {
            if (uuid) {
                actions.setUuid(uuid)
                actions.setDeepLinkContext(
                    parseVerifyEmailReason(searchParams.reason),
                    searchParams.email_sent !== 'false'
                )
                actions.setView('pending')
                // Lazy: authStepViewed reads the OAuth cookie through `he`, which every logged-in page would otherwise load.
                void import('scenes/authentication/shared/authStepViewed')
                    .then(({ captureAuthStepViewed }) => captureAuthStepViewed('verify_email', null))
                    .catch(() => {})
            }
        }
        return {
            '/verify_email/:uuid': showCodeEntry,
            // Emails sent before the switch to codes still carry a link with a token. The token no
            // longer verifies, so land the user on the code entry with a resend button.
            '/verify_email/:uuid/:token': showCodeEntry,
            '/verify_email': () => {
                actions.setView('invalid')
            },
        }
    }),
])