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.

6.7 KB
Raw Blame
import { MakeLogicType, actions, kea, path, reducers, useValues } from 'kea'
import { Form, forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'

import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'
import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'
import { AUTH_NOTES } from 'scenes/authentication/shared/authScene/authNotes'
import { AuthScene, AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
import { ERROR_MESSAGES } from 'scenes/authentication/shared/loginErrorMessages'
import { SupportModalButton } from 'scenes/authentication/shared/SupportModalButton'

export interface LoginForm {
    password: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface loginLogicValues {
    generalError: {
        code: string
        detail: string
    } | null
    isLoginSubmitting: boolean
    isLoginValid: boolean
    isSuccess: boolean
    login: LoginForm
    loginAllErrors: Record<string, any>
    loginChanged: boolean
    loginErrors: DeepPartialMap<LoginForm, ValidationErrorType>
    loginHasErrors: boolean
    loginManualErrors: Record<string, any>
    loginTouched: boolean
    loginTouches: Record<string, boolean>
    loginValidationErrors: DeepPartialMap<LoginForm, ValidationErrorType>
    showLoginErrors: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface loginLogicActions {
    clearGeneralError: () => {
        value: true
    }
    resetLogin: (values?: LoginForm) => {
        values?: LoginForm
    }
    setGeneralError: (
        code: string,
        detail: string
    ) => {
        code: string
        detail: string
    }
    setLoginManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setLoginValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setLoginValues: (values: DeepPartial<LoginForm>) => {
        values: DeepPartial<LoginForm>
    }
    setSuccess: () => {
        value: true
    }
    submitLogin: () => {
        value: boolean
    }
    submitLoginFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitLoginRequest: (login: LoginForm) => {
        login: LoginForm
    }
    submitLoginSuccess: (login: LoginForm) => {
        login: LoginForm
    }
    touchLoginField: (key: string) => {
        key: string
    }
}

export type loginLogicType = MakeLogicType<loginLogicValues, loginLogicActions>

export const loginLogic = kea<loginLogicType>([
    path(['exporter', 'ExporterLogin']),
    actions({
        setGeneralError: (code: string, detail: string) => ({ code, detail }),
        clearGeneralError: true,
        setSuccess: true,
    }),
    reducers({
        generalError: [
            null as { code: string; detail: string } | null,
            {
                setGeneralError: (_, error) => error,
                clearGeneralError: () => null,
                setSuccess: () => null, // Clear error on success
            },
        ],
        isSuccess: [
            false,
            {
                setSuccess: () => true,
                clearGeneralError: () => false,
            },
        ],
    }),
    forms(({ actions }) => ({
        login: {
            defaults: { password: '' } as LoginForm,
            errors: ({ password }) => ({
                password: !password ? 'Please enter your password to continue' : undefined,
            }),
            submit: async ({ password }, breakpoint) => {
                breakpoint()
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ password }),
                })
                if (response.status === 200) {
                    actions.setSuccess()
                    window.location.reload()
                } else if (response.status === 429) {
                    actions.setGeneralError('throttled', 'Too many attempts on this link. Wait a minute and try again.')
                } else {
                    actions.setGeneralError(response.statusText, (await response.json()).error)
                }
            },
        },
    })),
])

export interface ExporterLoginProps {
    whitelabel?: boolean
}

export function ExporterLogin(props: ExporterLoginProps): JSX.Element {
    const { isLoginSubmitting, generalError, isSuccess } = useValues(loginLogic())

    return (
        // A white-labelled share shows no PostHog branding, so it drops the corner notes and the logo
        <AuthScene notes={props.whitelabel ? [] : AUTH_NOTES.exporter.default}>
            <AuthSceneCard top={props.whitelabel ? null : undefined} footer={<SupportModalButton />}>
                <AuthCardTitle
                    title="Access share"
                    sub="Don't have a password? Ask the person who shared this with you."
                />
                {generalError && (
                    <AuthBanner variant="danger" className="mb-4">
                        {generalError.detail ||
                            ERROR_MESSAGES[generalError.code] ||
                            'Could not unlock the content. Please try again.'}
                    </AuthBanner>
                )}
                <Form logic={loginLogic} formKey="login" enableFormOnSubmit className="flex flex-col gap-4">
                    <LemonField name="password" label="Password">
                        <LemonInput
                            type="password"
                            className="ph-ignore-input"
                            data-attr="password"
                            placeholder="••••••••••"
                            autoComplete="current-password"
                            fullWidth
                        />
                    </LemonField>
                    <LemonButton
                        type="primary"
                        htmlType="submit"
                        data-attr="password-login"
                        fullWidth
                        center
                        loading={isLoginSubmitting && !isSuccess}
                        size="large"
                    >
                        {isSuccess ? 'Access granted!' : 'Unlock'}
                    </LemonButton>
                </Form>
            </AuthSceneCard>
        </AuthScene>
    )
}