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.

feat(auth): enter verification codes in six separate digit boxes (#91503)

Alex Lider31df3e3d6186
diff --git a/frontend/src/scenes/authentication/login/LoginForm.tsx b/frontend/src/scenes/authentication/login/LoginForm.tsx
index 94d7f59796c8..47accec997a4 100644
--- a/frontend/src/scenes/authentication/login/LoginForm.tsx
+++ b/frontend/src/scenes/authentication/login/LoginForm.tsx
@@ -1,11 +1,12 @@
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
import { useEffect } from 'react'
-import { twMerge } from 'tailwind-merge'
+import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass-1'
import { IconCheckCircle } from '@posthog/icons'
import { getCookie } from 'lib/api'
+import { pngHoggie } from 'lib/brand/hoggies'
import { SocialLoginButtons, SSOEnforcedLoginButton } from 'lib/components/SocialLoginButton/SocialLoginButton'
import { supportLogic } from 'lib/components/Support/supportLogic'
import { SSO_PROVIDER_NAMES } from 'lib/constants'
@@ -22,6 +23,8 @@ import { RegionField } from 'scenes/authentication/shared/authScene/RegionField'
import { ERROR_MESSAGES } from 'scenes/authentication/shared/loginErrorMessages'
import { OtherRegionHint } from 'scenes/authentication/shared/OtherRegionHint'
import { RedirectIfLoggedInOtherInstance } from 'scenes/authentication/shared/RedirectToLoggedInInstance'
+import { isValidVerificationCode, normalizeVerificationCode } from 'scenes/authentication/shared/verificationCode'
+import { VerificationCodeInput } from 'scenes/authentication/shared/VerificationCodeInput'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { urls } from 'scenes/urls'
@@ -32,6 +35,8 @@ import { SessionRiskBanner } from './SessionRiskBanner'
const LAST_LOGIN_METHOD_COOKIE = 'ph_last_login_method'
+const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)
+
function loginMethodLabel(method: LoginMethod): string {
if (method === 'password') {
return 'password'
@@ -91,7 +96,8 @@ function buildLoginSupportMessage({
// insertBefore NotFoundError, see react#11538). Text that is its own element's only child is
// already safe, so only text sharing a parent with element siblings needs wrapping.
export function LoginForm(): JSX.Element {
- const { precheck, exitCodeVerification, resendCodeBasedVerification } = useActions(loginLogic)
+ const { precheck, exitCodeVerification, resendCodeBasedVerification, submitCodeVerification } =
+ useActions(loginLogic)
const { openSupportForm } = useActions(supportLogic)
const { sendSupportRequest } = useValues(supportLogic)
const {
@@ -106,6 +112,8 @@ export function LoginForm(): JSX.Element {
codeVerificationRequired,
isCodeVerificationSubmitting,
isPasswordLoginUnavailable,
+ codeVerificationEmail,
+ codeVerification,
hasNoConfiguredLoginMethod,
restrictToProviders,
autoRedirectingToProvider,
@@ -144,10 +152,12 @@ export function LoginForm(): JSX.Element {
<AuthScene notes={['// welcome back', '// 500,000+ teams ship here']}>
{preflight?.cloud && <RedirectIfLoggedInOtherInstance />}
<AuthSceneCard footer={footer}>
+ {isCodeSent && <HedgehogMagnifyingGlass className="block w-auto mx-auto mb-3 h-28" />}
<AuthCardTitle
+ className={isCodeSent ? 'mb-2' : undefined}
title={
isCodeSent ? (
- 'Enter your login code'
+ 'Check your inbox'
) : (
<>
{/* This whole fragment is deleted when the title flips to the code-sent
@@ -159,16 +169,37 @@ export function LoginForm(): JSX.Element {
</>
)
}
- sub={isCodeSent ? undefined : "Welcome back. Let's go ship something."}
+ sub={
+ isCodeSent ? (
+ <>
+ For your security, we've emailed a 6-digit verification code to{' '}
+ <strong>{codeVerificationEmail}</strong>.
+ </>
+ ) : (
+ "Welcome back. Let's go ship something."
+ )
+ }
/>
<SessionRiskBanner className="mb-4" />
- {generalError && (
- <div
- className={twMerge(
- 'mb-4 py-2.5 px-3 text-sm leading-normal text-primary text-left bg-danger-highlight border border-danger rounded',
- isCodeSent ? 'bg-success-highlight border-success' : 'bg-danger-highlight border-danger'
+ {isCodeSent && (
+ <div className="mb-5 flex flex-col items-center gap-1 text-sm">
+ <Link
+ onClick={() => resendCodeBasedVerification(null)}
+ disabledReason={resendResponseLoading ? 'Sending...' : undefined}
+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-secondary"
+ >
+ Resend code
+ </Link>
+ {resendResponse?.success && (
+ <p className="flex items-center gap-1 text-success mb-0" role="status">
+ <IconCheckCircle />
+ <span>Code sent</span>
+ </p>
)}
- >
+ </div>
+ )}
+ {generalError && (
+ <div className="mb-4 py-2.5 px-3 text-sm leading-normal text-primary text-left bg-danger-highlight border border-danger rounded">
<span>
{generalError.detail ||
ERROR_MESSAGES[generalError.code] ||
@@ -224,16 +255,30 @@ export function LoginForm(): JSX.Element {
logic={loginLogic}
formKey="codeVerification"
enableFormOnSubmit
+ // The code input renders a hidden input with a \d{6} pattern. Without noValidate,
+ // the browser blocks submit on a partial code and kea cannot show its error.
+ noValidate
className="flex flex-col gap-4"
>
- <LemonField name="code" label="Verification code">
- <LemonInput
- className="ph-ignore-input"
- autoFocus
+ <LemonField
+ name="code"
+ label="Verification code"
+ labelClassName="sr-only"
+ // Plain centered text without an icon, like the signup verify screen's error
+ renderError={(error) => (
+ <p className="m-0 text-sm text-danger text-center" role="alert">
+ {error}
+ </p>
+ )}
+ >
+ <VerificationCodeInput
data-attr="code-verification"
- placeholder="123456"
- inputMode="numeric"
- autoComplete="one-time-code"
+ disabled={isCodeVerificationSubmitting}
+ onComplete={() => {
+ if (!isCodeVerificationSubmitting) {
+ submitCodeVerification()
+ }
+ }}
/>
</LemonField>
<LemonButton
@@ -245,25 +290,15 @@ export function LoginForm(): JSX.Element {
center
size="large"
loading={isCodeVerificationSubmitting}
+ disabledReason={
+ isValidVerificationCode(normalizeVerificationCode(codeVerification.code))
+ ? undefined
+ : 'Enter the 6-digit code from your email'
+ }
>
Verify and log in
</LemonButton>
<div className="flex flex-col items-center gap-3">
- <LemonButton
- size="small"
- type="tertiary"
- disabled={resendResponseLoading}
- loading={resendResponseLoading}
- onClick={() => resendCodeBasedVerification(null)}
- >
- Resend code
- </LemonButton>
- {resendResponse?.success && (
- <p className="flex items-center gap-1 text-success mb-0" role="status">
- <IconCheckCircle />
- <span>Code sent — check your inbox.</span>
- </p>
- )}
<Link
onClick={() => exitCodeVerification()}
className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-secondary"
diff --git a/frontend/src/scenes/authentication/login/loginLogic.test.ts b/frontend/src/scenes/authentication/login/loginLogic.test.ts
index c6a8dd825585..3e6b8fb296b7 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.test.ts
+++ b/frontend/src/scenes/authentication/login/loginLogic.test.ts
@@ -202,11 +202,12 @@ describe('loginLogic', () => {
await expectLogic(logic).toDispatchActions(['setCodeVerificationRequired', 'submitLoginFailure'])
expect(logic.values.codeVerificationRequired).toBe(true)
- expect(logic.values.generalError?.code).toBe('code_based_verification_sent')
+ expect(logic.values.codeVerificationEmail).toBe('[email protected]')
+ expect(logic.values.generalError).toBe(null)
logic.actions.exitCodeVerification()
expect(logic.values.codeVerificationRequired).toBe(false)
- expect(logic.values.generalError).toBe(null)
+ expect(logic.values.codeVerificationEmail).toBe(null)
})
})
diff --git a/frontend/src/scenes/authentication/login/loginLogic.ts b/frontend/src/scenes/authentication/login/loginLogic.ts
index cdda385b788e..cc238121ebae 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.ts
+++ b/frontend/src/scenes/authentication/login/loginLogic.ts
@@ -16,7 +16,11 @@ import { isWebKitBrowser } from 'lib/utils/dom'
import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'
import { getRelativeNextPath } from 'lib/utils/url'
import { devLoginLogic } from 'scenes/authentication/shared/devLoginLogic'
-import { normalizeVerificationCode } from 'scenes/authentication/shared/verificationCode'
+import {
+ clearPendingVerificationEmail,
+ normalizeVerificationCode,
+ setPendingVerificationEmail,
+} from 'scenes/authentication/shared/verificationCode'
import { twoFactorResetLogic } from 'scenes/authentication/two-factor-reset/twoFactorResetLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { urls } from 'scenes/urls'
@@ -153,6 +157,7 @@ export interface loginLogicValues {
codeVerification: CodeVerificationForm
codeVerificationAllErrors: Record<string, any>
codeVerificationChanged: boolean
+ codeVerificationEmail: string | null
codeVerificationErrors: DeepPartialMap<CodeVerificationForm, ValidationErrorType>
codeVerificationHasErrors: boolean
codeVerificationManualErrors: Record<string, any>
@@ -259,8 +264,8 @@ export interface loginLogicActions {
setCodeVerificationManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
- setCodeVerificationRequired: () => {
- value: true
+ setCodeVerificationRequired: (email: string) => {
+ email: string
}
setCodeVerificationValue: (
key: FieldName,
@@ -376,7 +381,7 @@ export const loginLogic = kea<loginLogicType>([
actions({
setGeneralError: (code: string, detail: string) => ({ code, detail }),
clearGeneralError: true,
- setCodeVerificationRequired: true,
+ setCodeVerificationRequired: (email: string) => ({ email }),
exitCodeVerification: true,
startAutoRedirectToProvider: (provider: SSOProvider, email: string) => ({ provider, email }),
}),
@@ -399,6 +404,14 @@ export const loginLogic = kea<loginLogicType>([
exitCodeVerification: () => false,
},
],
+ // The address the login code went to, shown under the code screen title
+ codeVerificationEmail: [
+ null as string | null,
+ {
+ setCodeVerificationRequired: (_, { email }) => email,
+ exitCodeVerification: () => null,
+ },
+ ],
// The provider we're currently bouncing the user to, so the form can say so out loud. The
// manual button stays rendered, so a blocked or slow redirect still leaves them a way in.
autoRedirectingToProvider: [
@@ -575,17 +588,16 @@ export const loginLogic = kea<loginLogicType>([
if (code === 'verify_email_pending' && typeof detail === 'string') {
// detail carries the user uuid; the verification page has the code entry form
lemonToast.info('Verify your email to continue. We just sent you a new code.')
+ // The verify page has no session in this state, so store the address for its copy.
+ // detail carries the user uuid, which keys the stored value.
+ setPendingVerificationEmail(detail, email)
const next: string | undefined = router.values.searchParams.next
router.actions.push(urls.verifyEmail(detail), next ? { next } : {})
throw e
}
if (code === 'code_based_verification_required') {
const emailAddress = detail?.email || email
- actions.setCodeVerificationRequired()
- actions.setGeneralError(
- 'code_based_verification_sent',
- `For your security, we've emailed a 6-digit verification code to ${emailAddress}. Enter it below to finish logging in.`
- )
+ actions.setCodeVerificationRequired(emailAddress)
throw e
}
// A response with no parseable JSON body (a 5xx HTML page, a 502 from the edge, a
@@ -602,14 +614,9 @@ export const loginLogic = kea<loginLogicType>([
},
},
codeVerification: {
+ // No kea validator here: the submit button carries a disabledReason for an incomplete
+ // code, like the signup verify screen, so the only inline error is a server rejection
defaults: { code: '' } as CodeVerificationForm,
- errors: ({ code }) => ({
- // Accept a code pasted with the whitespace/invisible characters an email client adds;
- // reject anything that isn't 6 digits once that noise is stripped.
- code: /^\d{6}$/.test(normalizeVerificationCode(code))
- ? undefined
- : 'Enter the 6-digit code from your email',
- }),
submit: async ({ code }, breakpoint) => {
breakpoint()
actions.clearGeneralError()
@@ -620,9 +627,9 @@ export const loginLogic = kea<loginLogicType>([
})
} catch (e) {
const { detail } = e as Record<string, any>
- const message =
- typeof detail === 'string' ? detail : 'That code is invalid or has expired. Please try again.'
- actions.setGeneralError('invalid_code', message)
+ const message = typeof detail === 'string' ? detail : 'This code is invalid or has expired.'
+ // Shown under the code input, like the signup verify screen, not in the banner
+ actions.setCodeVerificationManualErrors({ code: message })
throw e
}
},
@@ -630,11 +637,14 @@ export const loginLogic = kea<loginLogicType>([
})),
listeners(({ values, actions }) => ({
submitLoginSuccess: () => {
+ // A logged-in session reads the address from the user, so drop the stored one
+ clearPendingVerificationEmail()
handleLoginRedirect()
// Reload the page after login to ensure POSTHOG_APP_CONTEXT is set correctly.
window.location.reload()
},
submitCodeVerificationSuccess: () => {
+ clearPendingVerificationEmail()
handleLoginRedirect()
// Reload the page after login to ensure POSTHOG_APP_CONTEXT is set correctly.
window.location.reload()
@@ -642,6 +652,13 @@ export const loginLogic = kea<loginLogicType>([
exitCodeVerification: () => {
actions.resetCodeVerification()
},
+ // Manual errors persist until the next submit, so clear the invalid-code error as soon as
+ // the user edits the code, like the signup verify screen does
+ setCodeVerificationValue: () => {
+ if (Object.keys(values.codeVerificationManualErrors).length > 0) {
+ actions.setCodeVerificationManualErrors({})
+ }
+ },
precheckSuccess: async ({ payload }, breakpoint) => {
const { precheckResponse } = values
// Auto-trigger the modal passkey prompt if the user has passkeys and SSO isn't enforced.
diff --git a/frontend/src/scenes/authentication/shared/VerificationCodeInput.scss b/frontend/src/scenes/authentication/shared/VerificationCodeInput.scss
new file mode 100644
index 000000000000..0525afde1ded
--- /dev/null
+++ b/frontend/src/scenes/authentication/shared/VerificationCodeInput.scss
@@ -0,0 +1,29 @@
+// Border color and its states live here rather than in Tailwind classes.
+// The error state must react to .Field--error, which LemonField sets only on its wrapper.
+// The other interaction states stay next to it, so all conditional styles are in one place.
+.VerificationCodeInput {
+ .VerificationCodeInput__slot {
+ border-color: var(--color-border-primary);
+ outline: none;
+
+ &:hover:not(:disabled, :focus-visible) {
+ border-color: var(--color-border-secondary);
+ }
+
+ &:focus-visible {
+ border-color: var(--color-accent);
+ box-shadow: 0 0 0 2px var(--color-accent-highlight-secondary);
+ }
+
+ &:disabled {
+ cursor: not-allowed;
+ opacity: 0.5;
+ }
+ }
+
+ // This rule is last, so the error border wins over the hover and focus states above
+ &.VerificationCodeInput--danger .VerificationCodeInput__slot,
+ .Field--error & .VerificationCodeInput__slot {
+ border-color: var(--danger);
+ }
+}
diff --git a/frontend/src/scenes/authentication/shared/VerificationCodeInput.tsx b/frontend/src/scenes/authentication/shared/VerificationCodeInput.tsx
new file mode 100644
index 000000000000..61d43571eada
--- /dev/null
+++ b/frontend/src/scenes/authentication/shared/VerificationCodeInput.tsx
@@ -0,0 +1,68 @@
+import './VerificationCodeInput.scss'
+
+import { OTPField } from '@base-ui/react/otp-field'
+import clsx from 'clsx'
+import { useId } from 'react'
+
+import { normalizeVerificationCode } from './verificationCode'
+
+export const VERIFICATION_CODE_LENGTH = 6
+
+export interface VerificationCodeInputProps {
+ value?: string
+ onChange?: (value: string) => void
+ /** Fires when all slots are filled, by typing, paste, or autofill. */
+ onComplete?: (value: string) => void
+ disabled?: boolean
+ status?: 'default' | 'danger'
+ /** LemonField injects this id to connect its label to the first slot. */
+ id?: string
+ 'data-attr'?: string
+}
+
+export function VerificationCodeInput({
+ value,
+ onChange,
+ onComplete,
+ disabled,
+ status = 'default',
+ id,
+ 'data-attr': dataAttr,
+}: VerificationCodeInputProps): JSX.Element {
+ const generatedId = useId()
+ const inputId = id ?? generatedId
+ return (
+ <OTPField.Root
+ id={inputId}
+ length={VERIFICATION_CODE_LENGTH}
+ value={value}
+ onValueChange={(nextValue) => onChange?.(nextValue)}
+ onValueComplete={(completeValue) => onComplete?.(completeValue)}
+ normalizeValue={normalizeVerificationCode}
+ disabled={disabled}
+ className={clsx(
+ 'VerificationCodeInput flex w-full justify-center gap-2',
+ status === 'danger' && 'VerificationCodeInput--danger'
+ )}
+ data-attr={dataAttr}
+ >
+ {!id && (
+ // Base UI does not accept aria-label on the first slot and expects a <label> for it.
+ // When LemonField provides the id, the LemonField label already labels the first slot.
+ <label htmlFor={inputId} className="sr-only">
+ Verification code
+ </label>
+ )}
+ {Array.from({ length: VERIFICATION_CODE_LENGTH }, (_, index) => (
+ <OTPField.Input
+ key={index}
+ // ph-ignore-input excludes the slots from session replay and autocapture, the same as the other auth inputs
+ // The hover, focus, disabled, and error styles live in VerificationCodeInput.scss
+ className="VerificationCodeInput__slot ph-ignore-input h-12 min-w-0 max-w-12 flex-1 rounded border bg-fill-input text-center font-mono text-2xl font-semibold leading-none text-primary caret-accent transition-colors"
+ autoFocus={index === 0}
+ aria-label={index > 0 ? `Verification code, digit ${index + 1}` : undefined}
+ />
+ ))}
+ </OTPField.Root>
+ )
+}
diff --git a/frontend/src/scenes/authentication/shared/verificationCode.ts b/frontend/src/scenes/authentication/shared/verificationCode.ts
index efbf215e76b9..4c1958ecf939 100644
--- a/frontend/src/scenes/authentication/shared/verificationCode.ts
+++ b/frontend/src/scenes/authentication/shared/verificationCode.ts
@@ -20,3 +20,43 @@ export function verificationCodeErrorMessage(e: { code?: string; detail?: string
}
return e.detail || 'This code is invalid or has expired.'
}
+
+// The verify-email page cannot always read the address from the session. A fresh signup and a
+// login attempt on an unverified account both land there without one. The form that knows the
+// address stores it here, in this browser only, so the page can show it. The helpers use
+// try/catch because sessionStorage can throw, for example in private windows with site data blocked.
+const PENDING_VERIFICATION_EMAIL_KEY = 'ph_pending_verification_email'
+
+// The value is keyed by user uuid, so a verify page for one account never shows an address
+// that an earlier attempt for another account stored in the same tab.
+export function setPendingVerificationEmail(uuid: string, email: string): void {
+ try {
+ sessionStorage.setItem(PENDING_VERIFICATION_EMAIL_KEY, JSON.stringify({ uuid, email }))
+ } catch {
+ // The page shows the generic copy instead
+ }
+}
+
+export function getPendingVerificationEmail(uuid: string | null): string | null {
+ if (!uuid) {
+ return null
+ }
+ try {
+ const raw = sessionStorage.getItem(PENDING_VERIFICATION_EMAIL_KEY)
+ if (!raw) {
+ return null
+ }
+ const stored = JSON.parse(raw) as { uuid?: string; email?: string }
+ return stored.uuid === uuid ? (stored.email ?? null) : null
+ } catch {
+ return null
+ }
+}
+
+export function clearPendingVerificationEmail(): void {
+ try {
+ sessionStorage.removeItem(PENDING_VERIFICATION_EMAIL_KEY)
+ } catch {
+ // Nothing to clear when storage is unavailable
+ }
+}
diff --git a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts
index 6cfe713a9434..e4cd28cfd14c 100644
--- a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts
+++ b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts
@@ -13,6 +13,10 @@ import { CLOUD_HOSTNAMES, FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { splitFullName } from 'lib/utils/strings'
import { getRelativeNextPath } from 'lib/utils/url'
+import {
+ clearPendingVerificationEmail,
+ setPendingVerificationEmail,
+} from 'scenes/authentication/shared/verificationCode'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { getPasskeyErrorMessage, isWebAuthnCancellation } from 'scenes/settings/user/passkeys/utils'
import { RegistrationBeginResponse } from 'scenes/settings/user/passkeySettingsLogic'
@@ -495,6 +499,8 @@ export const signupLogic = kea<signupLogicType>([
},
submit: async (payload, breakpoint) => {
breakpoint()
+ // A new signup attempt must not inherit the address a previous attempt stored
+ clearPendingVerificationEmail()
try {
const nextUrl = getRelativeNextPath(new URLSearchParams(location.search).get('next'), location)
@@ -528,6 +534,12 @@ export const signupLogic = kea<signupLogicType>([
posthog.capture('signup completed with passkey')
}
+ // The verify page has no session yet, so store the address for its copy,
+ // keyed by the user uuid from the redirect path
+ const verifyUuid = res.redirect_url?.match(/\/verify_email\/([^/?#]+)/)?.[1]
+ if (verifyUuid && signupData.email) {
+ setPendingVerificationEmail(verifyUuid, signupData.email)
+ }
// it's ok to trust the url sent from the server
// nosemgrep: javascript.browser.security.open-redirect.js-open-redirect
location.href = res.redirect_url || '/'
diff --git a/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx b/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx
index d1d3c42b0c63..6ebca62d502f 100644
--- a/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx
+++ b/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx
@@ -7,10 +7,11 @@ import { pngHoggie } from 'lib/brand/hoggies'
import { ExplorerHog, SleepingHog } from 'lib/components/hedgehogs'
import { supportLogic } from 'lib/components/Support/supportLogic'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
-import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { Link } from 'lib/lemon-ui/Link'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
import { AuthScene, AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
+import { getPendingVerificationEmail, isValidVerificationCode } from 'scenes/authentication/shared/verificationCode'
+import { VerificationCodeInput } from 'scenes/authentication/shared/VerificationCodeInput'
import { urls } from 'scenes/urls'
import { verifyEmailLogic } from './verifyEmailLogic'
@@ -113,6 +114,9 @@ function VerificationCodeEntry(): JSX.Element {
return (
<form
className="flex w-full flex-col gap-2.5"
+ // The code input renders a hidden input with a \d{6} pattern. Without noValidate,
+ // the browser blocks an Enter-key submit on a partial code and shows no feedback.
+ noValidate
onSubmit={(e) => {
e.preventDefault()
if (!validatedEmailTokenLoading) {
@@ -120,16 +124,15 @@ function VerificationCodeEntry(): JSX.Element {
}
}}
>
- <LemonInput
- autoFocus
+ <VerificationCodeInput
value={verificationCode}
onChange={setVerificationCode}
- placeholder="123456"
- aria-label="Email verification code"
- inputMode="numeric"
- autoComplete="one-time-code"
- size="large"
- className="text-center ph-replay-block"
+ onComplete={() => {
+ if (!validatedEmailTokenLoading) {
+ submitVerificationCode()
+ }
+ }}
+ disabled={validatedEmailTokenLoading}
data-attr="verify-email-code"
status={verificationCodeError ? 'danger' : 'default'}
/>
@@ -145,7 +148,9 @@ function VerificationCodeEntry(): JSX.Element {
fullWidth
htmlType="submit"
loading={validatedEmailTokenLoading}
- disabledReason={verificationCode ? undefined : 'Enter the code from your email'}
+ disabledReason={
+ isValidVerificationCode(verificationCode) ? undefined : 'Enter the 6-digit code from your email'
+ }
data-attr="verify-email-code-submit"
>
Verify email
@@ -155,11 +160,15 @@ function VerificationCodeEntry(): JSX.Element {
}
export function VerifyEmailForm(): JSX.Element {
- const { view, uuid, newlyRequestedVerificationLinkLoading } = useValues(verifyEmailLogic)
+ const { view, uuid, newlyRequestedVerificationLinkLoading, user } = useValues(verifyEmailLogic)
const { requestVerificationLink } = useActions(verifyEmailLogic)
const { openSupportForm } = useActions(supportLogic)
const notes = NOTES[view ?? 'pending'] ?? NOTES.pending
+ // The address that received the code. This is the new address if an email change is pending,
+ // else the account address. Without a session, for example on a fresh signup, the page uses the
+ // address the signup or login form stored in this browser. It stays unset in a different browser.
+ const verificationEmail = user?.pending_email ?? user?.email ?? getPendingVerificationEmail(uuid) ?? undefined
if (view === 'success') {
return (
@@ -277,8 +286,15 @@ export function VerifyEmailForm(): JSX.Element {
Check your inbox
</h1>
<p className="AuthScene__sub mt-2 mb-4 text-sm text-secondary text-center text-pretty">
- We emailed you a 6-digit code. Enter it below to verify your email address. The code is valid
- for 30 minutes.
+ {verificationEmail ? (
+ <>
+ We sent a 6-digit code to <strong>{verificationEmail}</strong>.
+ <br />
+ It's valid for 30 minutes.
+ </>
+ ) : (
+ <>We sent you a 6-digit code. It's valid for 30 minutes.</>
+ )}
</p>
<VerificationCodeEntry />
<div className="mt-3">
diff --git a/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts b/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts
index edb7307800f3..35ab7994419b 100644
--- a/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts
+++ b/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts
@@ -6,6 +6,7 @@ import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { getRelativeNextPath } from 'lib/utils/url'
import {
+ clearPendingVerificationEmail,
isValidVerificationCode,
normalizeVerificationCode,
verificationCodeErrorMessage,
@@ -217,6 +218,7 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([
token,
uuid,
})
+ clearPendingVerificationEmail()
actions.setView('success')
await breakpoint(VERIFY_EMAIL_REDIRECT_DELAY_MS)
redirectAfterVerification(response, values)
@@ -254,6 +256,7 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([
uuid,
code,
})
+ clearPendingVerificationEmail()
actions.setView('success')
await breakpoint(VERIFY_EMAIL_REDIRECT_DELAY_MS)
redirectAfterVerification(response, values)
diff --git a/frontend/src/scenes/settings/user/EmailChangeVerificationModal.tsx b/frontend/src/scenes/settings/user/EmailChangeVerificationModal.tsx
index dcca4c30fcae..de89ce5332f9 100644
--- a/frontend/src/scenes/settings/user/EmailChangeVerificationModal.tsx
+++ b/frontend/src/scenes/settings/user/EmailChangeVerificationModal.tsx
@@ -5,8 +5,9 @@ import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass
import { pngHoggie } from 'lib/brand/hoggies'
import { supportLogic } from 'lib/components/Support/supportLogic'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
-import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { isValidVerificationCode } from 'scenes/authentication/shared/verificationCode'
+import { VerificationCodeInput } from 'scenes/authentication/shared/VerificationCodeInput'
import { userLogic } from 'scenes/userLogic'
import { MAX_RESENDS, emailChangeVerificationLogic } from './emailChangeVerificationLogic'
@@ -29,9 +30,13 @@ export function EmailChangeVerificationModal(): JSX.Element {
const { user } = useValues(userLogic)
return (
- <LemonModal isOpen={modalOpen} onClose={closeModal} simple width={480}>
+ // 400px gives the same content width as the auth card, so the button does not dwarf the code boxes
+ <LemonModal isOpen={modalOpen} onClose={closeModal} simple width={400}>
<form
className="flex flex-col items-center gap-2.5 p-6 text-center"
+ // The code input renders a hidden input with a \d{6} pattern. Without noValidate,
+ // the browser blocks an Enter-key submit on a partial code and shows no feedback.
+ noValidate
onSubmit={(e) => {
e.preventDefault()
if (!verificationResultLoading) {
@@ -45,18 +50,16 @@ export function EmailChangeVerificationModal(): JSX.Element {
We emailed a 6-digit code to <strong>{user?.pending_email}</strong>. Enter it below to verify your
new address. The code is valid for 30 minutes.
</p>
- <LemonInput
- autoFocus
+ <VerificationCodeInput
value={verificationCode}
onChange={setVerificationCode}
- placeholder="123456"
- aria-label="Email verification code"
- inputMode="numeric"
- autoComplete="one-time-code"
- size="large"
- fullWidth
+ onComplete={() => {
+ if (!verificationResultLoading) {
+ submitVerificationCode()
+ }
+ }}
+ disabled={verificationResultLoading}
data-attr="email-change-verification-code"
- className="ph-replay-block"
status={verificationCodeError ? 'danger' : 'default'}
/>
{verificationCodeError && (
@@ -71,7 +74,9 @@ export function EmailChangeVerificationModal(): JSX.Element {
fullWidth
htmlType="submit"
loading={verificationResultLoading}
- disabledReason={verificationCode ? undefined : 'Enter the code from your email'}
+ disabledReason={
+ isValidVerificationCode(verificationCode) ? undefined : 'Enter the 6-digit code from your email'
+ }
data-attr="email-change-verification-submit"
>
Verify email
@@ -85,7 +90,7 @@ export function EmailChangeVerificationModal(): JSX.Element {
onClick={resendCode}
data-attr="email-change-verification-resend"
>
- Not seeing it? Resend code
+ Resend code
</LemonButton>
) : (
<LemonButton
diff --git a/frontend/src/scenes/userLogic.ts b/frontend/src/scenes/userLogic.ts
index e36e2c4e359d..bfe268d95729 100644
--- a/frontend/src/scenes/userLogic.ts
+++ b/frontend/src/scenes/userLogic.ts
@@ -11,6 +11,7 @@ import { DashboardCompatibleScenes } from 'lib/components/SceneDashboardChoice/s
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { clearSession, isOAuthMode, setOAuthContextIds } from 'lib/oauth/oauthClient'
import { getAppContext } from 'lib/utils/getAppContext'
+import { clearPendingVerificationEmail } from 'scenes/authentication/shared/verificationCode'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { ProductKey } from '~/queries/schema/schema-general'
@@ -610,6 +611,8 @@ export const userLogic = kea<userLogicType>([
}
cache.loggingOut = true
posthog.reset()
+ // Drop the address a signup or login attempt stored for the verify page
+ clearPendingVerificationEmail()
// OAuth mode: there's no local Django session to end — just drop the stored cloud
// token and return to the local login. (A cross-origin /logout POST would do nothing.)
diff --git a/posthog/api/user.py b/posthog/api/user.py
index 95a93f21f5c3..e79228ae1077 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -1276,7 +1276,7 @@ class UserViewSet(
if code and not token:
if not user:
raise serializers.ValidationError(
- {"code": ["This verification code is invalid or has expired."]},
+ {"code": ["This code is invalid or has expired."]},
code="invalid_code",
)
attempts = email_verification_code_verifier.reserve_attempt(user)
@@ -1289,7 +1289,7 @@ class UserViewSet(
)
if not email_verification_code_verifier.check_code(user, code):
raise serializers.ValidationError(
- {"code": ["This verification code is invalid or has expired."]},
+ {"code": ["This code is invalid or has expired."]},
code="invalid_code",
)
email_verification_code_verifier.invalidate(user)