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.

7.3 KB
Raw Blame
import { MakeLogicType, connect, kea, path, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'

import { lemonToast } from '@posthog/lemon-ui'

import api from 'lib/api'
import { ValidatedPasswordResult, validatePassword } from 'lib/components/PasswordStrength'
import { userLogic } from 'scenes/userLogic'

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

export interface ChangePasswordForm {
    current_password: string
    password: string
    confirm_password: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface changePasswordLogicValues {
    user: UserType | null // userLogic
    changePassword: ChangePasswordForm
    changePasswordAllErrors: Record<string, any>
    changePasswordChanged: boolean
    changePasswordErrors: DeepPartialMap<ChangePasswordForm, ValidationErrorType>
    changePasswordHasErrors: boolean
    changePasswordManualErrors: Record<string, any>
    changePasswordTouched: boolean
    changePasswordTouches: Record<string, boolean>
    changePasswordValidationErrors: DeepPartialMap<ChangePasswordForm, ValidationErrorType>
    isChangePasswordSubmitting: boolean
    isChangePasswordValid: boolean
    passwordResetEmailSent: boolean
    passwordResetEmailSentLoading: boolean
    showChangePasswordErrors: boolean
    validatedPassword: ValidatedPasswordResult
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface changePasswordLogicActions {
    loadUser: (resetOnFailure?: boolean | undefined) => {
        resetOnFailure: boolean | undefined
    } // userLogic
    requestPasswordResetEmail: () => any
    requestPasswordResetEmailFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    requestPasswordResetEmailSuccess: (
        passwordResetEmailSent: boolean,
        payload?: any
    ) => {
        passwordResetEmailSent: boolean
        payload?: any
    }
    resetChangePassword: (values?: ChangePasswordForm) => {
        values?: ChangePasswordForm
    }
    setChangePasswordManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setChangePasswordValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setChangePasswordValues: (values: DeepPartial<ChangePasswordForm>) => {
        values: DeepPartial<ChangePasswordForm>
    }
    submitChangePassword: () => {
        value: boolean
    }
    submitChangePasswordFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitChangePasswordRequest: (changePassword: ChangePasswordForm) => {
        changePassword: ChangePasswordForm
    }
    submitChangePasswordSuccess: (changePassword: ChangePasswordForm) => {
        changePassword: ChangePasswordForm
    }
    touchChangePasswordField: (key: string) => {
        key: string
    }
}

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

export type changePasswordLogicType = MakeLogicType<
    changePasswordLogicValues,
    changePasswordLogicActions,
    Record<string, any>,
    changePasswordLogicMeta
>

export const changePasswordLogic = kea<changePasswordLogicType>([
    path(['scenes', 'me', 'settings', 'changePasswordLogic']),
    connect(() => ({
        values: [userLogic, ['user']],
        actions: [userLogic, ['loadUser']],
    })),
    forms(({ values, actions }) => ({
        changePassword: {
            defaults: {} as unknown as ChangePasswordForm,
            errors: ({ current_password, password, confirm_password }) => {
                const hasPassword = values.user?.has_password ?? false
                return {
                    current_password:
                        hasPassword && !current_password ? 'Please enter your current password' : undefined,
                    password: !password
                        ? 'Please enter your password to continue'
                        : values.validatedPassword.feedback || undefined,
                    confirm_password:
                        !hasPassword && !confirm_password
                            ? 'Please confirm your password'
                            : !hasPassword && password !== confirm_password
                              ? 'Passwords do not match'
                              : undefined,
                }
            },
            submit: async ({ password, current_password }, breakpoint) => {
                await breakpoint(150)

                const hasPassword = values.user?.has_password ?? false

                try {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use usersPartialUpdate() from '~/generated/core/api' instead.
                    await api.update('api/users/@me/', {
                        password,
                        ...(hasPassword ? { current_password } : {}),
                    })
                    actions.resetChangePassword({
                        password: '',
                        current_password: '',
                        confirm_password: '',
                    })
                    lemonToast.success(hasPassword ? 'Password changed' : 'Password set')
                    actions.loadUser()
                } catch (e: any) {
                    setTimeout(() => {
                        // TRICKY: We want to run on the next tick otherwise the errors don't show (possibly because of the async wait in the submit)
                        actions.setChangePasswordManualErrors({ [e.attr]: e.detail })
                    }, 1)
                }
            },
        },
    })),
    loaders(({ values }) => ({
        passwordResetEmailSent: [
            false,
            {
                // The same endpoint the login page's "Forgot password?" link posts to.
                requestPasswordResetEmail: async () => {
                    const email = values.user?.email
                    if (!email) {
                        return false
                    }
                    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 })
                        return true
                    } catch (e: any) {
                        lemonToast.error(e.detail ?? 'Could not send a reset link. Please try again.')
                        return false
                    }
                },
            },
        ],
    })),
    selectors({
        validatedPassword: [
            (s) => [s.changePassword],
            ({ password }): ValidatedPasswordResult => {
                return validatePassword(password)
            },
        ],
    }),
])