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.

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

import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { isEmail } from 'lib/utils/url'
import { AuthEntry, AuthStep } from 'scenes/authentication/shared/authStepViewed'
import { urls } from 'scenes/urls'

import type { PreflightStatus } from '~/types'

import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import { LoginForm, PrecheckResponseType, loginLogic } from './loginLogic'
import { PendingInvite, maintenanceSignupRedirectUrl, signupLogic } from './signupLogic'

export type AuthAccountPath = 'login' | 'signup'

/** `verify_email` is its own scene, so this page never shows it. */
export type AuthPageStep = Exclude<AuthStep, 'verify_email'>

/** Whether a person without an account may create one with email and password on this page. */
export function canSignUpWithEmail(precheck: PrecheckResponseType, preflight: PreflightStatus | null): boolean {
    // A self-hosted instance that cannot create organizations refuses every signup, so new people
    // there need an invite link. An enforced domain sends everyone through its IdP.
    return !!preflight?.can_create_org && !precheck.sso_enforcement
}

export function hasSingleSignOn(precheck: PrecheckResponseType): boolean {
    return !!precheck.sso_enforcement || precheck.saml_available || !!precheck.oidc_available
}

export function accountPathFor(precheck: PrecheckResponseType, preflight: PreflightStatus | null): AuthAccountPath {
    // Demo signup logs an existing demo user straight in, and demo users have no password to type.
    if (preflight?.demo) {
        return 'signup'
    }
    // A domain with SAML or OIDC lets its IdP create the account, and only the login step offers
    // those buttons. That step links to email signup when `canSignUpWithEmail` allows it.
    if (!canSignUpWithEmail(precheck, preflight) || precheck.saml_available || precheck.oidc_available) {
        return 'login'
    }
    // Only a definite "no account" goes to signup. An unknown answer (a failed precheck) shows the
    // login step, so an existing account is never pushed into creating a second one.
    return precheck.account_exists === false ? 'signup' : 'login'
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface authLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    codeVerificationRequired: boolean // loginLogic
    isPasswordLoginUnavailable: boolean // loginLogic
    login: LoginForm // loginLogic
    precheckResponse: PrecheckResponseType // loginLogic
    preflight: PreflightStatus | null // preflightLogic
    isSignupEmailChecking: boolean // signupLogic
    panel: number // signupLogic
    pendingInvite: PendingInvite | null // signupLogic
    signupEmailError: string | null // signupLogic
    accountExists: boolean | null
    accountPath: AuthAccountPath | null
    awaitingPrecheckFor: string | null
    canSignUpWithEmail: boolean
    emailError: string | null
    emailValidationError: string | null
    entry: AuthEntry
    isEmailSubmitting: boolean
    isLoginPasswordHidden: boolean
    step: AuthPageStep
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface authLogicActions {
    clearGeneralError: () => {
        value: true
    } // loginLogic
    exitCodeVerification: () => {
        value: true
    } // loginLogic
    precheck: (args_0: { autoAttempt?: boolean; email: string }) => {
        autoAttempt?: boolean
        email: string
    } // loginLogic
    precheckSuccess: (
        precheckResponse: PrecheckResponseType,
        payload?:
            | {
                  autoAttempt?: boolean
                  email: string
              }
            | undefined
    ) => {
        payload?: {
            autoAttempt?: boolean
            email: string
        }
        precheckResponse: PrecheckResponseType
    } // loginLogic
    resetLogin: (values?: LoginForm | undefined) => {
        values?: LoginForm
    } // loginLogic
    setLoginValue: (
        key: import('node_modules/kea-forms/lib').FieldName,
        value: any
    ) => {
        name: import('node_modules/kea-forms/lib').FieldName
        value: any
    } // loginLogic
    submitLogin: () => {
        value: boolean
    } // loginLogic
    precheckSignupEmail: (email: string) => {
        email: string
    } // signupLogic
    resetSignupCredentials: () => {
        value: true
    } // signupLogic
    setPanel: (panel: number) => {
        panel: number
    } // signupLogic
    setPendingInvite: (invite: PendingInvite | null) => {
        invite: PendingInvite | null
    } // signupLogic
    setSignupEmailError: (
        error: string | null,
        isTaken?: boolean | undefined
    ) => {
        error: string | null
        isTaken: boolean
    } // signupLogic
    submitSignupPanelAuth: () => {
        value: boolean
    } // signupLogic
    backToEmail: () => {
        value: true
    }
    chooseAccountPath: (
        accountPath: AuthAccountPath,
        accountExists: boolean | null
    ) => {
        accountExists: boolean | null
        accountPath: AuthAccountPath
    }
    continueWithEmail: () => {
        value: true
    }
    setAwaitingPrecheckFor: (email: string | null) => {
        email: string | null
    }
    setEmailValidationError: (error: string | null) => {
        error: string | null
    }
    submitEmailStep: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface authLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        entry: (location: { hash: string; pathname: string; search: string }) => AuthEntry
        step: (
            accountPath: AuthAccountPath | null,
            codeVerificationRequired: boolean,
            panel: number,
            pendingInvite: PendingInvite | null
        ) => AuthPageStep
        canSignUpWithEmail: (precheckResponse: PrecheckResponseType, preflight: PreflightStatus | null) => boolean
        isEmailSubmitting: (awaitingPrecheckFor: string | null, isSignupEmailChecking: boolean) => boolean
        emailError: (emailValidationError: string | null, signupEmailError: string | null) => string | null
        isLoginPasswordHidden: (
            precheckResponse: PrecheckResponseType,
            isPasswordLoginUnavailable: boolean,
            accountExists: boolean | null
        ) => boolean
    }
}

export type authLogicType = MakeLogicType<authLogicValues, authLogicActions, Record<string, any>, authLogicMeta>

/**
 * The scene logic behind both `/login` and `/signup`. The page asks for an email first, and the
 * precheck answer decides whether the person logs in (`loginLogic`) or creates an account
 * (`signupLogic`). The URL only changes the copy.
 */
export const authLogic = kea<authLogicType>([
    path(['scenes', 'authentication', 'auth', 'authLogic']),
    connect(() => ({
        values: [
            preflightLogic,
            ['preflight'],
            featureFlagLogic,
            ['featureFlags'],
            loginLogic,
            ['login', 'codeVerificationRequired', 'precheckResponse', 'isPasswordLoginUnavailable'],
            signupLogic,
            ['panel', 'pendingInvite', 'isSignupEmailChecking', 'signupEmailError'],
        ],
        actions: [
            loginLogic,
            [
                'precheck',
                'precheckSuccess',
                'setLoginValue',
                'resetLogin',
                'submitLogin',
                'clearGeneralError',
                'exitCodeVerification',
            ],
            signupLogic,
            [
                'precheckSignupEmail',
                'setSignupEmailError',
                'setPendingInvite',
                'setPanel',
                'resetSignupCredentials',
                'submitSignupPanelAuth',
            ],
        ],
    })),
    actions({
        continueWithEmail: true,
        submitEmailStep: true,
        setEmailValidationError: (error: string | null) => ({ error }),
        setAwaitingPrecheckFor: (email: string | null) => ({ email }),
        chooseAccountPath: (accountPath: AuthAccountPath, accountExists: boolean | null) => ({
            accountPath,
            accountExists,
        }),
        backToEmail: true,
    }),
    reducers({
        accountPath: [
            null as AuthAccountPath | null,
            {
                chooseAccountPath: (_, { accountPath }) => accountPath,
                backToEmail: () => null,
            },
        ],
        // Whether an account exists for the email, as known when the page chose the path. Null means
        // unknown, such as after a failed precheck. "Log in instead" on a taken email sets true even
        // though the precheck, which matches the exact address, answered false.
        accountExists: [
            null as boolean | null,
            {
                chooseAccountPath: (_, { accountExists }) => accountExists,
                backToEmail: () => null,
            },
        ],
        // The email that Continue submitted. The precheck can also run on its own while the person
        // types, and only an answer for this email moves the page on.
        awaitingPrecheckFor: [
            null as string | null,
            {
                setAwaitingPrecheckFor: (_, { email }) => email,
            },
        ],
        emailValidationError: [
            null as string | null,
            {
                setEmailValidationError: (_, { error }) => error,
            },
        ],
    }),
    selectors({
        entry: [
            () => [router.selectors.location],
            (location: { pathname: string }): AuthEntry => (location.pathname === urls.signup() ? 'signup' : 'login'),
        ],
        step: [
            (s) => [s.accountPath, s.codeVerificationRequired, s.panel, s.pendingInvite],
            (
                accountPath: AuthAccountPath | null,
                codeVerificationRequired: boolean,
                panel: number,
                pendingInvite: PendingInvite | null
            ): AuthPageStep => {
                if (accountPath === 'login') {
                    return codeVerificationRequired ? 'login_code' : 'login'
                }
                if (accountPath === 'signup') {
                    if (pendingInvite) {
                        return 'signup_pending_invite'
                    }
                    if (panel === 1) {
                        return 'signup_credentials'
                    }
                    if (panel === 2) {
                        return 'signup_profile'
                    }
                }
                // Signup panel 0 is this step too: the signup precheck rejected the email, and its
                // error shows under the email field.
                return 'email'
            },
        ],
        canSignUpWithEmail: [
            (s) => [s.precheckResponse, s.preflight],
            (precheckResponse: PrecheckResponseType, preflight: PreflightStatus | null): boolean =>
                canSignUpWithEmail(precheckResponse, preflight),
        ],
        isEmailSubmitting: [
            (s) => [s.awaitingPrecheckFor, s.isSignupEmailChecking],
            (awaitingPrecheckFor: string | null, isSignupEmailChecking: boolean): boolean =>
                awaitingPrecheckFor !== null || isSignupEmailChecking,
        ],
        emailError: [
            (s) => [s.emailValidationError, s.signupEmailError],
            (emailValidationError: string | null, signupEmailError: string | null): string | null =>
                emailValidationError ?? signupEmailError,
        ],
        // A new person reaches the login step on a SAML or OIDC domain, where the IdP creates the account,
        // or where nobody may sign up with email, such as a self-hosted instance with signups off
        isLoginPasswordHidden: [
            (s) => [s.precheckResponse, s.isPasswordLoginUnavailable, s.accountExists],
            (
                precheckResponse: PrecheckResponseType,
                isPasswordLoginUnavailable: boolean,
                accountExists: boolean | null
            ): boolean => !!precheckResponse.sso_enforcement || isPasswordLoginUnavailable || accountExists === false,
        ],
    }),
    listeners(({ actions, values }) => ({
        // The email card is one form, and its submit button finishes whichever path the email took
        submitEmailStep: () => {
            if (values.step === 'login') {
                actions.submitLogin()
            } else if (values.step === 'signup_credentials') {
                actions.submitSignupPanelAuth()
            } else {
                actions.continueWithEmail()
            }
        },
        continueWithEmail: () => {
            const email = values.login.email.trim()
            if (!email) {
                actions.setEmailValidationError('Please enter your email to continue')
                return
            }
            // No `requireTLD`: the backend accepts internationalized TLDs such as `xn--p1ai`
            if (!isEmail(email)) {
                actions.setEmailValidationError('Please use a valid email address')
                return
            }
            if (email !== values.login.email) {
                actions.setLoginValue('email', email)
            }
            actions.clearGeneralError()
            actions.setAwaitingPrecheckFor(email)
            // Continue is an explicit gesture, so a passwordless account with one sign-in method may
            // go straight to its provider (`autoAttempt`).
            actions.precheck({ email, autoAttempt: true })
        },
        precheckSuccess: ({ precheckResponse }) => {
            const email = values.awaitingPrecheckFor
            if (!email || precheckResponse.email !== email) {
                return
            }
            actions.setAwaitingPrecheckFor(null)
            actions.chooseAccountPath(
                accountPathFor(precheckResponse, values.preflight),
                precheckResponse.precheckFailed ? null : (precheckResponse.account_exists ?? null)
            )
        },
        chooseAccountPath: ({ accountPath }) => {
            if (accountPath === 'login') {
                // "Log in instead" on a taken email leaves the signup error behind
                actions.setSignupEmailError(null)
                return
            }
            const email = values.login.email.trim()
            const maintenanceRedirectUrl = maintenanceSignupRedirectUrl(values.preflight, values.featureFlags, email)
            if (maintenanceRedirectUrl) {
                window.location.href = maintenanceRedirectUrl
                return
            }
            // Start from a clean signup state, so an earlier attempt cannot show its panel first
            actions.setPendingInvite(null)
            actions.setPanel(0)
            actions.precheckSignupEmail(email)
        },
        backToEmail: () => {
            actions.exitCodeVerification()
            // A reset also clears the "show errors" state that a rejected password left behind, so the
            // next password field does not open with a red error
            actions.resetLogin({ email: values.login.email, password: '' })
            actions.clearGeneralError()
            actions.setPendingInvite(null)
            actions.setPanel(0)
            // A passkey or password set for the previous email would fail signup with the next one
            actions.resetSignupCredentials()
        },
        setLoginValue: ({ name }) => {
            if (name !== 'email') {
                return
            }
            // A precheck answer that is still on its way describes the previous email
            if (values.awaitingPrecheckFor !== null && values.awaitingPrecheckFor !== values.login.email) {
                actions.setAwaitingPrecheckFor(null)
            }
            // The password field opens under the email field, so editing the email closes it
            if (values.accountPath !== null && ['email', 'login', 'signup_credentials'].includes(values.step)) {
                actions.backToEmail()
            }
            if (values.emailError) {
                actions.setEmailValidationError(null)
                actions.setSignupEmailError(null)
            }
        },
    })),
    urlToAction(({ actions, values }) => {
        // `?email=` gives the `generate_demo_data` command a quick login link. Demo signup is left to
        // `signupLogic`, which signs the demo user in straight away.
        const prefillEmail = (_: Record<string, any>, { email }: Record<string, any>): void => {
            if (email && !(values.preflight?.demo && values.entry === 'signup')) {
                actions.setLoginValue('email', email)
                actions.precheck({ email })
            }
        }
        return { '/login': prefillEmail, '/signup': prefillEmail }
    }),
])