: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(settings): give the change password form a way out when you forgot it (#97093)
posthog[bot]e3cfdcd102b1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a8237c6172a0..f335d8ef83c8 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9013,13 +9013,13 @@ snapshots:scenes-app-settings-user--settings-user-notifications--light:hash: v1.k794b7964.90273cebc583a00056bfa1731001443305275d1ca018fcf3a17654c0e64178a5.9Sv2AD67xtzoF0R4xODU6b--urwaZZ-DeELmtk_pei8scenes-app-settings-user--settings-user-profile--dark:- hash: v1.k794b7964.be9766f7fb3b4767d3dca23a38adb9b03f781d3c7bcafed8c14b66279b1c319b.JJrVYzunXlrqVcxX2KUwSpzjwKp1gekUbzBDaAFum-c+ hash: v1.k794b7964.5f1d9971d5da44a5868c6f1cfc633fa5e2f90d0f31e9ed651783f949512350ab.3b41GlzDKrj_9lsTioV2GDzEZDpVY2GAiAEmGjKdA9cscenes-app-settings-user--settings-user-profile--light:- hash: v1.k794b7964.b511b0741535a94c3ae2b8d92a49616575ae094856964f62694b08266568dc17.KEUQBnu0veHFP6wYgeaFKBrxyxXnji7QiClDK_eqvow+ hash: v1.k794b7964.5b100b2d10529ed809efdd86a22385bbb934628ee42c124b59ae0d8a5a5c5cf8.0vxWXxtuElYDq3EAgdJRZ3fGGfoJ763l-MVp-N7W6ZQscenes-app-settings-user--settings-user-profile-hedgehog-avatar--dark:- hash: v1.k794b7964.ed10faf9a444537be980a72ea990c42d94c0555a5f79c60849ded07872b31143.TG2uoQWjoFKXOZoVats3PxrABgKEq81BGsEyj9r89Ko+ hash: v1.k794b7964.239346cd0abcf55998302af26ff564e92f56a261f6bb43b3d2063a2404c7cbdb.NvuonbjMwGbrkFpqCPGxUx4zmuSPU_CQKSI_PEIjQpYscenes-app-settings-user--settings-user-profile-hedgehog-avatar--light:- hash: v1.k794b7964.b321293603b35ac02d1e1776b884133b618607f0c6cce74a8ac9dd1c857f716f.0QAkSVwqVTUCx9A8Gb_Fnd1cI8is19xHR0vCI9m7jSM+ hash: v1.k794b7964.38fa67af25aa26dbad8e49e9e2acb0b021f755284ded1b1178b43256a47aeb05.KfjJ7Ia0xPCen9TOxy81P2LFHWKQGGDAMR80AJofFicscenes-app-settings-user--settings-user-reminders-modal--dark:hash: v1.k794b7964.5f1527469dc059025dfe4ad1c65195efd587ca4df4b9a70f1a99cabb13dc250f.YHM_sJIzdyWLi5BKco7ccM3GQxW84xO6VRanaNE4kGcscenes-app-settings-user--settings-user-reminders-modal--light:diff --git a/frontend/src/scenes/authentication/password-reset/PasswordResetComplete.tsx b/frontend/src/scenes/authentication/password-reset/PasswordResetComplete.tsxindex 98f12f0aeb86..702bdf423dba 100644--- a/frontend/src/scenes/authentication/password-reset/PasswordResetComplete.tsx+++ b/frontend/src/scenes/authentication/password-reset/PasswordResetComplete.tsx@@ -14,6 +14,7 @@ import { LemonField } from 'lib/lemon-ui/LemonField'import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import { passwordResetLogic } from './passwordResetLogic'@@ -107,11 +108,20 @@ function NewPasswordForm(): JSX.Element {}function ResetInvalid(): JSX.Element {+ const { user } = useValues(userLogic)+return (<div className="text-center">The provided link is <b>invalid or has expired</b>. Please request a new link.<div className="mt-4">- <LemonButton fullWidth type="primary" center data-attr="back-to-login" to={urls.passwordReset()}>+ <LemonButton+ fullWidth+ type="primary"+ center+ data-attr="back-to-login"+ // Scene.PasswordReset is onlyUnauthenticated, so /reset would bounce a signed-in user.+ to={user ? urls.settings('user-profile', 'change-password') : urls.passwordReset()}+ >Request new link</LemonButton></div>diff --git a/frontend/src/scenes/sceneLogic.test.tsx b/frontend/src/scenes/sceneLogic.test.tsxindex d82a5941df19..50c43524f9bf 100644--- a/frontend/src/scenes/sceneLogic.test.tsx+++ b/frontend/src/scenes/sceneLogic.test.tsx@@ -1,3 +1,5 @@+import { MOCK_USER_UUID } from 'lib/api.mock'+import { kea, path } from 'kea'import { router } from 'kea-router'import { expectLogic, partial, truth } from 'kea-test-utils'@@ -30,6 +32,7 @@ const sceneImport = (): any => ({ scene: { component: Component, logic: testLogiconst testScenes: Record<string, () => any> = {[Scene.Alerts]: sceneImport,[Scene.DataManagement]: sceneImport,+ [Scene.PasswordResetComplete]: sceneImport,[Scene.Settings]: sceneImport,}@@ -122,6 +125,15 @@ describe('sceneLogic', () => {expect(router.values.hashParams.panel).toEqual('max:inspect')})+ // The change password form emails this link to a user who is already signed in.+ it('keeps a signed-in user on the password reset link instead of redirecting them away', async () => {+ const resetLink = urls.passwordResetComplete(MOCK_USER_UUID, 'a-token')+ router.actions.push(resetLink)+ await expectLogic(logic).delay(1)++ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(resetLink)+ })+it('persists the loaded scenes', async () => {const expectedAnnotation = partial({component: expect.any(Function),diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex b024d62db7ce..e80499a12c9d 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -317,7 +317,7 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {onlyUnauthenticated: true,layout: 'plain',},- [Scene.PasswordResetComplete]: { onlyUnauthenticated: true, layout: 'plain' },+ [Scene.PasswordResetComplete]: { allowUnauthenticated: true, layout: 'plain' },[Scene.PasswordReset]: { onlyUnauthenticated: true, layout: 'plain' },[Scene.TwoFactorReset]: { allowUnauthenticated: true, layout: 'plain' },[Scene.VercelConnect]: { allowUnauthenticated: true, layout: 'plain', name: 'Connect to Vercel' },diff --git a/frontend/src/scenes/settings/user/ChangePassword.tsx b/frontend/src/scenes/settings/user/ChangePassword.tsxindex c2670e9a7b54..fdca5001de1c 100644--- a/frontend/src/scenes/settings/user/ChangePassword.tsx+++ b/frontend/src/scenes/settings/user/ChangePassword.tsx@@ -1,9 +1,10 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'import { LemonButton, LemonInput } from '@posthog/lemon-ui'import PasswordStrength from 'lib/components/PasswordStrength'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonField } from 'lib/lemon-ui/LemonField'import { userLogic } from 'scenes/userLogic'@@ -16,7 +17,14 @@ export function ChangePasswordTitle(): JSX.Element {}export function ChangePassword(): JSX.Element {- const { validatedPassword, isChangePasswordSubmitting, user } = useValues(changePasswordLogic)+ const {+ validatedPassword,+ isChangePasswordSubmitting,+ user,+ passwordResetEmailSent,+ passwordResetEmailSentLoading,+ } = useValues(changePasswordLogic)+ const { requestPasswordResetEmail } = useActions(changePasswordLogic)const hasPassword = user?.has_password ?? falsereturn (@@ -27,14 +35,39 @@ export function ChangePassword(): JSX.Element {className="deprecated-space-y-4 max-w-160">{hasPassword && (- <LemonField name="current_password" label="Current Password">- <LemonInput- autoComplete="current-password"- type="password"- className="ph-ignore-input"- placeholder="••••••••••"- />- </LemonField>+ <>+ <LemonField+ name="current_password"+ label={+ <div className="flex flex-1 items-center justify-between gap-2">+ <span>Current password</span>+ <LemonButton+ size="xsmall"+ type="tertiary"+ data-attr="settings-forgot-password"+ onClick={requestPasswordResetEmail}+ loading={passwordResetEmailSentLoading}+ >+ {passwordResetEmailSent ? 'Resend link' : 'Forgot password?'}+ </LemonButton>+ </div>+ }+ >+ <LemonInput+ autoComplete="current-password"+ type="password"+ className="ph-ignore-input"+ placeholder="••••••••••"+ />+ </LemonField>++ {passwordResetEmailSent && (+ <LemonBanner type="info">+ We emailed a reset link to <span translate="no">{user?.email}</span>. Open it to set a new+ password without your current one. Resetting signs you out of PostHog on every device.+ </LemonBanner>+ )}+ </>)}<LemonField@@ -55,7 +88,7 @@ export function ChangePassword(): JSX.Element {</LemonField>{!hasPassword && (- <LemonField name="confirm_password" label="Confirm Password">+ <LemonField name="confirm_password" label="Confirm password"><LemonInputautoComplete="new-password"type="password"diff --git a/frontend/src/scenes/settings/user/changePasswordLogic.test.ts b/frontend/src/scenes/settings/user/changePasswordLogic.test.tsnew file mode 100644index 000000000000..a6ff4c7d889d--- /dev/null+++ b/frontend/src/scenes/settings/user/changePasswordLogic.test.ts@@ -0,0 +1,58 @@+import { MOCK_DEFAULT_USER } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { changePasswordLogic } from './changePasswordLogic'++describe('changePasswordLogic', () => {+ let logic: ReturnType<typeof changePasswordLogic.build>+ let resetRequests: Record<string, any>[]++ beforeEach(() => {+ resetRequests = []+ useMocks({+ post: {+ '/api/reset/': async ({ request }) => {+ resetRequests.push((await request.json()) as Record<string, any>)+ return [204, null]+ },+ },+ })+ initKeaTests()+ logic = changePasswordLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('sends the reset link to the signed-in user without asking for their address', async () => {+ logic.actions.requestPasswordResetEmail()++ await expectLogic(logic).toFinishAllListeners().toMatchValues({ passwordResetEmailSent: true })+ expect(resetRequests).toEqual([{ email: MOCK_DEFAULT_USER.email }])+ })++ it('explains why no link arrived when the reset is refused', async () => {+ jest.spyOn(lemonToast, 'error')+ useMocks({+ post: {+ '/api/reset/': () => [+ 400,+ { type: 'validation_error', code: 'sso_enforced', detail: 'SSO login is enforced.' },+ ],+ },+ })++ logic.actions.requestPasswordResetEmail()++ await expectLogic(logic).toFinishAllListeners().toMatchValues({ passwordResetEmailSent: false })+ expect(lemonToast.error).toHaveBeenCalledWith('SSO login is enforced.')+ })+})diff --git a/frontend/src/scenes/settings/user/changePasswordLogic.ts b/frontend/src/scenes/settings/user/changePasswordLogic.tsindex b93efdc92e76..5da10d085c29 100644--- a/frontend/src/scenes/settings/user/changePasswordLogic.ts+++ b/frontend/src/scenes/settings/user/changePasswordLogic.ts@@ -1,6 +1,7 @@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'@@ -30,6 +31,8 @@ export interface changePasswordLogicValues {changePasswordValidationErrors: DeepPartialMap<ChangePasswordForm, ValidationErrorType>isChangePasswordSubmitting: booleanisChangePasswordValid: boolean+ passwordResetEmailSent: boolean+ passwordResetEmailSentLoading: booleanshowChangePasswordErrors: booleanvalidatedPassword: ValidatedPasswordResult}@@ -39,6 +42,21 @@ 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}@@ -141,6 +159,27 @@ export const changePasswordLogic = kea<changePasswordLogicType>([},},})),+ 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 {+ 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],