: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
chore(auth): remove the email verification link flow (#90177)
Alex Liderdf010a671200
diff --git a/ee/api/agentic_provisioning/views/deep_links.py b/ee/api/agentic_provisioning/views/deep_links.pyindex f9ed17c1470a..55cfbe856345 100644--- a/ee/api/agentic_provisioning/views/deep_links.py+++ b/ee/api/agentic_provisioning/views/deep_links.py@@ -18,7 +18,7 @@ import structlogfrom rest_framework.request import Requestfrom rest_framework.response import Response-from posthog.api.email_verification import EmailVerifier+from posthog.api.email_verification import email_verification_code_verifierfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.oauth import OAuthAccessTokenfrom posthog.models.oauth_provisioning import PartnerTier@@ -191,10 +191,10 @@ def agentic_login(request: Any) -> HttpResponseBase:# or the org-level email-verification-disabled flag.if user.is_email_verified is not True:try:- EmailVerifier.create_token_and_send_email_verification(user)+ email_verification_code_verifier.send_code(user)except Exception:# Intentionally swallowed: the login must stay blocked regardless of email delivery.- # EmailVerifier captures the exception internally; the verify_email page has a resend button.+ # The verifier captures the exception internally; the verify_email page has a resend button.logger.warning("agentic_login.verification_email_failed", user_id=user.id)capture_deep_link_event("email_unverified", user_id=user_id)logger.warning("agentic_login.email_unverified", user_id=user_id)diff --git a/ee/partners/stripe/api/provisioning/login.py b/ee/partners/stripe/api/provisioning/login.pyindex 3330bf09770b..2d9144b37e4a 100644--- a/ee/partners/stripe/api/provisioning/login.py+++ b/ee/partners/stripe/api/provisioning/login.py@@ -20,7 +20,7 @@ from django.http import HttpResponseBase, HttpResponseRedirectimport structlog-from posthog.api.email_verification import EmailVerifier+from posthog.api.email_verification import email_verification_code_verifierfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -109,10 +109,10 @@ def stripe_provisioning_login(request: Any) -> HttpResponseBase:# or the org-level email-verification-disabled flag.if user.is_email_verified is not True:try:- EmailVerifier.create_token_and_send_email_verification(user)+ email_verification_code_verifier.send_code(user)except Exception:# Intentionally swallowed: the login must stay blocked regardless of email delivery.- # EmailVerifier captures the exception internally; the verify_email page has a resend button.+ # The verifier captures the exception internally; the verify_email page has a resend button.logger.warning("stripe_provisioning.login.verification_email_failed", user_id=user.id)_capture("email_unverified", user_id=user_id)logger.warning("stripe_provisioning.login.email_unverified", user_id=user_id)diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 393641ecc85b..613105a8fd7f 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -4955,15 +4955,13 @@ export interface UserPushTokenUnregisterRequestApi {}/**- * Request body for POST /api/users/verify_email/. Exactly one of token or code is required.+ * Request body for POST /api/users/verify_email/.*/export interface VerifyEmailRequestApi {/** UUID of the user whose email is being verified. */uuid: string- /** Verification token from the emailed link. Required unless a code is provided. */- token?: string- /** The 6-digit verification code emailed at signup. Whitespace, invisible characters, and grouping hyphens are removed and compatibility digits are folded to ASCII before checking. */- code?: string+ /** The 6-digit verification code from the email. Whitespace, invisible characters, and grouping hyphens are removed and compatibility digits are folded to ASCII before checking. */+ code: string}export type CimdVerificationTokensListParams = {diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex e31a9e48c3e4..58fed89e56d7 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -2095,15 +2095,10 @@ export const UsersRequestEmailVerificationCreateBody = /* @__PURE__ */ zod.objecexport const UsersVerifyEmailCreateBody = /* @__PURE__ */ zod.object({uuid: zod.string().describe('UUID of the user whose email is being verified.'),- token: zod- .string()- .optional()- .describe('Verification token from the emailed link. Required unless a code is provided.'),code: zod.string()- .optional().describe(- 'The 6-digit verification code emailed at signup. Whitespace, invisible characters, and grouping hyphens are removed and compatibility digits are folded to ASCII before checking.'+ 'The 6-digit verification code from the email. Whitespace, invisible characters, and grouping hyphens are removed and compatibility digits are folded to ASCII before checking.'),})- .describe('Request body for POST \/api\/users\/verify_email\/. Exactly one of token or code is required.')+ .describe('Request body for POST \/api\/users\/verify_email\/.')diff --git a/frontend/src/layout/navigation/projectNoticeLogic.test.tsx b/frontend/src/layout/navigation/projectNoticeLogic.test.tsxindex c6150c8b2bb9..d2e7f77d3749 100644--- a/frontend/src/layout/navigation/projectNoticeLogic.test.tsx+++ b/frontend/src/layout/navigation/projectNoticeLogic.test.tsx@@ -287,8 +287,8 @@ describe('projectNoticeLogic', () => {expect(verifyEmailLogic.isMounted()).toBe(true)await expectLogic(verifyEmailLogic, () => {- verifyEmailLogic.actions.requestVerificationLink('test-uuid')- }).toDispatchActions(['requestVerificationLink', 'requestVerificationLinkSuccess'])+ verifyEmailLogic.actions.requestVerificationCode('test-uuid')+ }).toDispatchActions(['requestVerificationCode', 'requestVerificationCodeSuccess'])logic.unmount()})diff --git a/frontend/src/layout/navigation/projectNoticeLogic.tsx b/frontend/src/layout/navigation/projectNoticeLogic.tsxindex ae10a9790dd2..869430224477 100644--- a/frontend/src/layout/navigation/projectNoticeLogic.tsx+++ b/frontend/src/layout/navigation/projectNoticeLogic.tsx@@ -236,7 +236,7 @@ export interface projectNoticeLogicActions {reportProjectNoticeShown: (variant: string) => {variant: string} // eventUsageLogic- requestVerificationLink: (uuid: string) => {+ requestVerificationCode: (uuid: string) => {uuid: string} // verifyEmailLogicdismissProjectNotice: (dismissKey: string | null) => {@@ -353,7 +353,7 @@ export const projectNoticeLogic = kea<projectNoticeLogicType>([// Mount verifyEmailLogic so the "Send verification email" banner CTA's loader fires.// The banner renders on every scene, but verifyEmailLogic is otherwise only mounted on the verify-email scene.verifyEmailLogic,- ['requestVerificationLink'],+ ['requestVerificationCode'],],})),actions({@@ -662,7 +662,7 @@ export const projectNoticeLogic = kea<projectNoticeLogicType>([message: 'Please verify your email address.',action: {'data-attr': 'unverified-email-cta',- onClick: () => user && verifyEmailLogic.actions.requestVerificationLink(user.uuid),+ onClick: () => user && verifyEmailLogic.actions.requestVerificationCode(user.uuid),children: 'Send verification email',},type: 'warning',diff --git a/frontend/src/scenes/authentication/login/loginLogic.ts b/frontend/src/scenes/authentication/login/loginLogic.tsindex cc238121ebae..4432bc2db0c4 100644--- a/frontend/src/scenes/authentication/login/loginLogic.ts+++ b/frontend/src/scenes/authentication/login/loginLogic.ts@@ -565,12 +565,8 @@ export const loginLogic = kea<loginLogicType>([breakpoint()// Clear any previous passkey errors when submitting with passwordactions.clearGeneralError()- // Forward `next` so email verification / login-verification links can resume the- // original destination (e.g. an /oauth/authorize flow). The link carries `next`, so- // it works even when opened in a different browser than the one that started login.- const next = getRelativeNextPath(router.values.searchParams['next'], location) || undefinedtry {- return await api.create<any>('api/login', { email, password, ...(next ? { next } : {}) })+ return await api.create<any>('api/login', { email, password })} catch (e) {const { code, detail } = e as Record<string, any>if (code === '2fa_required') {diff --git a/frontend/src/scenes/authentication/verify-email/VerifyEmail.stories.tsx b/frontend/src/scenes/authentication/verify-email/VerifyEmail.stories.tsxindex 07792140c24c..28a385beaf36 100644--- a/frontend/src/scenes/authentication/verify-email/VerifyEmail.stories.tsx+++ b/frontend/src/scenes/authentication/verify-email/VerifyEmail.stories.tsx@@ -7,7 +7,7 @@ import preflightJson from '~/mocks/fixtures/_preflight.json'import { VerifyEmail } from './VerifyEmail'import { verifyEmailLogic } from './verifyEmailLogic'-type VerifyEmailView = 'pending' | 'verify' | 'success' | 'invalid'+type VerifyEmailView = 'pending' | 'success' | 'invalid'type StoryArgs = {view: VerifyEmailView@@ -24,7 +24,7 @@ const meta: Meta<StoryArgs> = {view: {control: 'select',name: 'View',- options: ['pending', 'verify', 'success', 'invalid'] satisfies VerifyEmailView[],+ options: ['pending', 'success', 'invalid'] satisfies VerifyEmailView[],},},args: {@@ -54,12 +54,8 @@ export const Default: StoryFn<StoryArgs> = Template.bind({})export const Pending: StoryFn<StoryArgs> = Template.bind({})Pending.args = { view: 'pending' }-export const Verifying: StoryFn<StoryArgs> = Template.bind({})-Verifying.args = { view: 'verify' }-Verifying.parameters = { testOptions: { waitForLoadersToDisappear: false } }-export const Success: StoryFn<StoryArgs> = Template.bind({})Success.args = { view: 'success' }-export const InvalidLink: StoryFn<StoryArgs> = Template.bind({})-InvalidLink.args = { view: 'invalid' }+export const Invalid: StoryFn<StoryArgs> = Template.bind({})+Invalid.args = { view: 'invalid' }diff --git a/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx b/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsxindex 6ebca62d502f..4cb0333551e2 100644--- a/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx+++ b/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx@@ -8,7 +8,6 @@ import { ExplorerHog, SleepingHog } from 'lib/components/hedgehogs'import { supportLogic } from 'lib/components/Support/supportLogic'import { LemonButton } from 'lib/lemon-ui/LemonButton'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'@@ -21,8 +20,7 @@ const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)const NOTES: Record<string, string[]> = {pending: ['// one email away', '// we just hit send'],success: ['// verified', '// go explore'],- invalid: ['// that link expired', '// happens to the best of us'],- verify: ['// hold tight', '// verifying'],+ invalid: ['// nothing to verify', "// let's start again"],}const CHECKLIST = [@@ -33,8 +31,8 @@ const CHECKLIST = [function NotSeeingIt(): JSX.Element {const { openSupportForm } = useActions(supportLogic)- const { requestVerificationLink } = useActions(verifyEmailLogic)- const { uuid, newlyRequestedVerificationLinkLoading } = useValues(verifyEmailLogic)+ const { requestVerificationCode } = useActions(verifyEmailLogic)+ const { uuid, newlyRequestedVerificationCodeLoading } = useValues(verifyEmailLogic)const [open, setOpen] = useState(false)const [checked, setChecked] = useState<boolean[]>([])const allChecked = CHECKLIST.every((_, i) => checked[i])@@ -80,11 +78,11 @@ function NotSeeingIt(): JSX.Element {size="large"centerfullWidth- loading={newlyRequestedVerificationLinkLoading}+ loading={newlyRequestedVerificationCodeLoading}disabledReason={gateReason}- onClick={() => requestVerificationLink(uuid)}+ onClick={() => requestVerificationCode(uuid)}>- Resend email+ Resend code</LemonButton>)}<LemonButton@@ -108,7 +106,7 @@ function NotSeeingIt(): JSX.Element {}function VerificationCodeEntry(): JSX.Element {- const { verificationCode, verificationCodeError, validatedEmailTokenLoading } = useValues(verifyEmailLogic)+ const { verificationCode, verificationCodeError, verificationResultLoading } = useValues(verifyEmailLogic)const { setVerificationCode, submitVerificationCode } = useActions(verifyEmailLogic)return (@@ -119,7 +117,7 @@ function VerificationCodeEntry(): JSX.Element {noValidateonSubmit={(e) => {e.preventDefault()- if (!validatedEmailTokenLoading) {+ if (!verificationResultLoading) {submitVerificationCode()}}}@@ -128,11 +126,11 @@ function VerificationCodeEntry(): JSX.Element {value={verificationCode}onChange={setVerificationCode}onComplete={() => {- if (!validatedEmailTokenLoading) {+ if (!verificationResultLoading) {submitVerificationCode()}}}- disabled={validatedEmailTokenLoading}+ disabled={verificationResultLoading}data-attr="verify-email-code"status={verificationCodeError ? 'danger' : 'default'}/>@@ -147,7 +145,7 @@ function VerificationCodeEntry(): JSX.Element {centerfullWidthhtmlType="submit"- loading={validatedEmailTokenLoading}+ loading={verificationResultLoading}disabledReason={isValidVerificationCode(verificationCode) ? undefined : 'Enter the 6-digit code from your email'}@@ -160,8 +158,7 @@ function VerificationCodeEntry(): JSX.Element {}export function VerifyEmailForm(): JSX.Element {- const { view, uuid, newlyRequestedVerificationLinkLoading, user } = useValues(verifyEmailLogic)- const { requestVerificationLink } = useActions(verifyEmailLogic)+ const { view, uuid, user } = useValues(verifyEmailLogic)const { openSupportForm } = useActions(supportLogic)const notes = NOTES[view ?? 'pending'] ?? NOTES.pending@@ -211,25 +208,15 @@ export function VerifyEmailForm(): JSX.Element {<div className="flex flex-col items-center text-center"><SleepingHog className="block w-auto mx-auto h-28" /><h1 className="m-0 mt-3 font-title text-2xl font-extrabold leading-tight text-primary text-center tracking-tight">- This link fell asleep+ We don't know who to verify</h1><p className="AuthScene__sub mt-2 mb-5 text-sm text-secondary text-center text-pretty">- Verification links last 24 hours, and this one's past its bedtime. Request a fresh one and- we'll get you in.+ Log in with your email and password and we'll send a new code to your inbox.</p><div className="flex w-full flex-col gap-2.5">- {uuid && (- <LemonButton- type="primary"- size="large"- center- fullWidth- loading={newlyRequestedVerificationLinkLoading}- onClick={() => requestVerificationLink(uuid)}- >- Resend verification email- </LemonButton>- )}+ <LemonButton type="primary" size="large" center fullWidth to={urls.login()}>+ Log in+ </LemonButton><LemonButtonsize="large"center@@ -249,21 +236,6 @@ export function VerifyEmailForm(): JSX.Element {)}- if (view === 'verify') {- return (- <AuthScene notes={notes}>- <AuthSceneCard>- <div className="flex flex-col items-center gap-4 text-center">- <Spinner className="text-4xl" />- <p className="AuthScene__sub m-0 text-sm text-secondary text-center text-pretty">- Verifying your email address…- </p>- </div>- </AuthSceneCard>- </AuthScene>- )- }-// pending — check inboxreturn (<AuthScene notes={notes}>diff --git a/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts b/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.tsindex 35ab7994419b..ccb8eea64a54 100644--- a/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts+++ b/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts@@ -61,49 +61,43 @@ const redirectAfterVerification = (location.href = nextUrl || resolvePostVerifyDefault(values)}-export interface ResponseType {+export interface VerificationResultType {success: boolean- errorCode?: string- errorDetail?: string-}--export interface ValidatedTokenResponseType extends ResponseType {- token?: stringuuid?: string}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface verifyEmailLogicValues {user: UserType | null // userLogic- newlyRequestedVerificationLink: boolean | null- newlyRequestedVerificationLinkLoading: boolean+ newlyRequestedVerificationCode: boolean | null+ newlyRequestedVerificationCodeLoading: booleanuuid: string | null- validatedEmailToken: ValidatedTokenResponseType | null- validatedEmailTokenLoading: booleanverificationCode: stringverificationCodeError: string | null- view: 'invalid' | 'pending' | 'success' | 'verify' | null+ verificationResult: VerificationResultType | null+ verificationResultLoading: boolean+ view: 'invalid' | 'pending' | 'success' | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface verifyEmailLogicActions {- requestVerificationLink: (uuid: string) => {+ requestVerificationCode: (uuid: string) => {uuid: string}- requestVerificationLinkFailure: (+ requestVerificationCodeFailure: (error: string,errorObject?: any) => {error: stringerrorObject?: any}- requestVerificationLinkSuccess: (- newlyRequestedVerificationLink: boolean,+ requestVerificationCodeSuccess: (+ newlyRequestedVerificationCode: boolean,payload?: {uuid: string}) => {- newlyRequestedVerificationLink: boolean+ newlyRequestedVerificationCode: booleanpayload?: {uuid: string}@@ -117,8 +111,8 @@ export interface verifyEmailLogicActions {setVerificationCodeError: (error: string | null) => {error: string | null}- setView: (view: 'invalid' | 'pending' | 'success' | 'verify' | null) => {- view: 'invalid' | 'pending' | 'success' | 'verify' | null+ setView: (view: 'invalid' | 'pending' | 'success' | null) => {+ view: 'invalid' | 'pending' | 'success' | null}submitVerificationCode: () => {value: true@@ -131,68 +125,16 @@ export interface verifyEmailLogicActions {errorObject?: any}submitVerificationCodeSuccess: (- validatedEmailToken: ValidatedTokenResponseType | null,+ verificationResult: VerificationResultType | null,payload?: {value: true}) => {- validatedEmailToken: ValidatedTokenResponseType | null+ verificationResult: VerificationResultType | nullpayload?: {value: true}}- validateEmailToken: ({ uuid, token }: { token: string; uuid: string }) => {- uuid: string- token: string- }- validateEmailTokenFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- validateEmailTokenSuccess: (- validatedEmailToken:- | {- 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- }- ) => {- validatedEmailToken:- | {- 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- }- }}export type verifyEmailLogicType = MakeLogicType<verifyEmailLogicValues, verifyEmailLogicActions>@@ -201,55 +143,26 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([path(['scenes', 'authentication', 'verify-email', 'verifyEmailLogic']),connect(() => ({ values: [userLogic, ['user']] })),actions({- setView: (view: 'verify' | 'pending' | 'invalid' | 'success' | null) => ({ view }),+ setView: (view: 'pending' | 'invalid' | 'success' | null) => ({ view }),setUuid: (uuid: string | null) => ({ uuid }),- requestVerificationLink: (uuid: string) => ({ uuid }),+ requestVerificationCode: (uuid: string) => ({ uuid }),setVerificationCode: (code: string) => ({ code }),setVerificationCodeError: (error: string | null) => ({ error }),submitVerificationCode: true,}),loaders(({ actions, values }) => ({- validatedEmailToken: [- null as ValidatedTokenResponseType | null,+ verificationResult: [+ null as VerificationResultType | null,{- validateEmailToken: async ({ uuid, token }: { uuid: string; token: string }, breakpoint) => {- try {- const response = await api.create<PostVerifyResponse>(`api/users/verify_email/`, {- token,- uuid,- })- clearPendingVerificationEmail()- actions.setView('success')- await breakpoint(VERIFY_EMAIL_REDIRECT_DELAY_MS)- redirectAfterVerification(response, values)- return { success: true, token, uuid }- } catch (e: any) {- const user = (values as any).user- if (user?.is_email_verified) {- actions.setView('success')- await breakpoint(VERIFY_EMAIL_REDIRECT_DELAY_MS)- const nextUrl = getRelativeNextPath(- new URLSearchParams(location.search).get('next'),- location- )- // this url is validated in getRelativeNextPath as either being relative or on the same origin- // nosemgrep: javascript.browser.security.open-redirect.js-open-redirect- location.href = nextUrl || resolvePostVerifyDefault(values)- return { success: true, token, uuid }- }- actions.setView('invalid')- return { success: false, errorCode: e.code, errorDetail: e.detail }- }- },submitVerificationCode: async (_, breakpoint) => {const uuid = values.uuidconst code = normalizeVerificationCode(values.verificationCode)if (!uuid) {- return values.validatedEmailToken+ return values.verificationResult}if (!isValidVerificationCode(code)) {actions.setVerificationCodeError('Enter the 6-digit code from your email.')- return values.validatedEmailToken+ return values.verificationResult}try {const response = await api.create<PostVerifyResponse>(`api/users/verify_email/`, {@@ -263,37 +176,30 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([return { success: true, uuid }} catch (e: any) {actions.setVerificationCodeError(verificationCodeErrorMessage(e))- return values.validatedEmailToken+ return values.verificationResult}},},],- newlyRequestedVerificationLink: [+ newlyRequestedVerificationCode: [null as boolean | null,{- requestVerificationLink: async ({ uuid }: { uuid: string }) => {+ requestVerificationCode: async ({ uuid }: { uuid: string }) => {try {await api.create(`api/users/request_email_verification/`, { uuid })- lemonToast.success(- 'A new verification email has been sent to the associated email address. Please check your inbox.'- )+ lemonToast.success('We sent a new code to your email address. Please check your inbox.')// A resend invalidates the previous code, so drop it and its error (the// setVerificationCode reducer clears the error too). The 6-char field is// otherwise full and blocks typing the freshly sent code.actions.setVerificationCode('')- // Show the pending view after a resend - it has the code entry form.actions.setView('pending')return true} catch (e: any) {if (e.code === 'throttled') {- lemonToast.error(- 'You have requested a new verification link too many times. Please try again later.'- )+ lemonToast.error('You have requested a new code too many times. Please try again later.')return false}- lemonToast.error(- 'Requesting verification link failed. Please try again later or contact support.'- )+ lemonToast.error('Requesting a new code failed. Please try again later or contact support.')return false}},@@ -302,7 +208,7 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([})),reducers({view: [- null as 'pending' | 'verify' | 'invalid' | 'success' | null,+ null as 'pending' | 'invalid' | 'success' | null,{setView: (_, { view }) => view,},@@ -328,22 +234,21 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([},],}),- urlToAction(({ actions }) => ({- '/verify_email/:uuid': ({ uuid }) => {+ urlToAction(({ actions }) => {+ const showCodeEntry = ({ uuid }: { uuid?: string }): void => {if (uuid) {actions.setUuid(uuid)actions.setView('pending')}- },- '/verify_email/:uuid/:token': ({ uuid, token }) => {- if (token && uuid) {- actions.setUuid(uuid)- actions.setView('verify')- actions.validateEmailToken({ uuid, token })- }- },- '/verify_email': () => {- actions.setView('invalid')- },- })),+ }+ return {+ '/verify_email/:uuid': showCodeEntry,+ // Emails sent before the switch to codes still carry a link with a token. The token no+ // longer verifies, so land the user on the code entry with a resend button.+ '/verify_email/:uuid/:token': showCodeEntry,+ '/verify_email': () => {+ actions.setView('invalid')+ },+ }+ }),])diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex 85df1fdd812d..536cc93c441a 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -897,7 +897,8 @@ export const routes: Record<string, [Scene | string, string]> = {[urls.onboarding()]: [Scene.Onboarding, 'onboarding'],[urls.verifyEmail()]: [Scene.VerifyEmail, 'verifyEmail'],[urls.verifyEmail(':uuid')]: [Scene.VerifyEmail, 'verifyEmailWithUuid'],- [urls.verifyEmail(':uuid', ':token')]: [Scene.VerifyEmail, 'verifyEmailWithToken'],+ // Links from emails sent before the switch to verification codes.+ [`${urls.verifyEmail(':uuid')}/:token`]: [Scene.VerifyEmail, 'verifyEmailWithToken'],[urls.vercelConnect()]: [Scene.VercelConnect, 'vercelConnect'],[urls.vercelLinkError()]: [Scene.VercelLinkError, 'vercelLinkError'],[urls.agenticAccountMismatch()]: [Scene.AgenticAccountMismatch, 'agenticAccountMismatch'],diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex e50c4e1a427b..9a42e9690b9b 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -202,8 +202,7 @@ export const urls = {twoFactorReset: (userUuid: string, token: string): string => `/reset_2fa/${userUuid}/${token}`,preflight: (): string => '/preflight',signup: (): string => '/signup',- verifyEmail: (userUuid: string = '', token: string = ''): string =>- `/verify_email${userUuid ? `/${userUuid}` : ''}${token ? `/${token}` : ''}`,+ verifyEmail: (userUuid: string = ''): string => `/verify_email${userUuid ? `/${userUuid}` : ''}`,vercelConnect: (): string => '/connect/vercel/link',vercelLinkError: (): string => '/integrations/vercel/link-error',agenticAccountMismatch: (): string => '/agentic/account-mismatch',diff --git a/posthog/admin/admins/user_admin.py b/posthog/admin/admins/user_admin.pyindex 8e14f7871197..938e49f59a71 100644--- a/posthog/admin/admins/user_admin.py+++ b/posthog/admin/admins/user_admin.py@@ -31,7 +31,7 @@ from posthog.admin.inlines.scim_provisioned_user_inline import SCIMProvisionedUsfrom posthog.admin.inlines.totp_device_inline import TOTPDeviceInlinefrom posthog.admin.inlines.user_social_auth_inline import UserSocialAuthInlinefrom posthog.api.authentication import password_reset_token_generator-from posthog.api.email_verification import EmailVerifier+from posthog.api.email_verification import email_verification_code_verifierfrom posthog.api.two_factor_reset import TwoFactorResetVerifierfrom posthog.dataclasses import frozenfrom posthog.helpers.impersonation import get_impersonated_user, is_impersonated@@ -243,7 +243,7 @@ class UserAdmin(DjangoUserAdmin):if request.POST.get("send_verification") == "1":try:if user and not user.is_email_verified:- EmailVerifier.create_token_and_send_email_verification(user)+ email_verification_code_verifier.send_code(user)self.log_change(request, user, "Sent verification email.")messages.success(request, f"Verification email sent to {user.email}")else:diff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex 3f97f9044781..4af6954c2e46 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -47,7 +47,7 @@ from two_factor.views.utils import get_remember_device_cookie, validate_rememberfrom webauthn.helpers import base64url_to_bytes, bytes_to_base64url, options_to_jsonfrom webauthn.helpers.structs import AuthenticatorTransport, PublicKeyCredentialDescriptor-from posthog.api.email_verification import EmailVerifier, is_email_verification_disabled+from posthog.api.email_verification import email_verification_code_verifier, is_email_verification_disabledfrom posthog.caching.login_device_cache import check_and_cache_login_devicefrom posthog.constants import AUTH_BACKEND_DISPLAY_NAMESfrom posthog.email import is_email_available@@ -56,7 +56,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.geoip import get_geoip_propertiesfrom posthog.helpers.dev_login import is_dev_login_allowedfrom posthog.helpers.email_utils import EmailLookupHandler-from posthog.helpers.sso import get_safe_next_url, is_sso_reauth_begin, sso_failure_redirect_url+from posthog.helpers.sso import is_sso_reauth_begin, sso_failure_redirect_urlfrom posthog.helpers.two_factor_session import (CODE_MAX_ATTEMPTS,LOGIN_CODE_VERIFICATION_COUNTER,@@ -200,9 +200,9 @@ class EmailVerificationPending(APIException):super().__init__(detail=user_uuid, code=self.default_code)-def is_email_verified_for_login(user: User, next_url: str | None = None) -> bool:+def is_email_verified_for_login(user: User) -> bool:"""- Send a verification email when the login policy requires it.+ Send a verification code when the login policy requires it.Returns whether login may continue for this user. Legacy users with a nullverification state are still allowed to sign in.@@ -216,7 +216,7 @@ def is_email_verified_for_login(user: User, next_url: str | None = None) -> boolif is_email_verification_disabled(user):return True- EmailVerifier.create_token_and_send_email_verification(user, next_url)+ email_verification_code_verifier.send_code(user)if user.is_email_verified is False:return False@@ -227,16 +227,6 @@ def is_email_verified_for_login(user: User, next_url: str | None = None) -> boolclass LoginSerializer(serializers.Serializer):email = serializers.EmailField()password = serializers.CharField()- next = serializers.CharField(- required=False,- allow_blank=True,- write_only=True,- help_text=(- "Relative path to resume after login (e.g. an /oauth/authorize URL). "- "Embedded into email verification / login-verification links so the flow "- "can continue after the email step. Ignored unless it is a safe same-origin path."- ),- )def to_representation(self, instance: Any) -> dict[str, Any]:return {"success": True}@@ -295,7 +285,6 @@ class LoginSerializer(serializers.Serializer):)request = self.context["request"]- next_url = get_safe_next_url(validated_data.get("next"), request)existing_user = User.objects.filter(email__iexact=validated_data["email"]).first()evaluate_auth_attempt(@@ -338,15 +327,10 @@ class LoginSerializer(serializers.Serializer):raise serializers.ValidationError("Invalid email or password.", code="invalid_credentials")- if not is_email_verified_for_login(user, next_url):- if EmailVerifier.use_verification_code(user):- # A fresh code was just emailed; hand the frontend the uuid so it can route to- # the code entry page. The legacy link flow keeps the plain error below.- raise EmailVerificationPending(str(user.uuid))- raise serializers.ValidationError(- "Your account is awaiting verification. Please check your email for a verification link.",- code="not_verified",- )+ if not is_email_verified_for_login(user):+ # A fresh code was just emailed; hand the frontend the uuid so it can route to+ # the code entry page.+ raise EmailVerificationPending(str(user.uuid))# Domain enforcement: refuse blocked members — blocked admins still get a gated session.if not resolve_login_organization(user):diff --git a/posthog/api/email_verification.py b/posthog/api/email_verification.pyindex 10a80cc17702..9f94062d1f09 100644--- a/posthog/api/email_verification.py+++ b/posthog/api/email_verification.py@@ -1,8 +1,5 @@import time-from django.contrib.auth.models import AbstractBaseUser-from django.contrib.auth.tokens import PasswordResetTokenGenerator-import structlogfrom rest_framework import exceptions@@ -11,12 +8,11 @@ from posthog.helpers.two_factor_session import (CODE_MAX_ATTEMPTS,CODE_TTL_SECONDS,code_based_verification_token_generator,- is_code_based_verification_globally_disabled,)from posthog.models.user import Userfrom posthog.ph_client import feature_enabled_or_falsefrom posthog.redis import get_client-from posthog.tasks.email import send_email_verification, send_email_verification_code+from posthog.tasks.email import send_email_verification_codelogger = structlog.get_logger(__name__)@@ -36,19 +32,6 @@ def is_email_verification_disabled(user: User) -> bool:)-class EmailVerificationTokenGenerator(PasswordResetTokenGenerator):- def _make_hash_value(self, user: AbstractBaseUser, timestamp):- # Due to type differences between the user model and the token generator, we need to- # re-fetch the user from the database to get the correct type.- usable_user: User = User.objects.get(pk=user.pk)- login_timestamp = "" if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None)-- return f"{usable_user.pk}{usable_user.email}{usable_user.is_email_verified}{usable_user.pending_email}{login_timestamp}{timestamp}"---email_verification_token_generator = EmailVerificationTokenGenerator()--class EmailVerificationCodeVerifier:"""Issues and checks the 6-digit code for signup and email-change verification.@@ -57,9 +40,9 @@ class EmailVerificationCodeVerifier:closes the tab or opens the app in a different browser. The code itself is derived by`code_based_verification_token_generator` and never stored.- The stored target address does for codes what the `pending_email` hash input does for link- tokens: a code verifies only the address it was issued for. One Redis slot per user means- a new code always invalidates the previous one.+ The stored target address binds a code to the address it was issued for: an email-change+ code verifies only the staged address. One Redis slot per user means a new code always+ invalidates the previous one.The attempt budget is separate from the code. It is not reset by issuing a new code, becausethe resend endpoint is public: a reset there would let a caller alternate resends and guesses@@ -75,11 +58,10 @@ class EmailVerificationCodeVerifier:def _attempts_key(user_id: int) -> str:return f"{EMAIL_CODE_ATTEMPTS_REDIS_KEY_PREFIX}:{user_id}"- def send_code(self, user: User, target_email: str | None = None) -> bool:+ def send_code(self, user: User, target_email: str | None = None) -> None:"""Issue a fresh code and email it to the address it authorizes.- Returns False when the code was not issued or sent, so the caller can send the- link email instead."""+ `target_email` is the staged address of an email change. Signup sends leave it None."""try:# Signup verification always proves the account address. Only a verified user's# email change targets the staged address; an unverified user's staged change must@@ -97,11 +79,12 @@ class EmailVerificationCodeVerifier:# Write the state before the send, so a delivered code can always verify.get_client().set(self._state_key(user.pk), f"{issued_at}:{target or ''}", ex=CODE_TTL_SECONDS)send_email_verification_code(user.pk, code, target)- return Trueexcept Exception as e:logger.exception("Email verification code send failed", user_id=user.pk, error=str(e))capture_exception(Exception(f"Email verification code send failed: {e}"))- return False+ raise exceptions.APIException(+ detail="Could not send the verification code. Please try again by logging in with your email and password."+ )def _get_state(self, user: User) -> tuple[int, str] | None:"""Return (issued_at, target_email) for the pending code. target_email is '' for signup."""@@ -159,38 +142,3 @@ class EmailVerificationCodeVerifier:email_verification_code_verifier = EmailVerificationCodeVerifier()---class EmailVerifier:- @staticmethod- def use_verification_code(user: User) -> bool:- """Signup and email-change verification use an emailed code. The code-based-verification- kill-switch reverts both to the token-link flow."""- return (not user.is_email_verified or bool(user.pending_email)) and (- not is_code_based_verification_globally_disabled()- )-- @staticmethod- def create_token_and_send_email_verification(user: User, next_url: str | None = None) -> None:- if EmailVerifier.use_verification_code(user) and email_verification_code_verifier.send_code(user):- return- token = email_verification_token_generator.make_token(user)- EmailVerifier.send_verification_email(user, token, next_url=next_url)-- @staticmethod- def send_verification_email(- user: User, token: str, next_url: str | None = None, target_email: str | None = None- ) -> None:- # `target_email` pins the recipient to the address the token authorizes; callers with a- # stable email leave it None and the recipient falls back to the user's pending_email.- try:- send_email_verification(user.pk, token, next_url, target_email)- except Exception as e:- capture_exception(Exception(f"Verification email failed: {e}"))- raise exceptions.APIException(- detail="Could not send email verification email. Please try again by logging in with your email and password."- )-- @staticmethod- def check_token(user: User, token: str) -> bool:- return email_verification_token_generator.check_token(user, token)diff --git a/posthog/api/signup.py b/posthog/api/signup.pyindex 008149938bfe..7b9002ebcc34 100644--- a/posthog/api/signup.py+++ b/posthog/api/signup.py@@ -22,7 +22,7 @@ from social_core.pipeline.partial import partialfrom social_django.strategy import DjangoStrategyfrom webauthn.helpers import base64url_to_bytes-from posthog.api.email_verification import EmailVerifier, is_email_verification_disabled+from posthog.api.email_verification import email_verification_code_verifier, is_email_verification_disabledfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.webauthn import (WEBAUTHN_SIGNUP_CREDENTIAL_KEY,@@ -60,13 +60,7 @@ def _save_session_with_recovery(session: SessionBase) -> None:def verify_email_or_login(request: Request, user: User) -> None:if is_email_available() and not user.is_email_verified and not is_email_verification_disabled(user):- next_url = request.data.get("next_url") if request and request.data else None-- # We only want to redirect to a relative url so that we don't redirect away from the current domain- if is_relative_url(next_url):- EmailVerifier.create_token_and_send_email_verification(user, next_url)- else:- EmailVerifier.create_token_and_send_email_verification(user)+ email_verification_code_verifier.send_code(user)else:login(request, user, backend="django.contrib.auth.backends.ModelBackend")diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.pyindex ea24c8fc3fdc..83e46cfb0290 100644--- a/posthog/api/test/test_authentication.py+++ b/posthog/api/test/test_authentication.py@@ -527,27 +527,6 @@ class TestLoginAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)self.assertEqual(response.json()["code"], "verified_domain_required")- @patch("posthog.api.authentication.is_email_available", return_value=True)- @patch("posthog.api.authentication.EmailVerifier.create_token_and_send_email_verification")- def test_email_unverified_user_cant_log_in_if_email_available(- self, mock_send_email_verification, mock_is_email_available- ):- self.user.is_email_verified = False- self.user.save()- self.assertEqual(self.user.is_email_verified, False)- response = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)-- # Test that we're not logged in- response = self.client.get("/api/users/@me/")- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)-- mock_is_email_available.assert_called_once()-- # Assert the email was sent.- mock_send_email_verification.assert_called_once_with(self.user, None)-- @pytest.mark.disable_mock_email_code_verification@patch("posthog.api.authentication.is_email_available", return_value=True)@patch("posthog.api.email_verification.send_email_verification_code")def test_email_unverified_login_returns_verify_email_pending_with_uuid(@@ -566,30 +545,8 @@ class TestLoginAPI(APIBaseTest):response = self.client.get("/api/users/@me/")self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)- @parameterized.expand(- [- # A relative `next` (e.g. an /oauth/authorize continuation) must be forwarded so the- # verification link can resume the flow.- ("safe_relative_next", "/oauth/authorize/?client_id=x", "/oauth/authorize/?client_id=x"),- # An off-origin `next` must be dropped.- ("unsafe_off_origin_next", "https://evil.example.com/steal", None),- ]- )- @patch("posthog.api.authentication.is_email_available", return_value=True)- @patch("posthog.api.authentication.EmailVerifier.create_token_and_send_email_verification")- def test_email_verification_link_carries_safe_next(- self, _name, next_input, expected, mock_send_email_verification, mock_is_email_available- ):- self.user.is_email_verified = False- self.user.save()- self.client.post(- "/api/login",- {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD, "next": next_input},- )- mock_send_email_verification.assert_called_once_with(self.user, expected)-@patch("posthog.api.authentication.is_email_available", return_value=True)- @patch("posthog.api.authentication.EmailVerifier.create_token_and_send_email_verification")+ @patch("posthog.api.authentication.email_verification_code_verifier.send_code")@patch("posthog.api.authentication.is_email_verification_disabled", return_value=True)def test_email_unverified_user_can_log_in_if_email_available_but_verification_disabled_flag_is_true(self, mock_is_verification_disabled, mock_send_email_verification, mock_is_email_available@@ -611,7 +568,7 @@ class TestLoginAPI(APIBaseTest):mock_send_email_verification.assert_not_called()@patch("posthog.api.authentication.is_email_available", return_value=True)- @patch("posthog.api.authentication.EmailVerifier.create_token_and_send_email_verification")+ @patch("posthog.api.authentication.email_verification_code_verifier.send_code")def test_email_unverified_null_user_can_log_in_if_email_available(self, mock_send_email_verification, mock_is_email_available):@@ -626,7 +583,7 @@ class TestLoginAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)mock_is_email_available.assert_called_once()# Assert the email was sent.- mock_send_email_verification.assert_called_once_with(self.user, None)+ mock_send_email_verification.assert_called_once_with(self.user)@patch("posthoganalytics.capture")def test_user_cant_login_with_incorrect_password(self, mock_capture):diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex 51d994e546bc..3237f48239d7 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -151,7 +151,7 @@ class TestSignupAPI(APIBaseTest):self.assertEqual(event_props["$set"]["referral_source_ai_prompt"], "What is the best product analytics tool?")@patch("posthog.api.signup.is_email_available", return_value=True)- @patch("posthog.api.signup.EmailVerifier.create_token_and_send_email_verification")+ @patch("posthog.api.signup.email_verification_code_verifier.send_code")def test_api_sign_up_requires_verification(self, mock_email_verifier, mock_is_email_available):# Ensure the internal system metrics org doesn't prevent org-creationOrganization.objects.create(name="PostHog Internal Metrics", for_internal_metrics=True)@@ -196,7 +196,7 @@ class TestSignupAPI(APIBaseTest):mock_email_verifier.assert_called_once_with(user)@patch("posthog.api.signup.is_email_available", return_value=True)- @patch("posthog.api.signup.EmailVerifier.create_token_and_send_email_verification")+ @patch("posthog.api.signup.email_verification_code_verifier.send_code")@patch("posthog.api.signup.is_email_verification_disabled", return_value=True)def test_api_sign_up_doesnt_require_verification_if_disabled(self,@@ -1480,7 +1480,7 @@ class TestSignupAPI(APIBaseTest):self.assertFalse(WebauthnCredential.objects.filter(user=existing_user).exists())@patch("posthog.api.signup.is_email_available", return_value=True)- @patch("posthog.api.signup.EmailVerifier.create_token_and_send_email_verification")+ @patch("posthog.api.signup.email_verification_code_verifier.send_code")def test_api_sign_up_preserves_next_param(self, mock_email_verifier, mock_is_email_available):Organization.objects.create(name="PostHog Internal Metrics", for_internal_metrics=True)@@ -1504,10 +1504,10 @@ class TestSignupAPI(APIBaseTest):response_data["redirect_url"],f"/verify_email/{user.uuid}?next=%2Fnext_path",)- mock_email_verifier.assert_called_once_with(user, "/next_path")+ mock_email_verifier.assert_called_once_with(user)@patch("posthog.api.signup.is_email_available", return_value=True)- @patch("posthog.api.signup.EmailVerifier.create_token_and_send_email_verification")+ @patch("posthog.api.signup.email_verification_code_verifier.send_code")def test_api_sign_up_preserves_oauth_next_param_with_query_string(self, mock_email_verifier, mock_is_email_available):@@ -1535,7 +1535,7 @@ class TestSignupAPI(APIBaseTest):response_data["redirect_url"],f"/verify_email/{user.uuid}?next={expected_encoded}",)- mock_email_verifier.assert_called_once_with(user, oauth_url)+ mock_email_verifier.assert_called_once_with(user)@pytest.mark.skip_on_multitenancy@patch("posthog.utils.get_ip_address", return_value="192.168.1.100")@@ -2898,7 +2898,7 @@ class TestInviteSignupAPI(APIBaseTest):)@patch("posthog.api.signup.is_email_available", return_value=True)- @patch("posthog.api.signup.EmailVerifier.create_token_and_send_email_verification")+ @patch("posthog.api.signup.email_verification_code_verifier.send_code")def test_api_social_invite_sign_up_if_email_verification_on(self, email_mock, email_available_mock):"""Test to make sure that social signups skip email verification"""Organization.objects.all().delete() # Can only create organizations in fresh instancesdiff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 783ef858be4c..7c070e73ebf0 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -1,3 +1,4 @@+import reimport uuidimport datetimefrom datetime import timedelta@@ -10,7 +11,6 @@ from posthog.test.base import APIBaseTest, NonAtomicBaseTestfrom unittest import mockfrom unittest.mock import ANY, patch-from django.contrib.auth.tokens import default_token_generatorfrom django.core import mailfrom django.core.cache import cachefrom django.db import connection@@ -25,7 +25,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom social_django.models import UserSocialAuth-from posthog.api.email_verification import email_verification_code_verifier, email_verification_token_generator+from posthog.api.email_verification import email_verification_code_verifierfrom posthog.api.oauth.toolbar_service import ToolbarOAuthState, build_toolbar_oauth_state, new_state_noncefrom posthog.api.user import UserSerializerfrom posthog.constants import AvailableFeature@@ -54,6 +54,13 @@ def create_user(email: str, password: str, organization: Organization):return User.objects.create_and_join(organization, email, password)+def issue_verification_code(user: User, target_email: str | None = None) -> str:+ """Issue a code for `user` and capture it at the send boundary instead of reading the email."""+ with patch("posthog.api.email_verification.send_email_verification_code") as mock_send:+ email_verification_code_verifier.send_code(user, target_email=target_email)+ return mock_send.call_args[0][1]++class TestUserAPI(APIBaseTest):new_org: Organization = None # type: ignorenew_project: Team = None # type: ignore@@ -818,15 +825,16 @@ class TestUserAPI(APIBaseTest):@patch("posthog.api.user.is_email_available", return_value=True)@patch("posthog.tasks.email.send_email_change_emails.delay")- @patch("posthog.api.email_verification.send_email_verification")+ @patch("posthog.api.email_verification.send_email_verification_code")def test_notifications_sent_when_user_email_is_changed_and_email_available(self,- mock_send_email_verification,+ mock_send_code,mock_send_email_change_emails,mock_is_email_available,):- """Test that when a user updates their email, they receive a verification email before the switch actually happens."""+ """Test that when a user updates their email, they receive a verification code before the switch actually happens."""self.user.email = "[email protected]"+ self.user.is_email_verified = Trueself.user.save()with self.is_cloud(True):with freeze_time("2020-01-01T21:37:00+00:00"):@@ -846,13 +854,12 @@ class TestUserAPI(APIBaseTest):assert self.user.pending_email == "[email protected]"mock_is_email_available.assert_called_once()- mock_send_email_verification.assert_called_once()+ mock_send_code.assert_called_once_with(self.user.pk, ANY, "[email protected]")- token = email_verification_token_generator.make_token(self.user)with freeze_time("2020-01-01T21:37:00+00:00"):response = self.client.post(f"/api/users/verify_email/",- {"uuid": self.user.uuid, "token": token},+ {"uuid": self.user.uuid, "code": mock_send_code.call_args[0][1]},)self.assertEqual(response.status_code, status.HTTP_200_OK)@@ -932,6 +939,7 @@ class TestUserAPI(APIBaseTest):)def test_verified_email_change_removes_social_auth_connections(self, _, social_auths: list[tuple[str, str]]):self.user.email = "[email protected]"+ self.user.is_email_verified = Trueself.user.save()social_auth_ids = [@@ -946,7 +954,7 @@ class TestUserAPI(APIBaseTest):with (patch("posthog.api.user.is_email_available", return_value=True) as mock_is_email_available,patch("posthog.tasks.email.send_email_change_emails.delay") as mock_send_email_change_emails,- patch("posthog.api.email_verification.send_email_verification") as mock_send_email_verification,+ patch("posthog.api.email_verification.send_email_verification_code") as mock_send_code,):with self.is_cloud(True):response = self.client.patch(@@ -958,12 +966,11 @@ class TestUserAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKmock_is_email_available.assert_called_once()- mock_send_email_verification.assert_called_once()+ mock_send_code.assert_called_once()- token = email_verification_token_generator.make_token(self.user)response = self.client.post("/api/users/verify_email/",- {"uuid": self.user.uuid, "token": token},+ {"uuid": self.user.uuid, "code": mock_send_code.call_args[0][1]},)assert response.status_code == status.HTTP_200_OK@@ -1014,10 +1021,10 @@ class TestUserAPI(APIBaseTest):mock_send_email_change_emails.assert_not_called()@patch("posthog.api.user.is_email_available", return_value=True)- @patch("posthog.api.user.EmailVerifier.send_verification_email")+ @patch("posthog.api.email_verification.send_email_verification_code")def test_email_change_allowed_between_two_sso_enforced_domains_of_same_org(self,- mock_send_email_verification,+ mock_send_code,mock_is_email_available,):self.user.email = "[email protected]"@@ -1042,7 +1049,7 @@ class TestUserAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKself.user.refresh_from_db()assert self.user.pending_email == "[email protected]"- mock_send_email_verification.assert_called_once()+ mock_send_code.assert_called_once()@patch("posthog.api.user.is_email_available", return_value=True)@patch("posthog.tasks.email.send_email_change_emails.delay")@@ -1090,11 +1097,8 @@ class TestUserAPI(APIBaseTest):uid="google-sub-1",)- token = email_verification_token_generator.make_token(self.user)- response = self.client.post(- "/api/users/verify_email/",- {"uuid": self.user.uuid, "token": token},- )+ code = issue_verification_code(self.user)+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})assert response.status_code == status.HTTP_200_OKself.user.refresh_from_db()@@ -1104,15 +1108,16 @@ class TestUserAPI(APIBaseTest):@patch("posthog.api.user.login")@patch("posthog.tasks.email.send_email_change_emails.delay")def test_email_change_verification_skips_auto_login_for_sso_enforced_domain(self, _, mock_login):+ self.user.is_email_verified = Trueself.user.pending_email = "[email protected]"self.user.save()+ code = issue_verification_code(self.user)with patch("posthog.models.organization_domain.OrganizationDomainManager.get_sso_enforcement_for_email_address",side_effect=lambda email, organization=None: "google-oauth2" if email == "[email protected]" else None,):- token = email_verification_token_generator.make_token(self.user)- response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "token": token})+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})assert response.status_code == status.HTTP_200_OKassert response.json()["requires_sso"] is True@@ -1127,13 +1132,13 @@ class TestUserAPI(APIBaseTest):self.user.email = "[email protected]"self.user.pending_email = Noneself.user.save()+ code = issue_verification_code(self.user)with patch("posthog.models.organization_domain.OrganizationDomainManager.get_sso_enforcement_for_email_address",side_effect=lambda email, organization=None: "google-oauth2" if email == "[email protected]" else None,):- token = email_verification_token_generator.make_token(self.user)- response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "token": token})+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})assert response.status_code == status.HTTP_200_OKassert response.json()["requires_sso"] is True@@ -1153,8 +1158,8 @@ class TestUserAPI(APIBaseTest):domain="hogflix.com", organization=self.organization, verified_at=timezone.now())- token = email_verification_token_generator.make_token(self.user)- response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "token": token})+ code = issue_verification_code(self.user)+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})assert response.status_code == status.HTTP_200_OKassert response.json()["requires_login"] is True@@ -2853,16 +2858,10 @@ class TestEmailVerificationAPI(APIBaseTest):self.assertEqual(mail.outbox[0].body, "") # no plain-text version support yethtml_message = mail.outbox[0].alternatives[0][0] # type: ignore- self.validate_basic_html(- html_message,- "https://my.posthog.net",- preheader="Please follow the link inside to verify your account.",- )- link_index = html_message.find("https://my.posthog.net/verify_email")- reset_link = html_message[link_index : html_message.find('"', link_index)]- token = reset_link.replace("https://my.posthog.net/verify_email/", "").replace(f"{self.user.uuid}/", "")+ code = re.search(r"(\d{6}) is your code\.", html_message).group(1) # type: ignore[union-attr]+ self.validate_basic_html(html_message, "https://my.posthog.net", preheader=f"{code} is your code.")- response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "token": token})+ response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})self.assertEqual(response.status_code, status.HTTP_200_OK)# check is_email_verified is changed to True@@ -2886,14 +2885,7 @@ class TestEmailVerificationAPI(APIBaseTest):properties={"$set": ANY},)- mock_capture.assert_any_call(- event="verification email sent",- distinct_id=self.user.distinct_id,- groups={- "organization": str(self.team.organization_id),- },- )- self.assertEqual(mock_capture.call_count, 3)+ self.assertEqual(mock_capture.call_count, 2)def test_cant_verify_if_email_is_not_configured(self):set_instance_setting("EMAIL_HOST", "")@@ -2932,14 +2924,9 @@ class TestEmailVerificationAPI(APIBaseTest):# Three emails should be sent, fourth should notself.assertEqual(len(mail.outbox), 6)- # Token validation-- def test_can_validate_email_verification_token(self):- token = email_verification_token_generator.make_token(self.user)- response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "token": token})- self.assertEqual(response.status_code, status.HTTP_200_OK)+ # Code validation- def test_cant_validate_email_verification_token_without_a_token(self):+ def test_cant_verify_email_without_a_code(self):response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid})self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(@@ -2948,88 +2935,23 @@ class TestEmailVerificationAPI(APIBaseTest):"type": "validation_error","code": "required","detail": "This field is required.",- "attr": "token",+ "attr": "code",},)- def test_invalid_verification_token_returns_error(self):- valid_token = default_token_generator.make_token(self.user)-- with freeze_time(timezone.now() - datetime.timedelta(seconds=86_401)):- # tokens expire after one day- expired_token = default_token_generator.make_token(self.user)-- for token in [- valid_token[:-1],- "not_even_trying",- self.user.uuid,- expired_token,- ]:- response = self.client.post(- f"/api/users/verify_email/",- {"uuid": self.user.uuid, "token": token},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(- response.json(),- {- "type": "validation_error",- "code": "invalid_token",- "detail": "This verification token is invalid or has expired.",- "attr": "token",- },- )-- def test_reused_token_reports_already_verified_without_a_session(self):- token = email_verification_token_generator.make_token(self.user)- response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "token": token})- self.assertEqual(response.status_code, status.HTTP_200_OK)-- # A second use (double click, or the link prefetched by an email scanner) reports success- # for the already-verified address, but must not hand out a session: the spent token no- # longer proves anything.- self.client.logout()- response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "token": token})- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json(), {"success": True, "requires_login": True})- assert self.client.session.get("_auth_user_id") is None-- def test_already_verified_user_gets_success_even_with_a_bad_token(self):+ def test_already_verified_user_gets_success_even_with_a_wrong_code(self):self.user.is_email_verified = Trueself.user.save()- response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "token": "garbage"})+ response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "code": "000000"})self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json(), {"success": True, "requires_login": True})assert self.client.session.get("_auth_user_id") is None- def test_email_verification_logs_in_user(self):- token = email_verification_token_generator.make_token(self.user)-- self.client.logout()- assert self.client.get("/api/users/@me/").status_code == 401- session_user_id = self.client.session.get("_auth_user_id")- assert session_user_id is None-- # NOTE: Posting sets the session user id but doesn't log in the test client hence we just check the session id- self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "token": token})- session_user_id = self.client.session.get("_auth_user_id")- assert session_user_id == str(self.user.id)-- def test_email_verification_logs_in_correctuser(self):- other_token = email_verification_token_generator.make_token(self.other_user)- self.client.logout()- assert self.client.session.get("_auth_user_id") is None-- # NOTE: The user id in path should basically be ignored- self.client.post(f"/api/users/verify_email/", {"uuid": self.other_user.uuid, "token": other_token})- session_user_id = self.client.session.get("_auth_user_id")- assert session_user_id == str(self.other_user.id)-def test_email_verification_does_not_apply_to_current_logged_in_user(self):- other_token = email_verification_token_generator.make_token(self.other_user)+ other_code = issue_verification_code(self.other_user)- res = self.client.post(f"/api/users/verify_email/", {"uuid": self.other_user.uuid, "token": other_token})+ res = self.client.post(f"/api/users/verify_email/", {"uuid": self.other_user.uuid, "code": other_code})assert res.status_code == status.HTTP_200_OKself.user.refresh_from_db()self.other_user.refresh_from_db()@@ -3038,53 +2960,34 @@ class TestEmailVerificationAPI(APIBaseTest):assert not self.user.is_email_verifiedassert self.other_user.is_email_verified- def test_email_verification_fails_if_using_other_accounts_token(self):- token = email_verification_token_generator.make_token(self.user)- other_token = email_verification_token_generator.make_token(self.other_user)+ def test_email_verification_fails_if_using_other_accounts_code(self):+ code = issue_verification_code(self.user)+ other_code = issue_verification_code(self.other_user)self.client.logout()assert (- self.client.post(f"/api/users/verify_email/", {"uuid": self.other_user.uuid, "token": token}).status_code+ self.client.post(f"/api/users/verify_email/", {"uuid": self.other_user.uuid, "code": code}).status_code== status.HTTP_400_BAD_REQUEST)assert (- self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "token": other_token}).status_code+ self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "code": other_code}).status_code== status.HTTP_400_BAD_REQUEST)- def test_does_not_apply_pending_email_for_old_tokens(self):- self.client.logout()-- token = email_verification_token_generator.make_token(self.user)- self.user.pending_email = "[email protected]"- self.user.save()-- response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "token": token})- assert response.status_code == status.HTTP_400_BAD_REQUEST- assert self.user.email != "[email protected]"- assert self.user.pending_email == "[email protected]"-- token = email_verification_token_generator.make_token(self.user)- response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "token": token})- assert response.status_code == status.HTTP_200_OK- self.user.refresh_from_db()- assert self.user.email == "[email protected]"- assert self.user.pending_email is None-def test_email_verification_does_not_log_in_user_with_2fa_totp(self):# If the user has a TOTP device configured, verifying their email must# NOT silently establish an authenticated session — otherwise an# attacker with access to the email inbox could bypass 2FA entirely.TOTPDevice.objects.create(user=self.user, name="default", confirmed=True)- token = email_verification_token_generator.make_token(self.user)+ code = issue_verification_code(self.user)self.client.logout()assert self.client.session.get("_auth_user_id") is None- response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "token": token})+ response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})assert response.status_code == status.HTTP_200_OK- assert response.json() == {"success": True, "token": token, "requires_2fa": True}+ assert response.json() == {"success": True, "requires_2fa": True}# Email should still be marked verified, but the session must remain unauthenticated.self.user.refresh_from_db()@@ -3112,7 +3015,8 @@ class TestEmailVerificationAPI(APIBaseTest):def test_can_request_verification_for_pending_email_change(self):# An already-verified user who initiated an email change still needs to- # verify the new address — re-requesting the verification link must work.+ # verify the new address, so re-requesting the code must work.+ set_instance_setting("EMAIL_HOST", "localhost")self.user.is_email_verified = Trueself.user.pending_email = "[email protected]"self.user.save()@@ -3124,7 +3028,6 @@ class TestEmailVerificationAPI(APIBaseTest):self.assertEqual(mail.outbox[0].to, ["[email protected]"])[email protected]_mock_email_code_verificationclass TestEmailVerificationCodeAPI(APIBaseTest):CONFIG_AUTO_LOGIN = False@@ -3265,18 +3168,6 @@ class TestEmailVerificationCodeAPI(APIBaseTest):self.assertEqual(response.json(), {"success": True, "requires_login": True})assert self.client.session.get("_auth_user_id") is None- def test_code_send_failure_falls_back_to_link_email(self):- with patch(- "posthog.api.email_verification.send_email_verification_code",- side_effect=Exception("template missing"),- ):- with self.settings(CELERY_TASK_ALWAYS_EAGER=True, SITE_URL="https://my.posthog.net"):- response = self.client.post("/api/users/request_email_verification/", {"uuid": self.user.uuid})- self.assertEqual(response.status_code, status.HTTP_200_OK)- assert len(mail.outbox) == 1- html_message = mail.outbox[0].alternatives[0][0] # type: ignore- assert f"https://my.posthog.net/verify_email/{self.user.uuid}/" in html_message-@parameterized.expand([("verified", True), ("legacy_never_verified", None)])def test_email_change_code_goes_to_the_pending_address_and_completes_the_swap(self, _name, is_email_verified):self.user.is_email_verified = is_email_verifieddiff --git a/posthog/api/test/test_user_auth_session.py b/posthog/api/test/test_user_auth_session.pyindex e0359a276971..e558f5b1a155 100644--- a/posthog/api/test/test_user_auth_session.py+++ b/posthog/api/test/test_user_auth_session.py@@ -18,7 +18,7 @@ from django.urls import reversefrom django.utils import timezonefrom posthog.api.authentication import password_reset_token_generator-from posthog.api.email_verification import email_verification_token_generator+from posthog.api.email_verification import email_verification_code_verifierfrom posthog.models import Userfrom posthog.models.activity_logging.signal_handlers import post_loginfrom posthog.models.webauthn_credential import WebauthnCredential@@ -442,11 +442,14 @@ class TestRevokeOnCredentialChange(APIBaseTest):@patch("posthog.tasks.email.send_email_change_emails.delay")def test_email_change_revokes_other_sessions(self, _mock_email):other = self._other_session()+ self.user.is_email_verified = Trueself.user.pending_email = "[email protected]"self.user.save()- token = email_verification_token_generator.make_token(self.user)+ with patch("posthog.api.email_verification.send_email_verification_code") as mock_send:+ email_verification_code_verifier.send_code(self.user)+ code = mock_send.call_args[0][1]- response = self.client.post("/api/users/verify_email/", {"uuid": str(self.user.uuid), "token": token})+ response = self.client.post("/api/users/verify_email/", {"uuid": str(self.user.uuid), "code": code})self.assertEqual(response.status_code, 200, response.content)self.assertFalse(Session.objects.filter(session_key=other.session_key).exists())diff --git a/posthog/api/test/test_webauthn.py b/posthog/api/test/test_webauthn.pyindex aaae20ff3543..64d34a80c943 100644--- a/posthog/api/test/test_webauthn.py+++ b/posthog/api/test/test_webauthn.py@@ -238,7 +238,7 @@ class TestWebAuthnLogin(APIBaseTest):self.assertEqual(me_response.json()["email"], self.user.email)@patch("posthog.api.authentication.is_email_available", return_value=True)- @patch("posthog.api.authentication.EmailVerifier.create_token_and_send_email_verification")+ @patch("posthog.api.authentication.email_verification_code_verifier.send_code")@patch("posthog.auth.verify_passkey_authentication_response")def test_login_blocks_explicitly_unverified_email_accounts(self, mock_verify, mock_send_email_verification, mock_is_email_available@@ -277,7 +277,7 @@ class TestWebAuthnLogin(APIBaseTest):self.assertEqual(me_response.status_code, status.HTTP_401_UNAUTHORIZED)mock_is_email_available.assert_called_once()- mock_send_email_verification.assert_called_once_with(self.user, None)+ mock_send_email_verification.assert_called_once_with(self.user)@patch("posthog.auth.verify_passkey_authentication_response")def test_login_with_unverified_credential_fails(self, mock_verify):diff --git a/posthog/api/user.py b/posthog/api/user.pyindex e79228ae1077..7c9d6daff04b 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -47,11 +47,7 @@ from two_factor.utils import default_devicefrom posthog.schema import UserUIConfiguration-from posthog.api.email_verification import (- EmailVerifier,- email_verification_code_verifier,- email_verification_token_generator,-)+from posthog.api.email_verification import email_verification_code_verifierfrom posthog.api.oauth.toolbar_service import (ToolbarOAuthError,ToolbarOAuthState,@@ -237,26 +233,17 @@ class PendingInviteSerializer(serializers.Serializer):class VerifyEmailRequestSerializer(serializers.Serializer):- """Request body for POST /api/users/verify_email/. Exactly one of token or code is required."""+ """Request body for POST /api/users/verify_email/."""- # A string, not a UUIDField: the E2E test sentinel is not a UUID, and an unknown uuid must- # answer the same way as a wrong credential rather than as a shape error.+ # A string, not a UUIDField: an unknown uuid must answer the same way as a wrong code rather+ # than as a shape error.uuid = serializers.CharField(help_text="UUID of the user whose email is being verified.")- token = serializers.CharField(- required=False,- allow_blank=True,- help_text="Verification token from the emailed link. Required unless a code is provided.",- )code = serializers.CharField(- required=False,- allow_blank=True,- help_text="The 6-digit verification code emailed at signup. Whitespace, invisible characters, "+ help_text="The 6-digit verification code from the email. Whitespace, invisible characters, ""and grouping hyphens are removed and compatibility digits are folded to ASCII before checking.",)def validate_code(self, value: str) -> str:- if not value:- return value# Same rule as the login code: exactly 6 digits after normalization, so malformed input is# rejected here and never reaches the attempt budget.cleaned = normalize_verification_code(value)@@ -264,11 +251,6 @@ class VerifyEmailRequestSerializer(serializers.Serializer):raise serializers.ValidationError("Enter the 6-digit code from your email.")return cleaned- def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:- if not attrs.get("token") and not attrs.get("code"):- raise serializers.ValidationError({"token": ["This field is required."]}, code="required")- return attrs-class OnboardingSkipRequestSerializer(serializers.Serializer):"""Request body for POST /api/users/{id}/onboarding/skip/.@@ -896,23 +878,11 @@ class UserSerializer(serializers.ModelSerializer):code="sso_enforced_new_email",)validated_data.pop("email", None) # staged as pending_email below, not written to `email` directly- # Serialize concurrent email changes for this user under a row lock so the token is- # minted against one consistent pending_email. Without it, interleaved requests can- # bind a token to one address but deliver its verification email to another.- with transaction.atomic():- User.objects.select_for_update().get(pk=instance.pk)- instance.pending_email = new_email- instance.save(update_fields=["pending_email"])- token = email_verification_token_generator.make_token(instance)- # Send after the transaction commits (never inside the atomic block), pinning the- # recipient to the captured address so a later pending_email change can't redirect- # this verification email. The code path stores that address as the code's target,- # so a stale code stops verifying once a different address is staged.- if not (- EmailVerifier.use_verification_code(instance)- and email_verification_code_verifier.send_code(instance, target_email=new_email)- ):- EmailVerifier.send_verification_email(instance, token, target_email=new_email)+ instance.pending_email = new_email+ instance.save(update_fields=["pending_email"])+ # The code is bound to the captured address, so a concurrent email change cannot+ # redirect this code: once a different address is staged, the code stops verifying.+ email_verification_code_verifier.send_code(instance, target_email=new_email)if validated_data.get("notification_settings"):validated_data["partial_notification_settings"] = validated_data.pop("notification_settings")@@ -1255,55 +1225,44 @@ class UserViewSet(def verify_email(self, request, **kwargs):body = VerifyEmailRequestSerializer(data=request.data if isinstance(request.data, dict) else {})body.is_valid(raise_exception=True)- token = body.validated_data.get("token") or None- code = body.validated_data.get("code") or None+ code = body.validated_data["code"]user_uuid = body.validated_data["uuid"]- # Special handling for E2E tests- if settings.E2E_TESTING and user_uuid == "e2e_test_user" and token == "e2e_test_token":- return {"success": True, "token": token}-try:user: Optional[User] = User.objects.filter(is_active=True).get(uuid=user_uuid)except User.DoesNotExist:user = None- # A replay of a spent token or code (double click, scanner prefetch) is not a failure:- # the address is verified. Do not create a session - no valid credential was presented.+ # A replay of a spent code (double submit) is not a failure: the address is verified.+ # Do not create a session - no valid credential was presented.if user and user.is_email_verified is True and not user.pending_email:return Response({"success": True, "requires_login": True})- if code and not token:- if not user:- raise serializers.ValidationError(- {"code": ["This code is invalid or has expired."]},- code="invalid_code",- )- attempts = email_verification_code_verifier.reserve_attempt(user)- if email_verification_code_verifier.attempts_exceeded(attempts):- # Refuse until the budget expires, but keep the code: anyone with the uuid can- # reach this endpoint, and deleting the code here would let them block the user.- raise serializers.ValidationError(- {"code": ["Too many incorrect attempts. Try again later."]},- code="too_many_attempts",- )- if not email_verification_code_verifier.check_code(user, code):- raise serializers.ValidationError(- {"code": ["This code is invalid or has expired."]},- code="invalid_code",- )- email_verification_code_verifier.invalidate(user)- elif not user or not token or not EmailVerifier.check_token(user, token):+ if not user:raise serializers.ValidationError(- {"token": ["This verification token is invalid or has expired."]},- code="invalid_token",+ {"code": ["This code is invalid or has expired."]},+ code="invalid_code",)+ attempts = email_verification_code_verifier.reserve_attempt(user)+ if email_verification_code_verifier.attempts_exceeded(attempts):+ # Refuse until the budget expires, but keep the code: anyone with the uuid can+ # reach this endpoint, and deleting the code here would let them block the user.+ raise serializers.ValidationError(+ {"code": ["Too many incorrect attempts. Try again later."]},+ code="too_many_attempts",+ )+ if not email_verification_code_verifier.check_code(user, code):+ raise serializers.ValidationError(+ {"code": ["This code is invalid or has expired."]},+ code="invalid_code",+ )+ email_verification_code_verifier.invalidate(user)- # The swap needs a credential issued for the staged address. A token always is (its hash- # includes pending_email). A code is only for a verified user; an unverified user's code- # proves the account address, so their staged change stays pending. A legacy account- # (is_email_verified None) counts as verified, like in the login flow and in the verifier.- if user.pending_email and (token or user.is_email_verified is not False):+ # An unverified user's code proves the account address, not the staged one, so their+ # staged change stays pending until they verify it with a code sent to the new address.+ # A legacy account (is_email_verified None) counts as verified, like in the login flow+ # and in the verifier.+ if user.pending_email and user.is_email_verified is not False:old_email = user.emailwith transaction.atomic():user.email = user.pending_email@@ -1321,21 +1280,21 @@ class UserViewSet(user_has_passkeys = has_passkeys(user)passkeys_enabled_for_2fa = user_has_passkeys and user.passkeys_enabled_for_2faif default_device(user) or passkeys_enabled_for_2fa:- return Response({"success": True, "token": token, "requires_2fa": True})+ return Response({"success": True, "requires_2fa": True})# Don't hand a non-SSO session to an account whose domain enforces SSO — verifying an email# must not become a password-backend login path around the IdP. The user logs in via SSO.if OrganizationDomain.objects.get_sso_enforcement_for_email_address(user.email):- return Response({"success": True, "token": token, "requires_sso": True})+ return Response({"success": True, "requires_sso": True})# Domain enforcement: refuse blocked members — blocked admins still get a gated session.if not resolve_login_organization(user):- return Response({"success": True, "token": token, "requires_login": True})+ return Response({"success": True, "requires_login": True})login(self.request, user, backend="django.contrib.auth.backends.ModelBackend")set_two_factor_verified_in_session(self.request)report_user_logged_in(user)- return Response({"success": True, "token": token})+ return Response({"success": True})@action(methods=["POST"],@@ -1362,7 +1321,7 @@ class UserViewSet("Email is already verified.",code="already_verified",)- EmailVerifier.create_token_and_send_email_verification(user)+ email_verification_code_verifier.send_code(user)return Response({"success": True})diff --git a/posthog/api/webauthn.py b/posthog/api/webauthn.pyindex b3c7df9d5702..d054aa0087f1 100644--- a/posthog/api/webauthn.py+++ b/posthog/api/webauthn.py@@ -365,7 +365,7 @@ class WebAuthnLoginViewSet(viewsets.ViewSet):return Response({"error": (- "Your account is awaiting verification. Please check your email for a verification link."+ "Your account is awaiting verification. Log in with your password to enter the code we emailed you.")},status=status.HTTP_400_BAD_REQUEST,diff --git a/posthog/conftest.py b/posthog/conftest.pyindex ad72e8eddcf9..68fdc3fb0799 100644--- a/posthog/conftest.py+++ b/posthog/conftest.py@@ -507,22 +507,6 @@ def mock_code_based_verifier(request, mocker):)[email protected](autouse=True)-def mock_email_code_verification(request, mocker):- """- Keep the pre-existing email-verification tests on the link flow. Codes are the default and- would bypass every mock of the link-email sender. Code-flow tests opt out with- @pytest.mark.disable_mock_email_code_verification.- """- if "disable_mock_email_code_verification" in request.keywords:- return-- mocker.patch(- "posthog.api.email_verification.EmailVerifier.use_verification_code",- return_value=False,- )--class _JUnitTimingsPlugin:"""Capture wall-clock offsets and surface them as JUnit `<testsuite>` properties.diff --git a/posthog/email.py b/posthog/email.pyindex 1e394c0e885e..d7b7e37a8d43 100644--- a/posthog/email.py+++ b/posthog/email.py@@ -122,7 +122,6 @@ CUSTOMER_IO_TEMPLATE_ID_MAP = {"password_reset": "32","invite": "33","member_join": "34",- "email_verification": "35","email_change_old_address": "36","email_change_new_address": "37","password_changed": "42",diff --git a/posthog/helpers/two_factor_session.py b/posthog/helpers/two_factor_session.pyindex f0bcdfee5122..a96df41957d8 100644--- a/posthog/helpers/two_factor_session.py+++ b/posthog/helpers/two_factor_session.py@@ -44,8 +44,8 @@ def remove_code_based_verification_bypass(email: str) -> None:# Global kill-switch: when this Redis key is present, code-based verification is skipped for every-# user (e.g. while transactional email delivery is down and the verification link can't be-# delivered). The key carries the reason/actor/timestamp and a mandatory TTL so it auto-re-enables.+# user (e.g. while transactional email delivery is down and the login code can't be delivered).+# The key carries the reason/actor/timestamp and a mandatory TTL so it auto-re-enables.# Only the email factor is affected — TOTP and passkey 2FA are gated earlier in the login flow.CODE_BASED_VERIFICATION_GLOBAL_DISABLE_REDIS_KEY = "code_based_verification_global_disable"MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 daysdiff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 8ec760231907..3d222a1a27ce 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -2,7 +2,6 @@ import uuidimport datetimefrom enum import Enumfrom typing import Any, Literal, Optional, cast-from urllib.parse import quotefrom django.conf import settingsfrom django.db import transaction@@ -569,36 +568,6 @@ def send_password_changed_email(user_id: int) -> None:message.send()-@shared_task(**EMAIL_TASK_KWARGS)-@skip_team_scope_audit-def send_email_verification(- user_id: int, token: str, next_url: str | None = None, target_email: str | None = None-) -> None:- user: User = User.objects.get(pk=user_id)- next_query = f"?next={quote(next_url, safe='')}" if next_url else ""- message = EmailMessage(- use_http=True,- campaign_key=f"email-verification-{user.uuid}-{timezone.now().timestamp()}",- subject=f"Verify your email address",- template_name="email_verification",- template_context={- "preheader": "Please follow the link inside to verify your account.",- "link": f"/verify_email/{user.uuid}/{token}{next_query}",- "site_url": settings.SITE_URL,- "url": f"{settings.SITE_URL}/verify_email/{user.uuid}/{token}{next_query}",- },- )- # Pin the recipient to the email the token authorizes (the caller-captured `target_email`)- # rather than re-reading `pending_email`, which a concurrent email change could have drifted.- message.add_user_recipient(user, email_override=target_email if target_email is not None else user.pending_email)- message.send(send_async=False)- posthoganalytics.capture(- distinct_id=str(user.distinct_id),- event="verification email sent",- groups={"organization": str(user.current_organization.id)} if user.current_organization else None,- )--@shared_task(**EMAIL_TASK_KWARGS)@skip_team_scope_auditdef send_email_verification_code(user_id: int, code: str, target_email: str | None = None) -> None:diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex 69c7c7a63556..8f6136f67ec4 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -38,7 +38,6 @@'posthog.tasks.email.send_email_sending_reputation_finding','posthog.tasks.email.send_email_sending_suspended','posthog.tasks.email.send_email_sending_unsuspended',- 'posthog.tasks.email.send_email_verification','posthog.tasks.email.send_email_verification_code','posthog.tasks.email.send_error_tracking_issue_assigned','posthog.tasks.email.send_error_tracking_weekly_digest',diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.pyindex 512f4caeb156..0f5c5a722dd6 100644--- a/posthog/tasks/test/test_email.py+++ b/posthog/tasks/test/test_email.py@@ -12,7 +12,6 @@ from django.utils import timezonefrom parameterized import parameterizedfrom posthog.api.authentication import password_reset_token_generator-from posthog.api.email_verification import email_verification_token_generatorfrom posthog.models import Comment, Organization, Team, Userfrom posthog.models.app_metrics2.sql import TRUNCATE_APP_METRICS2_TABLE_SQLfrom posthog.models.instance_setting import set_instance_setting@@ -29,7 +28,6 @@ from posthog.tasks.email import (send_canary_email,send_discussions_mentioned,send_email_change_emails,- send_email_verification,send_email_verification_code,send_external_data_failure_digest,send_fatal_plugin_error,@@ -522,22 +520,6 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):task.refresh_from_db()assert task.pr_ready_email_sent_at is not None- @patch("posthoganalytics.capture")- def test_send_email_verification(self, mock_capture: MagicMock, MockEmailMessage: MagicMock) -> None:- mocked_email_messages = mock_email_messages(MockEmailMessage)- org, user = create_org_team_and_user("2022-01-02 00:00:00", "[email protected]")- token = email_verification_token_generator.make_token(self.user)- send_email_verification(user.id, token)-- mock_capture.assert_called_once_with(- event="verification email sent",- distinct_id=user.distinct_id,- groups={"organization": str(user.current_organization_id)},- )- assert len(mocked_email_messages) == 1- assert mocked_email_messages[0].send.call_count == 1- assert mocked_email_messages[0].html_body-@patch("posthog.tasks.email.ph_scoped_capture")def test_send_email_verification_code(self, mock_scoped_capture: MagicMock, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)diff --git a/posthog/tasks/test/test_email_verification.py b/posthog/tasks/test/test_email_verification.pydeleted file mode 100644index 0429bcd9b5fd..000000000000--- a/posthog/tasks/test/test_email_verification.py+++ /dev/null@@ -1,41 +0,0 @@-from types import SimpleNamespace--from unittest.mock import patch--from django.test import SimpleTestCase--from parameterized import parameterized--from posthog.tasks.email import send_email_verification---class TestEmailVerificationRecipient(SimpleTestCase):- @parameterized.expand(- [- # (db_pending_email, target_email, expected_recipient)- # A concurrent email change may have drifted pending_email to an attacker-controlled- # address; the verification must still go only to the address the token authorizes.- ("pinned_target_wins_over_drifted_pending_email", "[email protected]", "[email protected]", "[email protected]"),- # Callers that don't pin a target (signup, auth, admin) keep the existing behavior.- ("defaults_to_pending_email_without_target", "[email protected]", None, "[email protected]"),- ]- )- def test_verification_recipient(- self, _name: str, db_pending_email: str, target_email: str | None, expected: str- ) -> None:- user = SimpleNamespace(- pk=1,- uuid="u",- pending_email=db_pending_email,- email="[email protected]",- distinct_id="d",- current_organization=SimpleNamespace(id="org"),- )- with (- patch("posthog.tasks.email.User.objects.get", return_value=user),- patch("posthog.tasks.email.posthoganalytics.capture"),- patch("posthog.tasks.email.EmailMessage") as MockEmailMessage,- ):- send_email_verification(user.pk, "token", target_email=target_email)-- MockEmailMessage.return_value.add_user_recipient.assert_called_once_with(user, email_override=expected)diff --git a/posthog/templates/email/email_verification.html b/posthog/templates/email/email_verification.htmldeleted file mode 100644index 127a843f2fdc..000000000000--- a/posthog/templates/email/email_verification.html+++ /dev/null@@ -1,14 +0,0 @@-{% extends "email/base.html" %}-{% block section %}- <p>Welcome to PostHog! Click on the following link to verify your email address.</p>- <div class="mb mt text-center">- <a class="button" href="{% absolute_uri link %}">Verify email address</a>- </div>- <div class="mt muted">- <p>- If the button above doesn't work, paste this link into your browser:- <br />- <a href="{% absolute_uri link %}">{% absolute_uri link %}</a>- </p>- </div>-{% endblock %} {% block preheader %}{{ preheader }}{% endblock %}{% block heading %}Verify your email address.{% endblock %}diff --git a/pytest.ini b/pytest.iniindex cdf38029de49..5edbf10828c8 100644--- a/pytest.ini+++ b/pytest.ini@@ -32,7 +32,6 @@ markers =requires_secrets: test needs internal secrets or infra and is skipped on external PRsquarantine: applied automatically to tests quarantined via .test_quarantine.json (hogli test:quarantine)persons_db_direct: test exercises the persons DB directly and must not have the personhog fake / ORM block active- disable_mock_email_code_verification: let email verification (signup and email change) send the real 6-digit code flow instead of the mocked-off link flowasyncio_mode = autoasyncio_default_fixture_loop_scope = modulediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ac87220bd52d..366ff22ca841 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -86131,15 +86131,13 @@ export namespace Schemas {}/**- * Request body for POST /api/users/verify_email/. Exactly one of token or code is required.+ * Request body for POST /api/users/verify_email/.*/export interface VerifyEmailRequest {/** UUID of the user whose email is being verified. */uuid: string;- /** Verification token from the emailed link. Required unless a code is provided. */- token?: string;- /** The 6-digit verification code emailed at signup. Whitespace, invisible characters, and grouping hyphens are removed and compatibility digits are folded to ASCII before checking. */- code?: string;+ /** The 6-digit verification code from the email. Whitespace, invisible characters, and grouping hyphens are removed and compatibility digits are folded to ASCII before checking. */+ code: string;}/**