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.

11.5 KB
Raw Blame
import { MakeLogicType, kea, path, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'
import posthog from 'posthog-js'

import api from 'lib/api'
import { ValidatedPasswordResult, validatePassword } from 'lib/components/PasswordStrength'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'

export interface ResponseType {
    success: boolean
    errorCode?: string
    errorDetail?: string
}
export interface ResetResponseType extends ResponseType {
    email?: string
}

export interface ValidatedTokenResponseType extends ResponseType {
    token?: string
    uuid?: string
}

export interface PasswordResetForm {
    password: string
    passwordConfirm: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface passwordResetLogicValues {
    isPasswordResetSubmitting: boolean
    isPasswordResetValid: boolean
    isRequestPasswordResetSubmitting: boolean
    isRequestPasswordResetValid: boolean
    passwordReset: PasswordResetForm
    passwordResetAllErrors: Record<string, any>
    passwordResetChanged: boolean
    passwordResetErrors: DeepPartialMap<PasswordResetForm, ValidationErrorType>
    passwordResetHasErrors: boolean
    passwordResetManualErrors: Record<string, any>
    passwordResetSucceeded: boolean
    passwordResetTouched: boolean
    passwordResetTouches: Record<string, boolean>
    passwordResetValidationErrors: DeepPartialMap<PasswordResetForm, ValidationErrorType>
    requestPasswordReset: {
        email: string
    }
    requestPasswordResetAllErrors: Record<string, any>
    requestPasswordResetChanged: boolean
    requestPasswordResetErrors: DeepPartialMap<
        {
            email: string
        },
        ValidationErrorType
    >
    requestPasswordResetHasErrors: boolean
    requestPasswordResetManualErrors: Record<string, any>
    requestPasswordResetSucceeded: boolean
    requestPasswordResetTouched: boolean
    requestPasswordResetTouches: Record<string, boolean>
    requestPasswordResetValidationErrors: DeepPartialMap<
        {
            email: string
        },
        ValidationErrorType
    >
    showPasswordResetErrors: boolean
    showRequestPasswordResetErrors: boolean
    validatedPassword: ValidatedPasswordResult
    validatedResetToken: ValidatedTokenResponseType | null
    validatedResetTokenLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface passwordResetLogicActions {
    resetPasswordReset: (values?: PasswordResetForm) => {
        values?: PasswordResetForm
    }
    resetRequestPasswordReset: (values?: { email: string }) => {
        values?: {
            email: string
        }
    }
    setPasswordResetManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setPasswordResetValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setPasswordResetValues: (values: DeepPartial<PasswordResetForm>) => {
        values: DeepPartial<PasswordResetForm>
    }
    setRequestPasswordResetManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setRequestPasswordResetValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setRequestPasswordResetValues: (
        values: DeepPartial<{
            email: string
        }>
    ) => {
        values: DeepPartial<{
            email: string
        }>
    }
    submitPasswordReset: () => {
        value: boolean
    }
    submitPasswordResetFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitPasswordResetRequest: (passwordReset: PasswordResetForm) => {
        passwordReset: PasswordResetForm
    }
    submitPasswordResetSuccess: (passwordReset: PasswordResetForm) => {
        passwordReset: PasswordResetForm
    }
    submitRequestPasswordReset: () => {
        value: boolean
    }
    submitRequestPasswordResetFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitRequestPasswordResetRequest: (requestPasswordReset: { email: string }) => {
        requestPasswordReset: {
            email: string
        }
    }
    submitRequestPasswordResetSuccess: (requestPasswordReset: { email: string }) => {
        requestPasswordReset: {
            email: string
        }
    }
    touchPasswordResetField: (key: string) => {
        key: string
    }
    touchRequestPasswordResetField: (key: string) => {
        key: string
    }
    validateResetToken: ({ uuid, token }: { token: string; uuid: string }) => {
        uuid: string
        token: string
    }
    validateResetTokenFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    validateResetTokenSuccess: (
        validatedResetToken:
            | {
                  errorCode: any
                  errorDetail: any
                  success: false
                  token?: undefined
                  uuid?: undefined
              }
            | {
                  errorCode?: undefined
                  errorDetail?: undefined
                  success: true
                  token: string
                  uuid: string
              },
        payload?: {
            uuid: string
            token: string
        }
    ) => {
        validatedResetToken:
            | {
                  errorCode: any
                  errorDetail: any
                  success: false
                  token?: undefined
                  uuid?: undefined
              }
            | {
                  errorCode?: undefined
                  errorDetail?: undefined
                  success: true
                  token: string
                  uuid: string
              }
        payload?: {
            uuid: string
            token: string
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface passwordResetLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        validatedPassword: (passwordReset: PasswordResetForm) => ValidatedPasswordResult
    }
}

export type passwordResetLogicType = MakeLogicType<
    passwordResetLogicValues,
    passwordResetLogicActions,
    Record<string, any>,
    passwordResetLogicMeta
>

export const passwordResetLogic = kea<passwordResetLogicType>([
    path(['scenes', 'authentication', 'password-reset', 'passwordResetLogic']),
    loaders(() => ({
        validatedResetToken: [
            null as ValidatedTokenResponseType | null,
            {
                validateResetToken: async ({ uuid, token }: { uuid: string; token: string }) => {
                    try {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                        await api.get(`api/reset/${uuid}/?token=${token}`)
                        return { success: true, token, uuid }
                    } catch (e: any) {
                        return { success: false, errorCode: e.code, errorDetail: e.detail }
                    }
                },
            },
        ],
    })),
    reducers({
        requestPasswordResetSucceeded: [
            false,
            {
                submitRequestPasswordResetSuccess: () => true,
                resetRequestPasswordReset: () => false,
            },
        ],
        passwordResetSucceeded: [
            false,
            {
                submitPasswordResetSuccess: () => true,
            },
        ],
    }),
    forms(({ values, actions }) => ({
        requestPasswordReset: {
            defaults: {} as unknown as { email: string },
            errors: ({ email }) => ({
                email: !email ? 'Please enter your email to continue' : undefined,
            }),
            submit: async ({ email }, breakpoint) => {
                breakpoint()

                try {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                    await api.create('api/reset/', { email })
                } catch (e: any) {
                    actions.setRequestPasswordResetManualErrors({ email: e.detail ?? 'An error occurred' })
                    posthog.captureException('Failed to reset password', { extra: { error: e } })
                    throw e
                }
            },
        },

        passwordReset: {
            defaults: {} as unknown as PasswordResetForm,
            errors: ({ password, passwordConfirm }) => ({
                password: !password
                    ? 'Please enter your password to continue'
                    : values.validatedPassword.feedback || undefined,
                passwordConfirm: !passwordConfirm
                    ? 'Please confirm your password to continue'
                    : password !== passwordConfirm
                      ? 'Passwords do not match'
                      : undefined,
            }),
            submit: async ({ password }, breakpoint) => {
                await breakpoint(150)

                if (!values.validatedResetToken?.token || !values.validatedResetToken.uuid) {
                    return
                }
                try {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                    const response = await api.create(`api/reset/${values.validatedResetToken.uuid}/`, {
                        password,
                        token: values.validatedResetToken.token,
                    })
                    lemonToast.success('Your password has been changed. Redirecting…')
                    await breakpoint(3000)

                    const url = new URL('/login', window.location.origin)
                    if (response.email) {
                        url.searchParams.set('email', response.email)
                    }
                    window.location.href = url.href // We need the refresh
                } catch (e: any) {
                    actions.setPasswordResetManualErrors({ password: e.detail })
                    throw e
                }
            },
        },
    })),
    selectors({
        validatedPassword: [
            (s) => [s.passwordReset],
            ({ password }): ValidatedPasswordResult => {
                return validatePassword(password)
            },
        ],
    }),
    urlToAction(({ actions }) => ({
        '/reset/:uuid/:token': ({ uuid, token }) => {
            if (token && uuid) {
                actions.validateResetToken({ uuid, token })
            }
        },
        '/reset': (_, { email }) => {
            if (email) {
                actions.setRequestPasswordResetValue('email', email)
            }
        },
    })),
])