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): ask for the email first on login and signup (#122817)

Rafael Audibertf743900616b1
diff --git a/docs/published/handbook/engineering/oauth-development-guide.md b/docs/published/handbook/engineering/oauth-development-guide.md
index 422cb6a1736c..1bdeb5dd45f4 100644
--- a/docs/published/handbook/engineering/oauth-development-guide.md
+++ b/docs/published/handbook/engineering/oauth-development-guide.md
@@ -354,9 +354,9 @@ The redirect also sets the `ph_pending_oauth_connection` cookie so those screens
An account created while the cookie is present skips in-app onboarding. Signup sets `onboarding_skipped_reason` to `connector`, pinned to the signup organization, so another organization the person joins later still shows onboarding. A delegated invitee keeps onboarding, because running it is the reason for the invite. Until the project ingests its first event, opening the project homepage sends that person to `/welcome`. Other pages open as linked, so a deep link from the connecting application still works.
-While the cookie is present, the signup form pins the data region to the region the form is served from. An OAuth client is registered in one region only, so an account created in the other region could not finish the connection.
+While the cookie is present, the auth page pins the data region to the region the form is served from. An OAuth client is registered in one region only, so an account created in the other region could not finish the connection.
-Analytics: the frontend captures `oauth pending connection viewed` with a `screen` property (`login`, `signup`, or `verify_email`). `user signed up` carries `signup_oauth_client_name` and `signup_oauth_client_id`, which are also set as person properties, so a signup can be traced back to the application that started it. When the signup creates a new organization, the project group also gets `created_via_oauth_client` and `created_via_oauth_client_id`.
+Analytics: `/login` and `/signup` render the same page, which asks for the email first and then shows the login or the signup steps. The frontend captures `auth step viewed` for every step, with `step` (`email`, `login`, `login_code`, `signup_credentials`, `signup_profile`, `signup_pending_invite`, or `verify_email`), `entry` (`login` or `signup`), and `oauth_client_name` and `oauth_client_id` while the cookie is present. `auth email submitted` records the routing decision with `routed_to` and `account_exists`. `user signed up` carries `signup_oauth_client_name` and `signup_oauth_client_id`, which are also set as person properties, so a signup can be traced back to the application that started it. When the signup creates a new organization, the project group also gets `created_via_oauth_client` and `created_via_oauth_client_id`.
## Endpoints
diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.py
index c01af71f6df9..5b3fa526c740 100644
--- a/ee/api/test/test_authentication.py
+++ b/ee/api/test/test_authentication.py
@@ -458,6 +458,7 @@ class TestEELoginPrecheckAPI(APILicensedTest):
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
+ "account_exists": True,
"password_login_available": True,
"social_providers": [],
},
@@ -483,6 +484,7 @@ class TestEELoginPrecheckAPI(APILicensedTest):
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
+ "account_exists": False,
"password_login_available": True,
"social_providers": [],
},
@@ -507,6 +509,7 @@ class TestEELoginPrecheckAPI(APILicensedTest):
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
+ "account_exists": True,
"password_login_available": True,
"social_providers": [],
},
@@ -532,6 +535,7 @@ class TestEELoginPrecheckAPI(APILicensedTest):
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
+ "account_exists": True,
"password_login_available": True,
"social_providers": [],
},
@@ -1261,6 +1265,7 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
"saml_available": True,
"oidc_available": False,
"webauthn_credentials": [],
+ "account_exists": False,
"password_login_available": True,
"social_providers": [],
},
@@ -1831,6 +1836,7 @@ YotAcSbU3p5bzd11wpyebYHB"""
"saml_available": True,
"oidc_available": False,
"webauthn_credentials": [],
+ "account_exists": True,
"password_login_available": True,
"social_providers": [],
},
@@ -1849,6 +1855,7 @@ YotAcSbU3p5bzd11wpyebYHB"""
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
+ "account_exists": True,
"password_login_available": True,
"social_providers": [],
},
@@ -1872,6 +1879,7 @@ YotAcSbU3p5bzd11wpyebYHB"""
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
+ "account_exists": True,
"password_login_available": True,
"social_providers": [],
},
diff --git a/frontend/src/scenes/authentication/login/Login.scss b/frontend/src/exporter/ExporterLogin.scss
similarity index 100%
rename from frontend/src/scenes/authentication/login/Login.scss
rename to frontend/src/exporter/ExporterLogin.scss
diff --git a/frontend/src/exporter/ExporterLogin.tsx b/frontend/src/exporter/ExporterLogin.tsx
index a5d588c3374e..ca4409394be7 100644
--- a/frontend/src/exporter/ExporterLogin.tsx
+++ b/frontend/src/exporter/ExporterLogin.tsx
@@ -1,4 +1,4 @@
-import '../scenes/authentication/login/Login.scss'
+import './ExporterLogin.scss'
import clsx from 'clsx'
import { MakeLogicType, actions, kea, path, reducers, useValues } from 'kea'
diff --git a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts
index 2ac57c9b91f3..304f9d3920f1 100644
--- a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts
+++ b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts
@@ -17,7 +17,7 @@ import api, { ApiError } from 'lib/api'
import { Dayjs, dayjs } from 'lib/dayjs'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { uuid } from 'lib/utils/dom'
-import { PrecheckResponseType } from 'scenes/authentication/login/loginLogic'
+import { PrecheckResponseType } from 'scenes/authentication/auth/loginLogic'
import { ERROR_MESSAGES } from 'scenes/authentication/shared/loginErrorMessages'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/appScenes.ts b/frontend/src/scenes/appScenes.ts
index 00726f7d3619..f95d4d21442f 100644
--- a/frontend/src/scenes/appScenes.ts
+++ b/frontend/src/scenes/appScenes.ts
@@ -59,7 +59,7 @@ export const appScenes: Record<Scene | string, () => any> = {
[Scene.Coupons]: () => import('./coupons/Coupons'),
[Scene.LiveEvents]: () => import('./activity/live/LiveEventsTable'),
[Scene.Login2FA]: () => import('./authentication/login-2fa/Login2FA'),
- [Scene.Login]: () => import('./authentication/login/Login'),
+ [Scene.Login]: () => import('./authentication/auth/Auth'),
[Scene.MarketingAnalytics]: () => import('./marketing-analytics/MarketingAnalyticsScene'),
[Scene.Max]: () => import('./max/Max'),
[Scene.MoveToPostHogCloud]: () => import('./moveToPostHogCloud/MoveToPostHogCloud'),
@@ -113,7 +113,7 @@ export const appScenes: Record<Scene | string, () => any> = {
[Scene.Settings]: () => import('./settings/SettingsScene'),
[Scene.IdentityProviderConfig]: () =>
import('./settings/organization/IdentityProviderConfig/IdentityProviderConfigScene'),
- [Scene.Signup]: () => import('./authentication/signup/Signup'),
+ [Scene.Signup]: () => import('./authentication/auth/Auth'),
[Scene.Site]: () => import('./sites/Site'),
[Scene.StartupProgram]: () => import('./startups/StartupProgram'),
[Scene.Survey]: () => import('./surveys/Survey'),
diff --git a/frontend/src/scenes/authentication/auth/Auth.stories.tsx b/frontend/src/scenes/authentication/auth/Auth.stories.tsx
new file mode 100644
index 000000000000..2136eb0c0d87
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/Auth.stories.tsx
@@ -0,0 +1,334 @@
+import { WEBSITE_REFERRER, setDocumentReferrer } from 'scenes/authentication/shared/authReferrer.mock'
+import { setLastLoginMethodCookie } from 'scenes/authentication/shared/lastLoginMethod.mock'
+import {
+ PENDING_OAUTH_CONNECTION_FIXTURE,
+ setPendingOAuthConnectionCookie,
+} from 'scenes/authentication/shared/pendingOAuthConnection.mock'
+
+import type { Meta, StoryFn } from '@storybook/react'
+import { useValues } from 'kea'
+import { router } from 'kea-router'
+import { useEffect } from 'react'
+
+import { useDelayedOnMountEffect } from 'lib/hooks/useOnMountEffect'
+import { userLogic } from 'scenes/userLogic'
+
+import { useStorybookMocks } from '~/mocks/browser'
+import preflightJson from '~/mocks/fixtures/_preflight.json'
+
+import { arrivedFromWebsiteLogic } from '../shared/arrivedFromWebsiteLogic'
+import { Auth } from './Auth'
+import { authLogic } from './authLogic'
+import { loginLogic } from './loginLogic'
+import { signupLogic } from './signupLogic'
+
+const STEP_OPTIONS = [
+ 'Email',
+ 'Login',
+ 'Login code',
+ 'New person on an SSO domain',
+ 'Signup credentials',
+ 'Signup profile',
+ 'Pending invite',
+] as const
+type StepOption = (typeof STEP_OPTIONS)[number]
+const NEW_ACCOUNT_STEPS: StepOption[] = [
+ 'New person on an SSO domain',
+ 'Signup credentials',
+ 'Signup profile',
+ 'Pending invite',
+]
+
+type StoryArgs = {
+ entry: 'login' | 'signup'
+ step: StepOption
+ cloud: boolean
+ region: 'US' | 'EU'
+ googleOAuth: boolean
+ github: boolean
+ gitlab: boolean
+ samlAvailable: boolean
+ ssoEnforcement: 'none' | 'google-oauth2' | 'github' | 'gitlab' | 'saml'
+ generalError: 'none' | 'invalid_credentials' | 'no_new_organizations'
+ pendingOAuthConnection: boolean
+ arrivedFromWebsite: boolean
+ hasLoggedInBefore: boolean
+ signedOutForSessionRisk: boolean
+ noSignInMethod: boolean
+ precheckFails: boolean
+ emailTaken: boolean
+ canCreateOrg: boolean
+}
+
+const EMAIL = '[email protected]'
+
+const meta: Meta<StoryArgs> = {
+ title: 'Scenes-Other/Auth',
+ tags: ['test-skip'],
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ },
+ argTypes: {
+ entry: { control: 'select', options: ['login', 'signup'], name: 'Entry URL' },
+ step: {
+ control: 'select',
+ name: 'Step',
+ options: [...STEP_OPTIONS],
+ },
+ cloud: { control: 'boolean', name: 'Cloud' },
+ region: { control: 'select', options: ['US', 'EU'], name: 'Region', if: { arg: 'cloud' } },
+ googleOAuth: { control: 'boolean', name: 'Google OAuth' },
+ github: { control: 'boolean', name: 'GitHub' },
+ gitlab: { control: 'boolean', name: 'GitLab' },
+ samlAvailable: { control: 'boolean', name: 'SAML available' },
+ ssoEnforcement: {
+ control: 'select',
+ name: 'SSO enforcement',
+ options: ['none', 'google-oauth2', 'github', 'gitlab', 'saml'],
+ },
+ generalError: {
+ control: 'select',
+ name: 'General error',
+ options: ['none', 'invalid_credentials', 'no_new_organizations'],
+ },
+ pendingOAuthConnection: { control: 'boolean', name: 'Pending OAuth connection' },
+ arrivedFromWebsite: { control: 'boolean', name: 'Arrived from posthog.com' },
+ hasLoggedInBefore: { control: 'boolean', name: 'Has logged in before' },
+ signedOutForSessionRisk: { control: 'boolean', name: 'Signed out for session risk' },
+ noSignInMethod: { control: 'boolean', name: 'Account has no sign-in method' },
+ precheckFails: { control: 'boolean', name: 'Login precheck fails' },
+ emailTaken: { control: 'boolean', name: 'Signup finds the email taken' },
+ canCreateOrg: { control: 'boolean', name: 'Signups allowed' },
+ },
+ args: {
+ entry: 'login',
+ step: 'Email',
+ cloud: true,
+ region: 'US',
+ googleOAuth: true,
+ github: true,
+ gitlab: true,
+ samlAvailable: false,
+ ssoEnforcement: 'none',
+ generalError: 'none',
+ pendingOAuthConnection: false,
+ arrivedFromWebsite: false,
+ hasLoggedInBefore: true,
+ signedOutForSessionRisk: false,
+ noSignInMethod: false,
+ precheckFails: false,
+ emailTaken: false,
+ canCreateOrg: true,
+ },
+}
+export default meta
+
+const ERROR_DETAILS: Record<string, string> = {
+ invalid_credentials: 'Invalid email or password.',
+}
+
+const Template: StoryFn<StoryArgs> = ({
+ entry,
+ step,
+ cloud,
+ region,
+ googleOAuth,
+ github,
+ gitlab,
+ samlAvailable,
+ ssoEnforcement,
+ generalError,
+ pendingOAuthConnection,
+ arrivedFromWebsite,
+ hasLoggedInBefore,
+ signedOutForSessionRisk,
+ noSignInMethod,
+ precheckFails,
+ emailTaken,
+ canCreateOrg,
+}) => {
+ const enforcement = ssoEnforcement === 'none' ? null : ssoEnforcement
+ // Set synchronously: the scene reads the cookies while it mounts during this same render.
+ setPendingOAuthConnectionCookie(pendingOAuthConnection ? PENDING_OAUTH_CONNECTION_FIXTURE : null)
+ setDocumentReferrer(arrivedFromWebsite ? WEBSITE_REFERRER : '')
+ setLastLoginMethodCookie(hasLoggedInBefore ? 'password' : null)
+
+ useStorybookMocks({
+ get: {
+ '/_preflight': {
+ ...preflightJson,
+ cloud,
+ region: cloud ? region : undefined,
+ realm: cloud ? 'cloud' : 'hosted-clickhouse',
+ is_debug: cloud,
+ can_create_org: canCreateOrg,
+ available_social_auth_providers: {
+ 'google-oauth2': googleOAuth,
+ github,
+ gitlab,
+ saml: samlAvailable,
+ },
+ },
+ '/api/users/@me': () => [500, null],
+ },
+ post: {
+ '/api/login/precheck': () =>
+ precheckFails
+ ? [429, { type: 'throttled_error', code: 'throttled', detail: 'Request was throttled.' }]
+ : [
+ 200,
+ {
+ account_exists: !NEW_ACCOUNT_STEPS.includes(step),
+ sso_enforcement: enforcement,
+ saml_available: samlAvailable || step === 'New person on an SSO domain',
+ password_login_available: !noSignInMethod,
+ },
+ ],
+ '/api/signup/precheck': () =>
+ emailTaken
+ ? [
+ 409,
+ {
+ email_exists: true,
+ code: 'account_exists',
+ detail: 'There is already an account with this email address.',
+ },
+ ]
+ : [
+ 200,
+ {
+ email_exists: false,
+ pending_invite: step === 'Pending invite' ? { organization_name: 'Hogflix' } : null,
+ },
+ ],
+ },
+ })
+
+ useDelayedOnMountEffect(() => userLogic.actions.loadUserSuccess(null))
+
+ useEffect(() => {
+ router.actions.push(
+ entry === 'signup' ? '/signup' : '/login',
+ signedOutForSessionRisk ? { reason: 'session_risk' } : {}
+ )
+ }, [entry, signedOutForSessionRisk])
+
+ useEffect(() => {
+ arrivedFromWebsiteLogic.findMounted()?.actions.setArrivedFromWebsite(arrivedFromWebsite)
+ }, [arrivedFromWebsite])
+
+ useEffect(() => {
+ authLogic.actions.backToEmail()
+ if (step === 'Email') {
+ return
+ }
+ loginLogic.actions.setLoginValue('email', EMAIL)
+ authLogic.actions.continueWithEmail()
+ }, [step, enforcement, precheckFails, emailTaken, canCreateOrg])
+
+ useEffect(() => {
+ if (step === 'Login code') {
+ loginLogic.actions.setCodeVerificationRequired(EMAIL)
+ }
+ }, [step])
+
+ // The signup precheck answers asynchronously and opens panel 1, so move on only once it has
+ const { panel } = useValues(signupLogic)
+ useEffect(() => {
+ if (step === 'Signup profile' && panel === 1) {
+ signupLogic.actions.setPanel(2)
+ }
+ }, [step, panel])
+
+ useEffect(() => {
+ if (generalError !== 'none') {
+ loginLogic.actions.setGeneralError(generalError, ERROR_DETAILS[generalError] ?? '')
+ } else {
+ loginLogic.actions.clearGeneralError()
+ }
+ }, [generalError])
+
+ return <Auth key={String(hasLoggedInBefore)} />
+}
+
+export const Default: StoryFn<StoryArgs> = Template.bind({})
+
+export const FirstLoginOnThisBrowser: StoryFn<StoryArgs> = Template.bind({})
+FirstLoginOnThisBrowser.storyName = 'First login on this browser'
+FirstLoginOnThisBrowser.args = { hasLoggedInBefore: false }
+
+export const SignupEntry: StoryFn<StoryArgs> = Template.bind({})
+SignupEntry.storyName = 'Signup entry'
+SignupEntry.args = { entry: 'signup' }
+
+export const SelfHosted: StoryFn<StoryArgs> = Template.bind({})
+SelfHosted.args = { cloud: false, googleOAuth: false, github: false, gitlab: false, samlAvailable: false }
+
+export const SocialSignInError: StoryFn<StoryArgs> = Template.bind({})
+SocialSignInError.storyName = 'Social sign-in error'
+SocialSignInError.args = { generalError: 'no_new_organizations' }
+
+export const PendingOAuthConnection: StoryFn<StoryArgs> = Template.bind({})
+PendingOAuthConnection.storyName = 'Pending OAuth connection'
+PendingOAuthConnection.args = { pendingOAuthConnection: true }
+
+export const LoginStep: StoryFn<StoryArgs> = Template.bind({})
+LoginStep.args = { step: 'Login' }
+
+export const LoginStepFromSignupEntry: StoryFn<StoryArgs> = Template.bind({})
+LoginStepFromSignupEntry.storyName = 'Login step from the signup entry'
+LoginStepFromSignupEntry.args = { step: 'Login', entry: 'signup' }
+
+export const LoginError: StoryFn<StoryArgs> = Template.bind({})
+LoginError.args = { step: 'Login', generalError: 'invalid_credentials' }
+
+export const SSOEnforced: StoryFn<StoryArgs> = Template.bind({})
+SSOEnforced.args = { step: 'Login', ssoEnforcement: 'google-oauth2' }
+
+export const SAMLAvailable: StoryFn<StoryArgs> = Template.bind({})
+SAMLAvailable.args = { step: 'Login', samlAvailable: true }
+
+export const LoginCode: StoryFn<StoryArgs> = Template.bind({})
+LoginCode.args = { step: 'Login code' }
+
+export const SignupCredentials: StoryFn<StoryArgs> = Template.bind({})
+SignupCredentials.args = { step: 'Signup credentials' }
+
+export const SignupCredentialsEU: StoryFn<StoryArgs> = Template.bind({})
+SignupCredentialsEU.storyName = 'Signup credentials (EU)'
+SignupCredentialsEU.args = { step: 'Signup credentials', region: 'EU' }
+
+export const SignupCredentialsPendingOAuthConnection: StoryFn<StoryArgs> = Template.bind({})
+SignupCredentialsPendingOAuthConnection.storyName = 'Signup credentials with a pending OAuth connection'
+SignupCredentialsPendingOAuthConnection.args = { step: 'Signup credentials', pendingOAuthConnection: true }
+
+export const SignupProfile: StoryFn<StoryArgs> = Template.bind({})
+SignupProfile.args = { step: 'Signup profile' }
+
+export const PendingInvite: StoryFn<StoryArgs> = Template.bind({})
+PendingInvite.args = { step: 'Pending invite' }
+
+export const NewPersonOnSSODomain: StoryFn<StoryArgs> = Template.bind({})
+NewPersonOnSSODomain.storyName = 'New person on an SSO domain'
+NewPersonOnSSODomain.args = { step: 'New person on an SSO domain' }
+
+export const SignedOutForSessionRisk: StoryFn<StoryArgs> = Template.bind({})
+SignedOutForSessionRisk.storyName = 'Signed out for session risk'
+SignedOutForSessionRisk.args = { signedOutForSessionRisk: true }
+
+export const NoSignInMethod: StoryFn<StoryArgs> = Template.bind({})
+NoSignInMethod.storyName = 'Account with no sign-in method'
+NoSignInMethod.args = { step: 'Login', noSignInMethod: true, googleOAuth: false, github: false, gitlab: false }
+
+export const PrecheckFailed: StoryFn<StoryArgs> = Template.bind({})
+PrecheckFailed.storyName = 'Login step when the precheck fails'
+PrecheckFailed.args = { step: 'Login', precheckFails: true }
+
+export const EmailTakenOnSignup: StoryFn<StoryArgs> = Template.bind({})
+EmailTakenOnSignup.storyName = 'Signup finds the email taken'
+EmailTakenOnSignup.args = { step: 'Signup credentials', emailTaken: true }
+
+export const NewPersonWithSignupsOff: StoryFn<StoryArgs> = Template.bind({})
+NewPersonWithSignupsOff.storyName = 'New person where signups are off'
+NewPersonWithSignupsOff.args = { step: 'Signup credentials', canCreateOrg: false, cloud: false }
diff --git a/frontend/src/scenes/authentication/signup/Signup.test.tsx b/frontend/src/scenes/authentication/auth/Auth.test.tsx
similarity index 78%
rename from frontend/src/scenes/authentication/signup/Signup.test.tsx
rename to frontend/src/scenes/authentication/auth/Auth.test.tsx
index 9dd2c8c9eb2b..f2590f74f9dd 100644
--- a/frontend/src/scenes/authentication/signup/Signup.test.tsx
+++ b/frontend/src/scenes/authentication/auth/Auth.test.tsx
@@ -5,22 +5,28 @@ import userEvent from '@testing-library/user-event'
import { Provider } from 'kea'
import { router } from 'kea-router'
+import preflightJson from '~/mocks/fixtures/_preflight.json'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { Signup } from './Signup'
+import { Auth } from './Auth'
-describe('Signup', () => {
+describe('Auth', () => {
let signupRequestBody: Record<string, any> | null
+ let accountExists: boolean
beforeEach(() => {
signupRequestBody = null
+ accountExists = false
useMocks({
get: {
+ // An instance that cannot create organizations sends unknown emails to the login step
+ '/_preflight': () => [200, { ...preflightJson, can_create_org: true }],
// The form only renders for a logged-out user
'/api/users/@me/': () => [401, { detail: 'Not authenticated' }],
},
post: {
+ '/api/login/precheck': () => [200, { account_exists: accountExists, saml_available: false }],
'/api/signup/precheck': () => [200, { email_exists: false, pending_invite: null }],
// 400 rather than 201 so the submit handler never assigns `location.href`,
// which jsdom does not implement. The request body is captured before the response.
@@ -37,7 +43,7 @@ describe('Signup', () => {
router.actions.push('/signup')
render(
<Provider>
- <Signup />
+ <Auth />
</Provider>
)
})
@@ -74,13 +80,21 @@ describe('Signup', () => {
await userEvent.click(screen.getByTestId('signup-submit'))
}
- it('submitting without an email shows the error and stays on the email panel', async () => {
+ it('submitting without an email shows the error and stays on the email step', async () => {
await submitEmail('')
expect(await screen.findByText('Please enter your email to continue')).toBeVisible()
expect(screen.getByTestId('signup-email')).toBeInTheDocument()
})
+ it('sends an email that already has an account to the password step instead of signup', async () => {
+ accountExists = true
+ await submitEmail('[email protected]')
+
+ expect(await screen.findByTestId('password-login')).toBeInTheDocument()
+ expect(screen.queryByTestId('signup-auth-continue')).not.toBeInTheDocument()
+ })
+
it('a too-short password blocks the auth panel; a valid one advances to onboarding', async () => {
await submitEmail('[email protected]')
@@ -93,17 +107,17 @@ describe('Signup', () => {
expect(await screen.findByTestId('signup-name')).toBeInTheDocument()
})
- // The panels are the only place the three forms get wired to the logic, so this walkthrough
+ // The steps are the only place the signup forms get wired to the logics, so this walkthrough
// guards that wiring. The payload shaping itself is covered in signupLogic.test.ts.
- it('walks all three panels and posts what was typed into them', async () => {
- await submitEmail('[email protected]')
+ it('walks a new email through every signup step and posts what was typed into them', async () => {
+ await submitEmail('[email protected]')
await submitPassword('Str0ng-Test-Pass!')
await fillOnboardingAndSubmit({ name: 'Alice Bob', organizationName: 'Hogflix SpinOff' })
await waitFor(() => {
expect(signupRequestBody).not.toBeNull()
})
- expect(signupRequestBody?.email).toBe('[email protected]')
+ expect(signupRequestBody?.email).toBe('[email protected]')
expect(signupRequestBody?.password).toBe('Str0ng-Test-Pass!')
expect(signupRequestBody?.first_name).toBe('Alice')
expect(signupRequestBody?.last_name).toBe('Bob')
diff --git a/frontend/src/scenes/authentication/auth/Auth.tsx b/frontend/src/scenes/authentication/auth/Auth.tsx
new file mode 100644
index 000000000000..114073309fb0
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/Auth.tsx
@@ -0,0 +1,92 @@
+import { useActions, useMountedLogic, useValues } from 'kea'
+import { useEffect } from 'react'
+
+import { AuthScene } from 'scenes/authentication/shared/authScene/AuthScene'
+import { AuthEntry } from 'scenes/authentication/shared/authStepViewed'
+import { useLastLoginMethod } from 'scenes/authentication/shared/lastLoginMethod'
+import { loginTelemetryLogic } from 'scenes/authentication/shared/loginTelemetryLogic'
+import { passkeyLogic } from 'scenes/authentication/shared/passkeyLogic'
+import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'
+import { RedirectIfLoggedInOtherInstance } from 'scenes/authentication/shared/RedirectToLoggedInInstance'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+import { SceneExport } from 'scenes/sceneTypes'
+import { userLogic } from 'scenes/userLogic'
+
+import { AuthPageStep, authLogic } from './authLogic'
+import { authTelemetryLogic } from './authTelemetryLogic'
+import { EmailStep } from './steps/EmailStep'
+import { LoginCodeStep } from './steps/LoginCodeStep'
+import { LoginStep } from './steps/LoginStep'
+import { PendingInviteStep } from './steps/PendingInviteStep'
+import { SignupCredentialsStep } from './steps/SignupCredentialsStep'
+import { SignupProfileStep } from './steps/SignupProfileStep'
+
+export const scene: SceneExport = {
+ component: Auth,
+ logic: authLogic,
+}
+
+const WELCOME_BACK_NOTES = ['// welcome back', '// 500,000+ teams ship here']
+const FIRST_VISIT_NOTES = ['// hey, good to see you', '// 500,000+ teams ship here']
+const CREATE_ACCOUNT_NOTES = ['// create an account', '// 1M events free, every month']
+
+function authNotes(step: AuthPageStep, entry: AuthEntry, isReturning: boolean): string[] {
+ switch (step) {
+ case 'login':
+ case 'login_code':
+ return WELCOME_BACK_NOTES
+ case 'signup_credentials':
+ case 'signup_pending_invite':
+ return CREATE_ACCOUNT_NOTES
+ case 'signup_profile':
+ return ['// almost there', '// last step']
+ default:
+ if (entry === 'signup') {
+ return CREATE_ACCOUNT_NOTES
+ }
+ return isReturning ? WELCOME_BACK_NOTES : FIRST_VISIT_NOTES
+ }
+}
+
+const STEP_COMPONENTS: Record<AuthPageStep, () => JSX.Element> = {
+ email: EmailStep,
+ login: LoginStep,
+ login_code: LoginCodeStep,
+ signup_credentials: SignupCredentialsStep,
+ signup_profile: SignupProfileStep,
+ signup_pending_invite: PendingInviteStep,
+}
+
+export function Auth(): JSX.Element | null {
+ // Mounted here so the login funnel is only reported from the auth scenes
+ useMountedLogic(loginTelemetryLogic)
+ useMountedLogic(authTelemetryLogic)
+ // Mounted at the scene root so the cookie is read once, not on every step change
+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)
+ const { step, entry } = useValues(authLogic)
+ const { user } = useValues(userLogic)
+ const { preflight } = useValues(preflightLogic)
+ const { startConditionalPasskeyLogin } = useActions(passkeyLogic)
+ const isReturning = useLastLoginMethod() !== null
+
+ // WebKit (Safari/iOS) can't open the passkey modal without a user gesture, so we show
+ // passkeys via the email field's autofill instead. Other browsers keep the auto-modal.
+ useEffect(() => {
+ startConditionalPasskeyLogin()
+ }, [startConditionalPasskeyLogin])
+
+ const StepComponent = STEP_COMPONENTS[step]
+
+ // A finished signup navigates away with a full page load, so nothing should render in between
+ if (user) {
+ return null
+ }
+
+ return (
+ <AuthScene notes={authNotes(step, entry, isReturning)}>
+ {/* Signup never had this redirect, and a pending OAuth connection belongs to this region */}
+ {preflight?.cloud && entry === 'login' && !pendingConnection && <RedirectIfLoggedInOtherInstance />}
+ <StepComponent />
+ </AuthScene>
+ )
+}
diff --git a/frontend/src/scenes/authentication/auth/authLogic.test.ts b/frontend/src/scenes/authentication/auth/authLogic.test.ts
new file mode 100644
index 000000000000..6698269b46fa
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/authLogic.test.ts
@@ -0,0 +1,250 @@
+import {
+ PENDING_OAUTH_CONNECTION_FIXTURE,
+ setPendingOAuthConnectionCookie,
+} from 'scenes/authentication/shared/pendingOAuthConnection.mock'
+
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import preflightJson from '~/mocks/fixtures/_preflight.json'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import type { PreflightStatus } from '~/types'
+
+import { AuthAccountPath, accountPathFor, authLogic, canSignUpWithEmail } from './authLogic'
+import { authTelemetryLogic } from './authTelemetryLogic'
+import { PrecheckResponseType } from './loginLogic'
+import { loginLogic } from './loginLogic'
+import { maintenanceSignupRedirectUrl, signupLogic } from './signupLogic'
+
+jest.mock('posthog-js')
+
+const COMPLETED: PrecheckResponseType = { status: 'completed', saml_available: false }
+const PREFLIGHT = { can_create_org: true, demo: false } as PreflightStatus
+
+describe('authLogic', () => {
+ it.each<[string, PrecheckResponseType, PreflightStatus, AuthAccountPath]>([
+ ['an existing account', { ...COMPLETED, account_exists: true }, PREFLIGHT, 'login'],
+ ['a new email', { ...COMPLETED, account_exists: false }, PREFLIGHT, 'signup'],
+ [
+ 'a failed precheck',
+ { ...COMPLETED, precheckFailed: true, password_login_available: true },
+ PREFLIGHT,
+ 'login',
+ ],
+ [
+ 'a new email on an SSO-enforced domain',
+ { ...COMPLETED, account_exists: false, sso_enforcement: 'saml' },
+ PREFLIGHT,
+ 'login',
+ ],
+ [
+ 'a new email on a domain with optional SAML',
+ { ...COMPLETED, account_exists: false, saml_available: true },
+ PREFLIGHT,
+ 'login',
+ ],
+ [
+ 'a new email where no organization can be created',
+ { ...COMPLETED, account_exists: false },
+ { ...PREFLIGHT, can_create_org: false },
+ 'login',
+ ],
+ ['an existing demo user', { ...COMPLETED, account_exists: true }, { ...PREFLIGHT, demo: true }, 'signup'],
+ ])('routes %s to the right step', (_name, precheck, preflight, expected) => {
+ expect(accountPathFor(precheck, preflight)).toEqual(expected)
+ })
+
+ it.each<[string, PrecheckResponseType, PreflightStatus, boolean]>([
+ ['an instance that creates organizations', COMPLETED, PREFLIGHT, true],
+ ['an instance that cannot create organizations', COMPLETED, { ...PREFLIGHT, can_create_org: false }, false],
+ ['an SSO-enforced domain', { ...COMPLETED, sso_enforcement: 'saml' }, PREFLIGHT, false],
+ ])('offers email signup to a new person on %s: %s', (_name, precheck, preflight, expected) => {
+ expect(canSignUpWithEmail(precheck, preflight)).toEqual(expected)
+ })
+
+ const US = { cloud: true, region: 'US' as PreflightStatus['region'] }
+ it.each<[string, Partial<PreflightStatus>, string | undefined, boolean, string | null]>([
+ [
+ 'sends a US signup to the EU with its email',
+ US,
+ 'eu',
+ false,
+ 'https://eu.posthog.com/signup?maintenanceRedirect=true&email=person%40example.com',
+ ],
+ [
+ 'keeps a signup in the region that takes them',
+ { ...US, region: 'EU' as PreflightStatus['region'] },
+ 'eu',
+ false,
+ null,
+ ],
+ ['keeps a signup when the flag is off', US, undefined, false, null],
+ ['keeps a self-hosted signup', { ...US, cloud: false }, 'eu', false, null],
+ ['keeps a signup with a pending OAuth connection', US, 'eu', true, null],
+ ])('maintenance redirect %s', (_name, preflight, flag, pendingOAuthConnection, expected) => {
+ setPendingOAuthConnectionCookie(pendingOAuthConnection ? PENDING_OAUTH_CONNECTION_FIXTURE : null)
+ const featureFlags = flag ? { 'redirect-signups-to-instance': flag } : {}
+ expect(
+ maintenanceSignupRedirectUrl({ ...PREFLIGHT, ...preflight }, featureFlags, '[email protected]')
+ ).toEqual(expected)
+ })
+
+ describe('when a request fails', () => {
+ let loginPrecheck: () => [number, Record<string, any>]
+ let signupPrecheck: () => [number, Record<string, any>]
+
+ beforeEach(() => {
+ loginPrecheck = () => [200, { account_exists: false, saml_available: false }]
+ signupPrecheck = () => [200, { email_exists: false, pending_invite: null }]
+ useMocks({
+ get: {
+ '/_preflight': () => [200, { ...preflightJson, can_create_org: true }],
+ },
+ post: {
+ '/api/login/precheck': () => loginPrecheck(),
+ '/api/signup/precheck': () => signupPrecheck(),
+ },
+ })
+ initKeaTests()
+ router.actions.push('/login')
+ authLogic.mount()
+ loginLogic.actions.setLoginValue('email', '[email protected]')
+ })
+
+ afterEach(() => {
+ authLogic.unmount()
+ })
+
+ it('lands on the login step with the account unknown, and still lets the person sign up', async () => {
+ loginPrecheck = () => [429, { type: 'throttled_error', code: 'throttled', detail: 'Slow down' }]
+
+ await expectLogic(authLogic, () => authLogic.actions.continueWithEmail())
+ .toDispatchActions(['chooseAccountPath'])
+ .toMatchValues({ step: 'login', accountExists: null })
+
+ authLogic.actions.chooseAccountPath('signup', null)
+ await expectLogic(signupLogic).toDispatchActions(['finishSignupEmailPrecheck'])
+ await expectLogic(authLogic).toMatchValues({ step: 'signup_credentials' })
+ })
+
+ it('offers login for an email that signup finds taken, with the password field', async () => {
+ signupPrecheck = () => [
+ 409,
+ {
+ email_exists: true,
+ code: 'account_exists',
+ detail: 'There is already an account with this email address.',
+ },
+ ]
+
+ await expectLogic(authLogic, () => authLogic.actions.continueWithEmail()).toDispatchActions([
+ 'chooseAccountPath',
+ ])
+ await expectLogic(signupLogic).toDispatchActions(['setSignupEmailError']).toMatchValues({
+ signupEmailTaken: true,
+ })
+ await expectLogic(authLogic).toMatchValues({ step: 'email' })
+
+ authLogic.actions.chooseAccountPath('login', true)
+ await expectLogic(authLogic).toMatchValues({ step: 'login', accountExists: true, emailError: null })
+ })
+
+ it('drops the passkey registered for the previous email when the person changes it', async () => {
+ await expectLogic(authLogic, () => authLogic.actions.continueWithEmail()).toDispatchActions([
+ 'chooseAccountPath',
+ ])
+ await expectLogic(signupLogic).toDispatchActions(['finishSignupEmailPrecheck'])
+ signupLogic.actions.setPasskeyRegistered(true)
+
+ authLogic.actions.backToEmail()
+ await expectLogic(signupLogic).toMatchValues({ passkeyRegistered: false })
+ })
+ })
+
+ describe('funnel events', () => {
+ let accountExists: boolean
+ let holdPrecheck: Promise<void> | null
+
+ beforeEach(() => {
+ accountExists = false
+ holdPrecheck = null
+ useMocks({
+ get: {
+ '/_preflight': () => [200, { ...preflightJson, can_create_org: true }],
+ },
+ post: {
+ '/api/login/precheck': async () => {
+ await holdPrecheck
+ return [200, { account_exists: accountExists, saml_available: false }]
+ },
+ '/api/signup/precheck': () => [200, { email_exists: false, pending_invite: null }],
+ },
+ })
+ initKeaTests()
+ jest.mocked(posthog.capture).mockClear()
+ router.actions.push('/signup')
+ authLogic.mount()
+ authTelemetryLogic.mount()
+ })
+
+ afterEach(() => {
+ authTelemetryLogic.unmount()
+ authLogic.unmount()
+ })
+
+ function capturedEvents(): [string, Record<string, any>][] {
+ return jest
+ .mocked(posthog.capture)
+ .mock.calls.filter(([name]) => name.startsWith('auth '))
+ .map(([name, properties]) => [name, properties as Record<string, any>])
+ }
+
+ it.each<[string, boolean, AuthAccountPath, string]>([
+ ['a new email', false, 'signup', 'signup_credentials'],
+ ['an existing account', true, 'login', 'login'],
+ ])('reports each step of %s once, plus the routing decision', async (_name, exists, path, step) => {
+ accountExists = exists
+ loginLogic.actions.setLoginValue('email', '[email protected]')
+
+ await expectLogic(authLogic, () => authLogic.actions.continueWithEmail()).toDispatchActions([
+ 'chooseAccountPath',
+ ])
+ if (path === 'signup') {
+ await expectLogic(signupLogic).toDispatchActions(['finishSignupEmailPrecheck'])
+ }
+
+ const [first, ...rest] = capturedEvents()
+ expect(first).toEqual(['auth step viewed', expect.objectContaining({ step: 'email', entry: 'signup' })])
+ expect(rest).toHaveLength(2)
+ expect(rest).toEqual(
+ expect.arrayContaining([
+ [
+ 'auth email submitted',
+ expect.objectContaining({ entry: 'signup', routed_to: path, account_exists: exists }),
+ ],
+ ['auth step viewed', expect.objectContaining({ step, entry: 'signup' })],
+ ])
+ )
+ })
+
+ it('ignores a precheck answer for an email the person has since changed', async () => {
+ accountExists = true
+ let releasePrecheck = (): void => {}
+ holdPrecheck = new Promise((resolve) => {
+ releasePrecheck = resolve
+ })
+ loginLogic.actions.setLoginValue('email', '[email protected]')
+ authLogic.actions.continueWithEmail()
+ loginLogic.actions.setLoginValue('email', '[email protected]')
+ releasePrecheck()
+
+ await expectLogic(loginLogic).toDispatchActions(['precheckSuccess'])
+ await expectLogic(authLogic).toNotHaveDispatchedActions(['chooseAccountPath']).toMatchValues({
+ step: 'email',
+ isEmailSubmitting: false,
+ })
+ })
+ })
+})
diff --git a/frontend/src/scenes/authentication/auth/authLogic.ts b/frontend/src/scenes/authentication/auth/authLogic.ts
new file mode 100644
index 000000000000..59d4c762671a
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/authLogic.ts
@@ -0,0 +1,359 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { router, urlToAction } from 'kea-router'
+
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { isEmail } from 'lib/utils/url'
+import { AuthEntry, AuthStep } from 'scenes/authentication/shared/authStepViewed'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+import { urls } from 'scenes/urls'
+
+import type { PreflightStatus } from '~/types'
+
+import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
+import { LoginForm, PrecheckResponseType, loginLogic } from './loginLogic'
+import { PendingInvite, maintenanceSignupRedirectUrl, signupLogic } from './signupLogic'
+
+export type AuthAccountPath = 'login' | 'signup'
+
+/** `verify_email` is its own scene, so this page never shows it. */
+export type AuthPageStep = Exclude<AuthStep, 'verify_email'>
+
+/** Whether a person without an account may create one with email and password on this page. */
+export function canSignUpWithEmail(precheck: PrecheckResponseType, preflight: PreflightStatus | null): boolean {
+ // A self-hosted instance that cannot create organizations refuses every signup, so new people
+ // there need an invite link. An enforced domain sends everyone through its IdP.
+ return !!preflight?.can_create_org && !precheck.sso_enforcement
+}
+
+export function accountPathFor(precheck: PrecheckResponseType, preflight: PreflightStatus | null): AuthAccountPath {
+ // Demo signup logs an existing demo user straight in, and demo users have no password to type.
+ if (preflight?.demo) {
+ return 'signup'
+ }
+ // A domain with SAML or OIDC lets its IdP create the account, and only the login step offers
+ // those buttons. That step links to email signup when `canSignUpWithEmail` allows it.
+ if (!canSignUpWithEmail(precheck, preflight) || precheck.saml_available || precheck.oidc_available) {
+ return 'login'
+ }
+ // Only a definite "no account" goes to signup. An unknown answer (a failed precheck) shows the
+ // login step, so an existing account is never pushed into creating a second one.
+ return precheck.account_exists === false ? 'signup' : 'login'
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface authLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ codeVerificationRequired: boolean // loginLogic
+ login: LoginForm // loginLogic
+ precheckResponse: PrecheckResponseType // loginLogic
+ preflight: PreflightStatus | null // preflightLogic
+ isSignupEmailChecking: boolean // signupLogic
+ panel: number // signupLogic
+ pendingInvite: PendingInvite | null // signupLogic
+ signupEmailError: string | null // signupLogic
+ accountExists: boolean | null
+ accountPath: AuthAccountPath | null
+ awaitingPrecheckFor: string | null
+ canSignUpWithEmail: boolean
+ emailError: string | null
+ emailValidationError: string | null
+ entry: AuthEntry
+ isEmailSubmitting: boolean
+ step: AuthPageStep
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface authLogicActions {
+ clearGeneralError: () => {
+ value: true
+ } // loginLogic
+ exitCodeVerification: () => {
+ value: true
+ } // loginLogic
+ precheck: (args_0: { autoAttempt?: boolean; email: string }) => {
+ autoAttempt?: boolean
+ email: string
+ } // loginLogic
+ precheckSuccess: (
+ precheckResponse: PrecheckResponseType,
+ payload?:
+ | {
+ autoAttempt?: boolean
+ email: string
+ }
+ | undefined
+ ) => {
+ payload?: {
+ autoAttempt?: boolean
+ email: string
+ }
+ precheckResponse: PrecheckResponseType
+ } // loginLogic
+ setLoginValue: (
+ key: import('node_modules/kea-forms/lib').FieldName,
+ value: any
+ ) => {
+ name: import('node_modules/kea-forms/lib').FieldName
+ value: any
+ } // loginLogic
+ precheckSignupEmail: (email: string) => {
+ email: string
+ } // signupLogic
+ resetSignupCredentials: () => {
+ value: true
+ } // signupLogic
+ setPanel: (panel: number) => {
+ panel: number
+ } // signupLogic
+ setPendingInvite: (invite: PendingInvite | null) => {
+ invite: PendingInvite | null
+ } // signupLogic
+ setSignupEmailError: (
+ error: string | null,
+ isTaken?: boolean | undefined
+ ) => {
+ error: string | null
+ isTaken: boolean
+ } // signupLogic
+ backToEmail: () => {
+ value: true
+ }
+ chooseAccountPath: (
+ accountPath: AuthAccountPath,
+ accountExists: boolean | null
+ ) => {
+ accountExists: boolean | null
+ accountPath: AuthAccountPath
+ }
+ continueWithEmail: () => {
+ value: true
+ }
+ setAwaitingPrecheckFor: (email: string | null) => {
+ email: string | null
+ }
+ setEmailValidationError: (error: string | null) => {
+ error: string | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface authLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ entry: (location: { hash: string; pathname: string; search: string }) => AuthEntry
+ step: (
+ accountPath: AuthAccountPath | null,
+ codeVerificationRequired: boolean,
+ panel: number,
+ pendingInvite: PendingInvite | null
+ ) => AuthPageStep
+ canSignUpWithEmail: (precheckResponse: PrecheckResponseType, preflight: PreflightStatus | null) => boolean
+ isEmailSubmitting: (awaitingPrecheckFor: string | null, isSignupEmailChecking: boolean) => boolean
+ emailError: (emailValidationError: string | null, signupEmailError: string | null) => string | null
+ }
+}
+
+export type authLogicType = MakeLogicType<authLogicValues, authLogicActions, Record<string, any>, authLogicMeta>
+
+/**
+ * The scene logic behind both `/login` and `/signup`. The page asks for an email first, and the
+ * precheck answer decides whether the person logs in (`loginLogic`) or creates an account
+ * (`signupLogic`). The URL only changes the copy.
+ */
+export const authLogic = kea<authLogicType>([
+ path(['scenes', 'authentication', 'auth', 'authLogic']),
+ connect(() => ({
+ values: [
+ preflightLogic,
+ ['preflight'],
+ featureFlagLogic,
+ ['featureFlags'],
+ loginLogic,
+ ['login', 'codeVerificationRequired', 'precheckResponse'],
+ signupLogic,
+ ['panel', 'pendingInvite', 'isSignupEmailChecking', 'signupEmailError'],
+ ],
+ actions: [
+ loginLogic,
+ ['precheck', 'precheckSuccess', 'setLoginValue', 'clearGeneralError', 'exitCodeVerification'],
+ signupLogic,
+ ['precheckSignupEmail', 'setSignupEmailError', 'setPendingInvite', 'setPanel', 'resetSignupCredentials'],
+ ],
+ })),
+ actions({
+ continueWithEmail: true,
+ setEmailValidationError: (error: string | null) => ({ error }),
+ setAwaitingPrecheckFor: (email: string | null) => ({ email }),
+ chooseAccountPath: (accountPath: AuthAccountPath, accountExists: boolean | null) => ({
+ accountPath,
+ accountExists,
+ }),
+ backToEmail: true,
+ }),
+ reducers({
+ accountPath: [
+ null as AuthAccountPath | null,
+ {
+ chooseAccountPath: (_, { accountPath }) => accountPath,
+ backToEmail: () => null,
+ },
+ ],
+ // Whether an account exists for the email, as known when the page chose the path. Null means
+ // unknown, such as after a failed precheck. "Log in instead" on a taken email sets true even
+ // though the precheck, which matches the exact address, answered false.
+ accountExists: [
+ null as boolean | null,
+ {
+ chooseAccountPath: (_, { accountExists }) => accountExists,
+ backToEmail: () => null,
+ },
+ ],
+ // The email that Continue submitted. The precheck can also run on its own while the person
+ // types, and only an answer for this email moves the page on.
+ awaitingPrecheckFor: [
+ null as string | null,
+ {
+ setAwaitingPrecheckFor: (_, { email }) => email,
+ },
+ ],
+ emailValidationError: [
+ null as string | null,
+ {
+ setEmailValidationError: (_, { error }) => error,
+ },
+ ],
+ }),
+ selectors({
+ entry: [
+ () => [router.selectors.location],
+ (location: { pathname: string }): AuthEntry => (location.pathname === urls.signup() ? 'signup' : 'login'),
+ ],
+ step: [
+ (s) => [s.accountPath, s.codeVerificationRequired, s.panel, s.pendingInvite],
+ (
+ accountPath: AuthAccountPath | null,
+ codeVerificationRequired: boolean,
+ panel: number,
+ pendingInvite: PendingInvite | null
+ ): AuthPageStep => {
+ if (accountPath === 'login') {
+ return codeVerificationRequired ? 'login_code' : 'login'
+ }
+ if (accountPath === 'signup') {
+ if (pendingInvite) {
+ return 'signup_pending_invite'
+ }
+ if (panel === 1) {
+ return 'signup_credentials'
+ }
+ if (panel === 2) {
+ return 'signup_profile'
+ }
+ }
+ // Signup panel 0 is this step too: the signup precheck rejected the email, and its
+ // error shows under the email field.
+ return 'email'
+ },
+ ],
+ canSignUpWithEmail: [
+ (s) => [s.precheckResponse, s.preflight],
+ (precheckResponse: PrecheckResponseType, preflight: PreflightStatus | null): boolean =>
+ canSignUpWithEmail(precheckResponse, preflight),
+ ],
+ isEmailSubmitting: [
+ (s) => [s.awaitingPrecheckFor, s.isSignupEmailChecking],
+ (awaitingPrecheckFor: string | null, isSignupEmailChecking: boolean): boolean =>
+ awaitingPrecheckFor !== null || isSignupEmailChecking,
+ ],
+ emailError: [
+ (s) => [s.emailValidationError, s.signupEmailError],
+ (emailValidationError: string | null, signupEmailError: string | null): string | null =>
+ emailValidationError ?? signupEmailError,
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ continueWithEmail: () => {
+ const email = values.login.email.trim()
+ if (!email) {
+ actions.setEmailValidationError('Please enter your email to continue')
+ return
+ }
+ // No `requireTLD`: the backend accepts internationalized TLDs such as `xn--p1ai`
+ if (!isEmail(email)) {
+ actions.setEmailValidationError('Please use a valid email address')
+ return
+ }
+ if (email !== values.login.email) {
+ actions.setLoginValue('email', email)
+ }
+ actions.clearGeneralError()
+ actions.setAwaitingPrecheckFor(email)
+ // Continue is an explicit gesture, so a passwordless account with one sign-in method may
+ // go straight to its provider (`autoAttempt`).
+ actions.precheck({ email, autoAttempt: true })
+ },
+ precheckSuccess: ({ precheckResponse }) => {
+ const email = values.awaitingPrecheckFor
+ if (!email || precheckResponse.email !== email) {
+ return
+ }
+ actions.setAwaitingPrecheckFor(null)
+ actions.chooseAccountPath(
+ accountPathFor(precheckResponse, values.preflight),
+ precheckResponse.precheckFailed ? null : (precheckResponse.account_exists ?? null)
+ )
+ },
+ chooseAccountPath: ({ accountPath }) => {
+ if (accountPath === 'login') {
+ // "Log in instead" on a taken email leaves the signup error behind
+ actions.setSignupEmailError(null)
+ return
+ }
+ const email = values.login.email.trim()
+ const maintenanceRedirectUrl = maintenanceSignupRedirectUrl(values.preflight, values.featureFlags, email)
+ if (maintenanceRedirectUrl) {
+ window.location.href = maintenanceRedirectUrl
+ return
+ }
+ // Start from a clean signup state, so an earlier attempt cannot show its panel first
+ actions.setPendingInvite(null)
+ actions.setPanel(0)
+ actions.precheckSignupEmail(email)
+ },
+ backToEmail: () => {
+ actions.exitCodeVerification()
+ actions.setLoginValue('password', '')
+ actions.clearGeneralError()
+ actions.setPendingInvite(null)
+ actions.setPanel(0)
+ // A passkey or password set for the previous email would fail signup with the next one
+ actions.resetSignupCredentials()
+ },
+ setLoginValue: ({ name }) => {
+ if (name !== 'email') {
+ return
+ }
+ // A precheck answer that is still on its way describes the previous email
+ if (values.awaitingPrecheckFor !== null && values.awaitingPrecheckFor !== values.login.email) {
+ actions.setAwaitingPrecheckFor(null)
+ }
+ if (values.accountPath !== null && values.step === 'email') {
+ actions.backToEmail()
+ }
+ if (values.emailError) {
+ actions.setEmailValidationError(null)
+ actions.setSignupEmailError(null)
+ }
+ },
+ })),
+ urlToAction(({ actions, values }) => {
+ // `?email=` gives the `generate_demo_data` command a quick login link. Demo signup is left to
+ // `signupLogic`, which signs the demo user in straight away.
+ const prefillEmail = (_: Record<string, any>, { email }: Record<string, any>): void => {
+ if (email && !(values.preflight?.demo && values.entry === 'signup')) {
+ actions.setLoginValue('email', email)
+ actions.precheck({ email })
+ }
+ }
+ return { '/login': prefillEmail, '/signup': prefillEmail }
+ }),
+])
diff --git a/frontend/src/scenes/authentication/auth/authTelemetryLogic.ts b/frontend/src/scenes/authentication/auth/authTelemetryLogic.ts
new file mode 100644
index 000000000000..0ee91da576f3
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/authTelemetryLogic.ts
@@ -0,0 +1,59 @@
+import { MakeLogicType, connect, kea, listeners, path } from 'kea'
+import { subscriptions } from 'kea-subscriptions'
+import posthog from 'posthog-js'
+
+import { captureAuthStepViewed, pendingOAuthConnectionProperties } from 'scenes/authentication/shared/authStepViewed'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+
+import type { PreflightStatus } from '../../../types'
+import type { AuthEntry } from '../shared/authStepViewed'
+import { authLogic } from './authLogic'
+import type { AuthPageStep } from './authLogic'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface authTelemetryLogicValues {
+ entry: AuthEntry // authLogic
+ step: AuthPageStep // authLogic
+ preflight: PreflightStatus | null // preflightLogic
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface authTelemetryLogicActions {
+ chooseAccountPath: (
+ accountPath: import('./authLogic').AuthAccountPath,
+ accountExists: boolean | null
+ ) => {
+ accountExists: boolean | null
+ accountPath: import('./authLogic').AuthAccountPath
+ } // authLogic
+}
+
+export type authTelemetryLogicType = MakeLogicType<authTelemetryLogicValues, authTelemetryLogicActions>
+
+/**
+ * Reports the login and signup funnel of the auth page. `step` is derived from three logics, so a
+ * subscription reports it on mount and on every change. `loginTelemetryLogic` still reports the
+ * password attempts and their failures.
+ */
+export const authTelemetryLogic = kea<authTelemetryLogicType>([
+ path(['scenes', 'authentication', 'auth', 'authTelemetryLogic']),
+ connect(() => ({
+ values: [authLogic, ['step', 'entry'], preflightLogic, ['preflight']],
+ actions: [authLogic, ['chooseAccountPath']],
+ })),
+ listeners(({ values }) => ({
+ chooseAccountPath: ({ accountPath, accountExists }) => {
+ // pinned: analytics event name and property names
+ posthog.capture('auth email submitted', {
+ entry: values.entry,
+ routed_to: accountPath,
+ account_exists: accountExists,
+ region: values.preflight?.region,
+ ...pendingOAuthConnectionProperties(),
+ })
+ },
+ })),
+ subscriptions(({ values }) => ({
+ step: (step) => captureAuthStepViewed(step, values.entry),
+ })),
+])
diff --git a/frontend/src/scenes/authentication/auth/components/ConnectTitle.tsx b/frontend/src/scenes/authentication/auth/components/ConnectTitle.tsx
new file mode 100644
index 000000000000..9907ea2f2863
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/components/ConnectTitle.tsx
@@ -0,0 +1,10 @@
+import { HighlightedName } from './HighlightedName'
+
+export function ConnectTitle({ lead, clientName }: { lead: string; clientName: string }): JSX.Element {
+ return (
+ <>
+ <span>{lead} </span>
+ <HighlightedName>{clientName}</HighlightedName>
+ </>
+ )
+}
diff --git a/frontend/src/scenes/authentication/auth/components/HighlightedName.tsx b/frontend/src/scenes/authentication/auth/components/HighlightedName.tsx
new file mode 100644
index 000000000000..1567941e56a0
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/components/HighlightedName.tsx
@@ -0,0 +1,7 @@
+export function HighlightedName({ children }: { children: string }): JSX.Element {
+ return (
+ <span className="px-1 rounded-md bg-[color-mix(in_srgb,var(--color-blue-500)_10%,transparent)] text-[var(--color-blue-500)]">
+ {children}
+ </span>
+ )
+}
diff --git a/frontend/src/scenes/authentication/auth/components/LoginErrorBanner.tsx b/frontend/src/scenes/authentication/auth/components/LoginErrorBanner.tsx
new file mode 100644
index 000000000000..b454f1d4c5bb
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/components/LoginErrorBanner.tsx
@@ -0,0 +1,129 @@
+import { useActions, useValues } from 'kea'
+
+import { supportLogic } from 'lib/components/Support/supportLogic'
+import { SSO_PROVIDER_NAMES } from 'lib/constants'
+import { Link } from 'lib/lemon-ui/Link'
+import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'
+import { ERROR_MESSAGES } from 'scenes/authentication/shared/loginErrorMessages'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+
+import { LoginMethod, Region, SSOProvider } from '~/types'
+
+import { loginLogic } from '../loginLogic'
+
+function loginMethodLabel(method: LoginMethod): string {
+ if (method === 'password') {
+ return 'password'
+ }
+ if (method === 'passkey') {
+ return 'passkey'
+ }
+ return method ? SSO_PROVIDER_NAMES[method] : ''
+}
+
+// The support form starts empty for the person, so a login-error ticket loses the context the page
+// already holds. Prefill the message with the error code, region, and login methods, so support can
+// triage without a round trip.
+function buildLoginSupportMessage({
+ errorCode,
+ region,
+ ssoEnforcement,
+ availableLoginMethods,
+ precheckTrusted,
+ codeVerificationPending,
+}: {
+ errorCode?: string
+ region?: Region | null
+ ssoEnforcement?: SSOProvider | null
+ availableLoginMethods: LoginMethod[]
+ precheckTrusted: boolean
+ codeVerificationPending: boolean
+}): string {
+ const lines = ['I need help logging in.']
+ if (errorCode) {
+ lines.push(`Error code: ${errorCode}`)
+ }
+ if (region) {
+ lines.push(`Data region: ${region}`)
+ }
+ // Only state the account's methods when the precheck is trustworthy. A failed or stale one
+ // reports permissive defaults (e.g. password login for an SSO-only account), which would point
+ // support the wrong way.
+ if (precheckTrusted) {
+ if (ssoEnforcement) {
+ lines.push(`Login method: SSO enforced (${SSO_PROVIDER_NAMES[ssoEnforcement]})`)
+ } else {
+ const labels = availableLoginMethods.map(loginMethodLabel).filter(Boolean)
+ if (labels.length) {
+ lines.push(`Login methods available: ${labels.join(', ')}`)
+ }
+ }
+ }
+ if (codeVerificationPending) {
+ lines.push('Waiting on an emailed verification code.')
+ }
+ return lines.join('\n')
+}
+
+/** The login error that `loginLogic` holds, from a rejected password or from a sign-in that the server
+ * redirected back with `?error_code=`. The email step shows it too, because a failed SSO or social
+ * sign-in lands there. */
+export function LoginErrorBanner(): JSX.Element | null {
+ const { generalError, precheckResponse, login, availableLoginMethods, codeVerificationRequired } =
+ useValues(loginLogic)
+ const { preflight } = useValues(preflightLogic)
+ const { openSupportForm } = useActions(supportLogic)
+ const { sendSupportRequest } = useValues(supportLogic)
+
+ if (!generalError) {
+ return null
+ }
+
+ return (
+ <AuthBanner variant="danger" className="mb-4">
+ <span>
+ {generalError.detail ||
+ ERROR_MESSAGES[generalError.code] ||
+ 'Could not complete your login. Please try again.'}
+ </span>
+ {preflight?.cloud && (
+ <>
+ {' '}
+ <Link
+ data-attr="login-error-contact-support"
+ onClick={(e) => {
+ e.preventDefault()
+ // Trust the precheck only when it resolved for the email now
+ // in the form: a failed precheck reports permissive defaults,
+ // and a stale one still holds the previous email's account.
+ const precheckTrusted =
+ precheckResponse.status === 'completed' &&
+ !precheckResponse.precheckFailed &&
+ precheckResponse.email === login.email
+ openSupportForm({
+ kind: 'support',
+ email: login.email,
+ // Prefill only into an empty form. Passing no message lets
+ // openSupportForm keep a draft the person already started,
+ // so reopening this link never overwrites their text.
+ message: sendSupportRequest.message
+ ? undefined
+ : buildLoginSupportMessage({
+ errorCode: generalError.code,
+ region: preflight?.region,
+ ssoEnforcement: precheckResponse.sso_enforcement,
+ availableLoginMethods,
+ precheckTrusted,
+ codeVerificationPending: codeVerificationRequired,
+ }),
+ })
+ }}
+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
+ >
+ Need help?
+ </Link>
+ </>
+ )}
+ </AuthBanner>
+ )
+}
diff --git a/frontend/src/scenes/authentication/auth/components/OtherRegionNotice.tsx b/frontend/src/scenes/authentication/auth/components/OtherRegionNotice.tsx
new file mode 100644
index 000000000000..4c5a6628ebd6
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/components/OtherRegionNotice.tsx
@@ -0,0 +1,80 @@
+import clsx from 'clsx'
+import { useValues } from 'kea'
+
+import { Link } from 'lib/lemon-ui/Link'
+import { countryCodeToFlag } from 'lib/utils/country'
+import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'
+import { otherRegionLoginUrl, otherRegionOf } from 'scenes/authentication/shared/OtherRegionHint'
+import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+
+/** `no_account` shows before an account is created. `login_failed` shows after a rejected password. */
+export type OtherRegionReason = 'no_account' | 'login_failed'
+
+// pinned: autocapture `data-attr` values, `other-region-login` predates this page
+const SWITCH_DATA_ATTR: Record<OtherRegionReason, string> = {
+ no_account: 'auth-no-account-switch-region',
+ login_failed: 'other-region-login',
+}
+
+/**
+ * A person who already uses PostHog in the other cloud region gets "no account" or "wrong
+ * password" here, and could otherwise create a second, empty account. Most new people are in the
+ * right region, so before signup this is one small line. After a rejected password it is a banner.
+ * A pending OAuth connection is pinned to this region, so the notice stays hidden for it.
+ */
+export function OtherRegionNotice({
+ email,
+ reason,
+ className,
+}: {
+ email: string
+ reason: OtherRegionReason
+ className?: string
+}): JSX.Element | null {
+ const { preflight } = useValues(preflightLogic)
+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)
+
+ if (!preflight?.cloud || !preflight.region || pendingConnection) {
+ return null
+ }
+
+ const otherRegion = otherRegionOf(preflight.region)
+ const search = new URLSearchParams(location.search)
+ search.set('email', email)
+ const switchUrl = otherRegionLoginUrl(preflight.region, `?${search.toString()}`)
+
+ if (reason === 'no_account') {
+ return (
+ <p className={clsx('m-0 text-xs text-secondary text-center', className)}>
+ <span>Already have an account? Maybe it's in our</span>{' '}
+ <Link
+ to={switchUrl}
+ disableClientSideRouting
+ data-attr={SWITCH_DATA_ATTR[reason]}
+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
+ >
+ {countryCodeToFlag(otherRegion)} {otherRegion} region
+ </Link>
+ <span>?</span>
+ </p>
+ )
+ }
+
+ return (
+ <AuthBanner variant="note" className={clsx('mb-5', className)} icon={countryCodeToFlag(otherRegion)}>
+ <p className="m-0">
+ <strong className="text-primary">Wrong region, maybe?</strong>{' '}
+ <span>Your account might live in the {otherRegion}.</span>
+ </p>
+ <Link
+ to={switchUrl}
+ disableClientSideRouting
+ data-attr={SWITCH_DATA_ATTR[reason]}
+ className="inline-block mt-1 font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
+ >
+ Switch to {otherRegion} →
+ </Link>
+ </AuthBanner>
+ )
+}
diff --git a/frontend/src/scenes/authentication/login/SessionRiskBanner.tsx b/frontend/src/scenes/authentication/auth/components/SessionRiskBanner.tsx
similarity index 66%
rename from frontend/src/scenes/authentication/login/SessionRiskBanner.tsx
rename to frontend/src/scenes/authentication/auth/components/SessionRiskBanner.tsx
index 40da5db4d8ea..069aff4248ec 100644
--- a/frontend/src/scenes/authentication/login/SessionRiskBanner.tsx
+++ b/frontend/src/scenes/authentication/auth/components/SessionRiskBanner.tsx
@@ -1,8 +1,8 @@
import { useValues } from 'kea'
-import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'
-import { loginLogic } from './loginLogic'
+import { loginLogic } from '../loginLogic'
export function SessionRiskBanner({ className }: { className?: string }): JSX.Element | null {
const { wasSignedOutForSessionRisk } = useValues(loginLogic)
@@ -12,8 +12,8 @@ export function SessionRiskBanner({ className }: { className?: string }): JSX.El
}
return (
- <LemonBanner type="warning" className={className}>
+ <AuthBanner variant="warning" className={className}>
For your security, we signed you out because this session showed unusual activity. Sign back in to continue.
- </LemonBanner>
+ </AuthBanner>
)
}
diff --git a/frontend/src/scenes/authentication/auth/components/UseDifferentEmailLink.tsx b/frontend/src/scenes/authentication/auth/components/UseDifferentEmailLink.tsx
new file mode 100644
index 000000000000..06057e78ecb5
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/components/UseDifferentEmailLink.tsx
@@ -0,0 +1,21 @@
+import { useActions } from 'kea'
+
+import { Link } from 'lib/lemon-ui/Link'
+
+import { authLogic } from '../authLogic'
+
+export function UseDifferentEmailLink(): JSX.Element {
+ const { backToEmail } = useActions(authLogic)
+
+ return (
+ <p className="mt-5 mb-0 text-sm text-secondary text-center">
+ <Link
+ onClick={() => backToEmail()}
+ data-attr="auth-use-different-email"
+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
+ >
+ ← Use a different email
+ </Link>
+ </p>
+ )
+}
diff --git a/frontend/src/scenes/authentication/login/loginLogic.test.ts b/frontend/src/scenes/authentication/auth/loginLogic.test.ts
similarity index 98%
rename from frontend/src/scenes/authentication/login/loginLogic.test.ts
rename to frontend/src/scenes/authentication/auth/loginLogic.test.ts
index 00a583798bcf..04aa0c8ec968 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.test.ts
+++ b/frontend/src/scenes/authentication/auth/loginLogic.test.ts
@@ -4,13 +4,14 @@ import { expectLogic, testUtilsPlugin } from 'kea-test-utils'
import posthog from 'posthog-js'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
-import { handleLoginRedirect, loginLogic, redirectAfterLogin } from 'scenes/authentication/login/loginLogic'
import { passkeyLogic } from 'scenes/authentication/shared/passkeyLogic'
import { initKea } from '~/initKea'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import { handleLoginRedirect, loginLogic, redirectAfterLogin } from './loginLogic'
+
jest.mock('@simplewebauthn/browser', () => ({ startAuthentication: jest.fn() }))
jest.mock('posthog-js')
@@ -276,7 +277,7 @@ describe('loginLogic', () => {
jest.clearAllMocks()
})
- it('skips a redundant precheck for an already-resolved email but re-runs for a new one', async () => {
+ it('skips a redundant precheck for an already-resolved or in-flight email but re-runs for a new one', async () => {
logic.actions.precheck({ email: '[email protected]' })
await expectLogic(logic).toDispatchActions(['precheckSuccess'])
logic.actions.precheck({ email: '[email protected]' })
@@ -286,6 +287,15 @@ describe('loginLogic', () => {
logic.actions.precheck({ email: '[email protected]' })
await expectLogic(logic).toDispatchActions(['precheckSuccess'])
expect(precheckHandler).toHaveBeenCalledTimes(2)
+
+ logic.actions.precheck({ email: '[email protected]' })
+ logic.actions.precheck({ email: '[email protected]' })
+ await expectLogic(logic)
+ .toDispatchActions(['precheckSuccess'])
+ .toMatchValues({
+ precheckResponse: expect.objectContaining({ email: '[email protected]', status: 'completed' }),
+ })
+ expect(precheckHandler).toHaveBeenCalledTimes(3)
})
it('prechecks the latest email only after typing pauses for 3 seconds', async () => {
diff --git a/frontend/src/scenes/authentication/login/loginLogic.ts b/frontend/src/scenes/authentication/auth/loginLogic.ts
similarity index 94%
rename from frontend/src/scenes/authentication/login/loginLogic.ts
rename to frontend/src/scenes/authentication/auth/loginLogic.ts
index 3ec44e4df15d..c9d885097d1e 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.ts
+++ b/frontend/src/scenes/authentication/auth/loginLogic.ts
@@ -38,6 +38,12 @@ export interface AuthenticateResponseType {
}
export interface PrecheckResponseType {
+ /**
+ * Whether an account, active or deactivated, uses this email. Absent (from an older server or a failed precheck)
+ * means unknown, and the auth page then shows the login step, so an existing account is never
+ * sent into signup.
+ */
+ account_exists?: boolean
sso_enforcement?: SSOProvider | null
saml_available: boolean
oidc_available?: boolean
@@ -220,7 +226,6 @@ export interface loginLogicValues {
restrictToProviders: SSOProvider[] | null
showCodeVerificationErrors: boolean
showLoginErrors: boolean
- signupUrl: string
wasSignedOutForSessionRisk: boolean
}
@@ -387,7 +392,6 @@ export interface loginLogicMeta {
precheckResponse: PrecheckResponseType,
isPasswordLoginUnavailable: boolean
) => SSOProvider[] | null
- signupUrl: (searchParams: Record<string, any>) => string
wasSignedOutForSessionRisk: (searchParams: Record<string, any>) => boolean
}
}
@@ -397,7 +401,7 @@ export type loginLogicType = MakeLogicType<loginLogicValues, loginLogicActions,
const PRECHECK_IDLE_DELAY_MS = 3000
export const loginLogic = kea<loginLogicType>([
- path(['scenes', 'authentication', 'login', 'loginLogic']),
+ path(['scenes', 'authentication', 'auth', 'loginLogic']),
connect(() => ({
values: [
preflightLogic,
@@ -466,7 +470,7 @@ export const loginLogic = kea<loginLogicType>([
},
],
}),
- loaders(({ values }) => ({
+ loaders(({ values, cache }) => ({
precheckResponse: [
{ status: 'pending' } as PrecheckResponseType,
{
@@ -495,14 +499,30 @@ export const loginLogic = kea<loginLogicType>([
return values.precheckResponse
}
+ // Autofill, the typing pause and Continue can all ask for the same email while
+ // its request is still running, so they share that request instead of restarting it.
+ if (cache.inflightPrecheck?.email === email) {
+ return await cache.inflightPrecheck.request
+ }
+
breakpoint()
+ const request = (async (): Promise<PrecheckResponseType> => {
+ try {
+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
+ const response = await api.create<any>('api/login/precheck', { email })
+ return { status: 'completed', ...response, email }
+ } catch {
+ // Never let a failed precheck lock the user out of password login.
+ return precheckFallback(email)
+ }
+ })()
+ cache.inflightPrecheck = { email, request }
try {
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
- const response = await api.create<any>('api/login/precheck', { email })
- return { status: 'completed', ...response, email }
- } catch {
- // Never let a failed precheck lock the user out of password login.
- return precheckFallback(email)
+ return await request
+ } finally {
+ if (cache.inflightPrecheck?.request === request) {
+ cache.inflightPrecheck = null
+ }
}
},
},
@@ -585,13 +605,6 @@ export const loginLogic = kea<loginLogicType>([
(precheckResponse: PrecheckResponseType, isPasswordLoginUnavailable: boolean): SSOProvider[] | null =>
isPasswordLoginUnavailable ? (precheckResponse.social_providers ?? []) : null,
],
- signupUrl: [
- () => [router.selectors.searchParams],
- (searchParams: Record<string, string>) => {
- const nextParam = getRelativeNextPath(searchParams['next'], location)
- return nextParam ? `/signup?next=${encodeURIComponent(nextParam)}` : '/signup'
- },
- ],
wasSignedOutForSessionRisk: [
() => [router.selectors.searchParams],
(searchParams: Record<string, string>): boolean => searchParams['reason'] === 'session_risk',
@@ -756,7 +769,7 @@ export const loginLogic = kea<loginLogicType>([
},
})),
urlToAction(({ actions }) => ({
- '/login': (_, { error_code, error_detail, email, message }) => {
+ '/login': (_, { error_code, error_detail, message }) => {
if (error_code) {
actions.setGeneralError(error_code, error_detail)
router.actions.replace('/login', {})
@@ -767,12 +780,6 @@ export const loginLogic = kea<loginLogicType>([
const { message: _, ...otherParams } = router.values.searchParams
router.actions.replace('/login', otherParams)
}
-
- // This allows us to give a quick login link in the `generate_demo_data` command
- if (email) {
- actions.setLoginValue('email', email)
- actions.precheck({ email })
- }
},
})),
])
diff --git a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.ts b/frontend/src/scenes/authentication/auth/signupLogic.test.ts
similarity index 83%
rename from frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.ts
rename to frontend/src/scenes/authentication/auth/signupLogic.test.ts
index daa9975e0e21..5a78d476da66 100644
--- a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.ts
+++ b/frontend/src/scenes/authentication/auth/signupLogic.test.ts
@@ -10,12 +10,14 @@ import { signupLogic } from './signupLogic'
describe('signupLogic — email error surfacing', () => {
let logic: ReturnType<typeof signupLogic.build>
+ let signupErrorBody: Record<string, any>
beforeEach(() => {
+ signupErrorBody = {}
useMocks({
post: {
'/api/signup/precheck': () => [200, { email_exists: false, pending_invite: null }],
- '/api/signup/': () => [400, { email: ['There is already an account with this email address.'] }],
+ '/api/signup/': () => [400, signupErrorBody],
},
})
initKeaTests()
@@ -28,36 +30,52 @@ describe('signupLogic — email error surfacing', () => {
logic.unmount()
})
- it('redirects to the email panel and shows the error when the final POST fails with an email error', async () => {
- // Advance through email panel (precheck passes)
- logic.actions.setSignupPanelEmailValue('email', '[email protected]')
- logic.actions.submitSignupPanelEmail()
- await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.panel).toBe(1)
-
- // Advance through auth panel (a valid password is required to pass form validation)
- logic.actions.setSignupPanelAuthValue('password', 'Str0ng-Test-Pass!')
- logic.actions.submitSignupPanelAuth()
- await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.panel).toBe(2)
-
- // Submit onboarding — final POST fails with an email error
- logic.actions.setSignupPanelOnboardingValues({
- name: 'Jane Doe',
- organization_name: 'Hogflix',
- role_at_organization: 'engineer',
- referral_source: '',
- referral_source_ai_prompt: '',
- })
- logic.actions.submitSignupPanelOnboarding()
- await expectLogic(logic).toFinishAllListeners()
-
- // User should be sent back to step 0 with the email error shown there
- expect(logic.values.panel).toBe(0)
- expect(logic.values.signupPanelEmailManualErrors.email).toBe(
- 'There is already an account with this email address.'
- )
- })
+ it.each([
+ ['a field-keyed body', { email: ['There is already an account with this email address.'] }, false],
+ [
+ 'a DRF error body',
+ {
+ type: 'validation_error',
+ code: 'unique',
+ detail: 'There is already an account with this email address.',
+ attr: 'email',
+ },
+ true,
+ ],
+ ])(
+ 'redirects to the email panel and shows the error when the final POST fails with %s',
+ async (_name, body, offersLogin) => {
+ signupErrorBody = body
+ // Advance through email panel (precheck passes)
+ logic.actions.precheckSignupEmail('[email protected]')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.panel).toBe(1)
+
+ // Advance through auth panel (a valid password is required to pass form validation)
+ logic.actions.setSignupPanelAuthValue('password', 'Str0ng-Test-Pass!')
+ logic.actions.submitSignupPanelAuth()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.panel).toBe(2)
+
+ // Submit onboarding — final POST fails with an email error
+ logic.actions.setSignupPanelOnboardingValues({
+ name: 'Jane Doe',
+ organization_name: 'Hogflix',
+ role_at_organization: 'engineer',
+ referral_source: '',
+ referral_source_ai_prompt: '',
+ })
+ logic.actions.submitSignupPanelOnboarding()
+ await expectLogic(logic).toFinishAllListeners()
+
+ // User should be sent back to step 0 with the email error shown there
+ expect(logic.values.panel).toBe(0)
+ expect(logic.values.signupEmailError).toBe('There is already an account with this email address.')
+ expect(logic.values.signupEmailTaken).toBe(offersLogin)
+ // The password picked for this email must not carry over to the next one
+ expect(logic.values.signupPanelAuth.password).toBe('')
+ }
+ )
})
describe('signupLogic — pending invite banner', () => {
@@ -87,8 +105,7 @@ describe('signupLogic — pending invite banner', () => {
})
it('shows the pending invite banner instead of advancing the panel', async () => {
- logic.actions.setSignupPanelEmailValue('email', '[email protected]')
- logic.actions.submitSignupPanelEmail()
+ logic.actions.precheckSignupEmail('[email protected]')
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.pendingInvite).toEqual({ organization_name: 'Acme Corp' })
expect(logic.values.panel).toBe(0)
@@ -100,16 +117,14 @@ describe('signupLogic — pending invite banner', () => {
'/api/signup/precheck': () => [200, { email_exists: false, pending_invite: null }],
},
})
- logic.actions.setSignupPanelEmailValue('email', '[email protected]')
- logic.actions.submitSignupPanelEmail()
+ logic.actions.precheckSignupEmail('[email protected]')
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.pendingInvite).toBeNull()
expect(logic.values.panel).toBe(1)
})
it('advances the panel when the user dismisses the banner', async () => {
- logic.actions.setSignupPanelEmailValue('email', '[email protected]')
- logic.actions.submitSignupPanelEmail()
+ logic.actions.precheckSignupEmail('[email protected]')
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.pendingInvite).not.toBeNull()
logic.actions.dismissPendingInvite()
@@ -120,8 +135,7 @@ describe('signupLogic — pending invite banner', () => {
it('skips the banner when skip_invite_check=1 is on the URL', async () => {
router.actions.push('/signup', { skip_invite_check: '1' })
- logic.actions.setSignupPanelEmailValue('email', '[email protected]')
- logic.actions.submitSignupPanelEmail()
+ logic.actions.precheckSignupEmail('[email protected]')
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.pendingInvite).toBeNull()
expect(logic.values.panel).toBe(1)
@@ -149,8 +163,7 @@ describe('signupLogic — retrying a panel after a failed submit', () => {
let signupRequestCount: number
const advanceToOnboardingPanel = async (): Promise<void> => {
- logic.actions.setSignupPanelEmailValue('email', '[email protected]')
- logic.actions.submitSignupPanelEmail()
+ logic.actions.precheckSignupEmail('[email protected]')
await expectLogic(logic).toFinishAllListeners()
logic.actions.setSignupPanelAuthValue('password', 'Str0ng-Test-Pass!')
logic.actions.submitSignupPanelAuth()
@@ -192,20 +205,16 @@ describe('signupLogic — retrying a panel after a failed submit', () => {
})
it('advances when a different email is submitted after an account-exists error', async () => {
- logic.actions.setSignupPanelEmailValue('email', '[email protected]')
- logic.actions.submitSignupPanelEmail()
+ logic.actions.precheckSignupEmail('[email protected]')
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.panel).toBe(0)
- expect(logic.values.signupPanelEmailManualErrors.email).toBe(
- 'There is already an account with this email address.'
- )
+ expect(logic.values.signupEmailError).toBe('There is already an account with this email address.')
- logic.actions.setSignupPanelEmailValue('email', '[email protected]')
- logic.actions.submitSignupPanelEmail()
+ logic.actions.precheckSignupEmail('[email protected]')
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.panel).toBe(1)
- expect(logic.values.signupPanelEmailManualErrors.email).toBeUndefined()
+ expect(logic.values.signupEmailError).toBeNull()
})
it('reissues the signup request when onboarding is submitted again after a generic error', async () => {
@@ -234,8 +243,7 @@ describe('signupLogic — name handling', () => {
let signupRequestBody: Record<string, any> | null
const advanceToOnboardingPanel = async (): Promise<void> => {
- logic.actions.setSignupPanelEmailValue('email', '[email protected]')
- logic.actions.submitSignupPanelEmail()
+ logic.actions.precheckSignupEmail('[email protected]')
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.panel).toBe(1)
logic.actions.setSignupPanelAuthValue('password', 'Str0ng-Test-Pass!')
@@ -414,8 +422,7 @@ describe('signupLogic — name handling', () => {
expect(logic.values.signupPanelAuthManualErrors.password).toBeTruthy()
logic.actions.setPanel(0)
- logic.actions.setSignupPanelEmailValue('email', '[email protected]')
- logic.actions.submitSignupPanelEmail()
+ logic.actions.precheckSignupEmail('[email protected]')
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.panel).toBe(1)
diff --git a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts b/frontend/src/scenes/authentication/auth/signupLogic.ts
similarity index 71%
rename from frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts
rename to frontend/src/scenes/authentication/auth/signupLogic.ts
index 4e6123460b15..bc325f5b5838 100644
--- a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts
+++ b/frontend/src/scenes/authentication/auth/signupLogic.ts
@@ -23,8 +23,8 @@ import { getPasskeyErrorMessage, isWebAuthnCancellation } from 'scenes/settings/
import { RegistrationBeginResponse } from 'scenes/settings/user/passkeySettingsLogic'
import { urls } from 'scenes/urls'
-import type { FeatureFlagsSet } from '../../../../lib/logic/featureFlagLogic'
-import type { PreflightStatus } from '../../../../types'
+import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
+import type { PreflightStatus } from '../../../types'
export interface AccountResponse {
success: boolean
@@ -34,10 +34,6 @@ export interface AccountResponse {
errorAttribute?: string
}
-export interface SignupPanelEmailForm {
- email: string
-}
-
export interface SignupPanelAuthForm {
password: string
}
@@ -61,35 +57,29 @@ interface SignupEmailPrecheckResponse {
pending_invite?: PendingInvite | null
}
-export const emailRegex: RegExp =
- // oxlint-disable-next-line no-control-regex
- /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface signupLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
preflight: PreflightStatus | null // preflightLogic
challengeNonce: string | null
challengeRequired: boolean
- emailCaseNotice: string | undefined
- emailWasNormalized: boolean
isPasskeyRegistering: boolean
isPendingInviteResending: boolean
+ isSignupEmailChecking: boolean
isSignupPanelAuthSubmitting: boolean
isSignupPanelAuthValid: boolean
- isSignupPanelEmailSubmitting: boolean
- isSignupPanelEmailValid: boolean
isSignupPanelOnboardingSubmitting: boolean
isSignupPanelOnboardingValid: boolean
- loginUrl: string
panel: number
passkeyError: string | null
passkeyRegistered: boolean
pendingInvite: PendingInvite | null
pendingInviteResent: boolean
showSignupPanelAuthErrors: boolean
- showSignupPanelEmailErrors: boolean
showSignupPanelOnboardingErrors: boolean
+ signupEmail: string
+ signupEmailError: string | null
+ signupEmailTaken: boolean
signupPanelAuth: SignupPanelAuthForm
signupPanelAuthAllErrors: Record<string, any>
signupPanelAuthChanged: boolean
@@ -99,15 +89,6 @@ export interface signupLogicValues {
signupPanelAuthTouched: boolean
signupPanelAuthTouches: Record<string, boolean>
signupPanelAuthValidationErrors: DeepPartialMap<SignupPanelAuthForm, ValidationErrorType>
- signupPanelEmail: SignupPanelEmailForm
- signupPanelEmailAllErrors: Record<string, any>
- signupPanelEmailChanged: boolean
- signupPanelEmailErrors: DeepPartialMap<SignupPanelEmailForm, ValidationErrorType>
- signupPanelEmailHasErrors: boolean
- signupPanelEmailManualErrors: Record<string, any>
- signupPanelEmailTouched: boolean
- signupPanelEmailTouches: Record<string, boolean>
- signupPanelEmailValidationErrors: DeepPartialMap<SignupPanelEmailForm, ValidationErrorType>
signupPanelOnboarding: SignupPanelOnboardingForm
signupPanelOnboardingAllErrors: Record<string, any>
signupPanelOnboardingChanged: boolean
@@ -127,7 +108,10 @@ export interface signupLogicActions {
dismissPendingInvite: () => {
value: true
}
- normalizeEmailWithDelay: (email: string) => {
+ finishSignupEmailPrecheck: () => {
+ value: true
+ }
+ precheckSignupEmail: (email: string) => {
email: string
}
registerPasskey: () => {
@@ -139,12 +123,12 @@ export interface signupLogicActions {
resetChallenge: () => {
value: true
}
+ resetSignupCredentials: () => {
+ value: true
+ }
resetSignupPanelAuth: (values?: SignupPanelAuthForm) => {
values?: SignupPanelAuthForm
}
- resetSignupPanelEmail: (values?: SignupPanelEmailForm) => {
- values?: SignupPanelEmailForm
- }
resetSignupPanelOnboarding: (values?: SignupPanelOnboardingForm) => {
values?: SignupPanelOnboardingForm
}
@@ -154,9 +138,6 @@ export interface signupLogicActions {
setChallengeRequired: (required: boolean) => {
required: boolean
}
- setEmailNormalized: (wasNormalized: boolean) => {
- wasNormalized: boolean
- }
setPanel: (panel: number) => {
panel: number
}
@@ -178,6 +159,16 @@ export interface signupLogicActions {
setPendingInviteResent: (resent: boolean) => {
resent: boolean
}
+ setSignupEmail: (email: string) => {
+ email: string
+ }
+ setSignupEmailError: (
+ error: string | null,
+ isTaken?: boolean
+ ) => {
+ error: string | null
+ isTaken: boolean
+ }
setSignupPanelAuthManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
@@ -191,19 +182,6 @@ export interface signupLogicActions {
setSignupPanelAuthValues: (values: DeepPartial<SignupPanelAuthForm>) => {
values: DeepPartial<SignupPanelAuthForm>
}
- setSignupPanelEmailManualErrors: (errors: Record<string, any>) => {
- errors: Record<string, any>
- }
- setSignupPanelEmailValue: (
- key: FieldName,
- value: any
- ) => {
- name: FieldName
- value: any
- }
- setSignupPanelEmailValues: (values: DeepPartial<SignupPanelEmailForm>) => {
- values: DeepPartial<SignupPanelEmailForm>
- }
setSignupPanelOnboardingManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
@@ -239,22 +217,6 @@ export interface signupLogicActions {
submitSignupPanelAuthSuccess: (signupPanelAuth: SignupPanelAuthForm) => {
signupPanelAuth: SignupPanelAuthForm
}
- submitSignupPanelEmail: () => {
- value: boolean
- }
- submitSignupPanelEmailFailure: (
- error: Error,
- errors: Record<string, any>
- ) => {
- error: Error
- errors: Record<string, any>
- }
- submitSignupPanelEmailRequest: (signupPanelEmail: SignupPanelEmailForm) => {
- signupPanelEmail: SignupPanelEmailForm
- }
- submitSignupPanelEmailSuccess: (signupPanelEmail: SignupPanelEmailForm) => {
- signupPanelEmail: SignupPanelEmailForm
- }
submitSignupPanelOnboarding: () => {
value: boolean
}
@@ -274,9 +236,6 @@ export interface signupLogicActions {
touchSignupPanelAuthField: (key: string) => {
key: string
}
- touchSignupPanelEmailField: (key: string) => {
- key: string
- }
touchSignupPanelOnboardingField: (key: string) => {
key: string
}
@@ -286,22 +245,71 @@ export interface signupLogicActions {
export interface signupLogicMeta {
__keaTypeGenInternalSelectorTypes: {
validatedPassword: (signupPanelAuth: SignupPanelAuthForm) => ValidatedPasswordResult
- emailCaseNotice: (emailWasNormalized: boolean) => string | undefined
- loginUrl: (searchParams: Record<string, any>) => string
}
}
export type signupLogicType = MakeLogicType<signupLogicValues, signupLogicActions, Record<string, any>, signupLogicMeta>
+const MAINTENANCE_REGIONS = ['eu', 'us'] as const
+type MaintenanceRegion = (typeof MAINTENANCE_REGIONS)[number]
+
+/** The cloud region that takes all signups while the other one is under maintenance, if any. */
+function maintenanceSignupRegion(
+ preflight: PreflightStatus | null,
+ featureFlags: FeatureFlagsSet
+): MaintenanceRegion | null {
+ const region = featureFlags[FEATURE_FLAGS.REDIRECT_SIGNUPS_TO_INSTANCE]
+ if (!preflight?.cloud || typeof region !== 'string') {
+ return null
+ }
+ return (MAINTENANCE_REGIONS as readonly string[]).includes(region) ? (region as MaintenanceRegion) : null
+}
+
+/**
+ * Where to send a signup on this instance while the other region takes all signups, or null to stay.
+ * The `email` carries over, so the person does not type it again on the other instance. A pending
+ * OAuth connection always stays, because its client is registered in this region.
+ */
+export function maintenanceSignupRedirectUrl(
+ preflight: PreflightStatus | null,
+ featureFlags: FeatureFlagsSet,
+ email?: string
+): string | null {
+ if (readPendingOAuthConnection()) {
+ return null
+ }
+ const region = maintenanceSignupRegion(preflight, featureFlags)
+ // KLUDGE: the backend can technically return null, and we don't want to redirect to the app
+ // unless the preflight region is valid
+ const currentRegion = preflight?.region?.toLowerCase()
+ if (!region || !currentRegion || !(MAINTENANCE_REGIONS as readonly string[]).includes(currentRegion)) {
+ return null
+ }
+ if (region === currentRegion) {
+ return null
+ }
+ const params = new URLSearchParams({ maintenanceRedirect: 'true' })
+ if (email) {
+ params.set('email', email)
+ }
+ return `https://${CLOUD_HOSTNAMES[region.toUpperCase() as keyof typeof CLOUD_HOSTNAMES]}${urls.signup()}?${params}`
+}
+
export const signupLogic = kea<signupLogicType>([
- path(['scenes', 'authentication', 'signupLogic']),
+ path(['scenes', 'authentication', 'auth', 'signupLogic']),
connect(() => ({
values: [preflightLogic, ['preflight'], featureFlagLogic, ['featureFlags']],
})),
actions(() => ({
setPanel: (panel: number) => ({ panel }),
- normalizeEmailWithDelay: (email: string) => ({ email }),
- setEmailNormalized: (wasNormalized: boolean) => ({ wasNormalized }),
+ // The signup precheck refuses aliases of an existing address and finds pending invites
+ precheckSignupEmail: (email: string) => ({ email }),
+ setSignupEmail: (email: string) => ({ email }),
+ // `isTaken`: the email, or an alias of it, already has an account, so the error offers login
+ setSignupEmailError: (error: string | null, isTaken: boolean = false) => ({ error, isTaken }),
+ finishSignupEmailPrecheck: true,
+ // Clears the password and passkey picked for the previous email
+ resetSignupCredentials: true,
// Passkey actions
registerPasskey: true,
setPasskeyRegistered: (registered: boolean) => ({ registered }),
@@ -325,12 +333,36 @@ export const signupLogic = kea<signupLogicType>([
0,
{
setPanel: (_, { panel }) => panel,
+ // Set here rather than in a listener, so the panel never reads 0 between the two
+ dismissPendingInvite: () => 1,
},
],
- emailWasNormalized: [
+ signupEmail: [
+ '',
+ {
+ precheckSignupEmail: (_, { email }) => email,
+ setSignupEmail: (_, { email }) => email,
+ },
+ ],
+ signupEmailError: [
+ null as string | null,
+ {
+ precheckSignupEmail: () => null,
+ setSignupEmailError: (_, { error }) => error,
+ },
+ ],
+ signupEmailTaken: [
false,
{
- setEmailNormalized: (_, { wasNormalized }) => wasNormalized,
+ precheckSignupEmail: () => false,
+ setSignupEmailError: (_, { isTaken }) => isTaken,
+ },
+ ],
+ isSignupEmailChecking: [
+ false,
+ {
+ precheckSignupEmail: () => true,
+ finishSignupEmailPrecheck: () => false,
},
],
passkeyRegistered: [
@@ -402,66 +434,6 @@ export const signupLogic = kea<signupLogicType>([
],
})),
forms(({ actions, values }) => ({
- signupPanelEmail: {
- alwaysShowErrors: true,
- showErrorsOnTouch: true,
- defaults: {
- email: '',
- } as SignupPanelEmailForm,
- errors: ({ email }) => ({
- email: !email
- ? 'Please enter your email to continue'
- : !emailRegex.test(email)
- ? 'Please use a valid email address'
- : undefined,
- }),
- // kea-forms counts manual errors as validation errors and refuses to submit while any
- // are set, and it only clears them when the field is touched or the form is reset. So
- // the "account already exists" error from a previous attempt would block every later
- // submit, leaving the user stuck on the email panel with a different email typed in.
- preSubmit: () => {
- actions.setSignupPanelEmailManualErrors({})
- },
- submit: async ({ email }, breakpoint) => {
- breakpoint()
- actions.setPasskeyError(null)
- actions.setSignupPanelAuthManualErrors({})
- let precheckResponse: SignupEmailPrecheckResponse
- try {
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
- precheckResponse = await api.create<SignupEmailPrecheckResponse>('api/signup/precheck', {
- email,
- })
- } catch (e: any) {
- if (e?.status === 409 || e?.code === 'account_exists') {
- const errorMessage = e?.detail || 'There is already an account with this email address.'
- actions.setSignupPanelEmailManualErrors({
- email: errorMessage,
- })
- actions.setPanel(0)
- return
- }
- const fieldError = e?.data?.email
- const emailErrorMessage = fieldError
- ? Array.isArray(fieldError)
- ? String(fieldError[0])
- : String(fieldError)
- : e?.detail || 'Could not verify your email. Please try again.'
- actions.setSignupPanelEmailManualErrors({
- email: emailErrorMessage,
- })
- return
- }
- const pendingInvite = precheckResponse.pending_invite ?? null
- if (pendingInvite && (router.values.searchParams as Record<string, string>).skip_invite_check !== '1') {
- actions.setPendingInvite(pendingInvite)
- return
- }
- actions.setPendingInvite(null)
- // Demo is passwordless — skip the password/passkey panel straight to onboarding.
- actions.setPanel(values.preflight?.demo ? 2 : 1)
- },
- },
signupPanelAuth: {
alwaysShowErrors: true,
showErrorsOnTouch: true,
@@ -514,7 +486,7 @@ export const signupLogic = kea<signupLogicType>([
const nextUrl = getRelativeNextPath(new URLSearchParams(location.search).get('next'), location)
const signupData: Record<string, any> = {
- email: values.signupPanelEmail.email,
+ email: values.signupEmail,
...splitFullName(payload.name),
organization_name: payload.organization_name?.trim() || undefined,
role_at_organization: payload.role_at_organization,
@@ -568,10 +540,13 @@ export const signupLogic = kea<signupLogicType>([
// If the server returns an email validation error, send the user back to the
// email step so the error appears next to the field that caused it.
- const emailError = error.data?.email
+ // DRF sends `attr: 'email'`, and an older body shape keys the message by field
+ const emailError = error.attr === 'email' ? error.detail : error.data?.email
if (emailError) {
const message = Array.isArray(emailError) ? String(emailError[0]) : String(emailError)
- actions.setSignupPanelEmailManualErrors({ email: message })
+ // A passkey registered for this email would fail the next submit the same way
+ actions.resetSignupCredentials()
+ actions.setSignupEmailError(message, error.code === 'unique')
actions.setPanel(0)
return
}
@@ -625,24 +600,46 @@ export const signupLogic = kea<signupLogicType>([
return validatePassword(signupPanelAuth.password)
},
],
- emailCaseNotice: [
- (s) => [s.emailWasNormalized],
- (emailWasNormalized: boolean): string | undefined => {
- return emailWasNormalized ? '⚠ Your email was automatically converted to lowercase' : undefined
- },
- ],
- loginUrl: [
- () => [router.selectors.searchParams],
- (searchParams: Record<string, string>) => {
- const nextParam = getRelativeNextPath(searchParams['next'], location)
- return nextParam ? `/login?next=${encodeURIComponent(nextParam)}` : '/login'
- },
- ],
}),
listeners(({ actions, values }) => ({
- dismissPendingInvite: () => {
- // User chose to proceed with creating a new organization despite the pending invite.
- actions.setPanel(1)
+ precheckSignupEmail: async ({ email }, breakpoint) => {
+ actions.setPasskeyError(null)
+ actions.setSignupPanelAuthManualErrors({})
+ let precheckResponse: SignupEmailPrecheckResponse
+ try {
+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
+ precheckResponse = await api.create<SignupEmailPrecheckResponse>('api/signup/precheck', { email })
+ } catch (e: any) {
+ breakpoint()
+ actions.finishSignupEmailPrecheck()
+ if (e?.status === 409 || e?.code === 'account_exists') {
+ actions.setSignupEmailError(
+ e?.detail || 'There is already an account with this email address.',
+ true
+ )
+ actions.setPanel(0)
+ return
+ }
+ const fieldError = e?.data?.email
+ actions.setSignupEmailError(
+ fieldError
+ ? Array.isArray(fieldError)
+ ? String(fieldError[0])
+ : String(fieldError)
+ : e?.detail || 'Could not verify your email. Please try again.'
+ )
+ return
+ }
+ breakpoint()
+ actions.finishSignupEmailPrecheck()
+ const pendingInvite = precheckResponse.pending_invite ?? null
+ if (pendingInvite && (router.values.searchParams as Record<string, string>).skip_invite_check !== '1') {
+ actions.setPendingInvite(pendingInvite)
+ return
+ }
+ actions.setPendingInvite(null)
+ // Demo is passwordless — skip the password/passkey panel straight to onboarding.
+ actions.setPanel(values.preflight?.demo ? 2 : 1)
},
resendPendingInvite: async ({ email }, breakpoint) => {
actions.setPendingInviteResending(true)
@@ -657,20 +654,10 @@ export const signupLogic = kea<signupLogicType>([
actions.setPendingInviteResending(false)
}
},
- normalizeEmailWithDelay: async ({ email }, breakpoint) => {
- await breakpoint(500)
-
- const hasUppercase = /[A-Z]/.test(email)
- if (hasUppercase) {
- actions.setSignupPanelEmailValue('email', email.toLowerCase())
- actions.setEmailNormalized(true)
- }
- },
- setSignupPanelEmailValue: ({ name, value }) => {
- if (name.toString() === 'email' && typeof value === 'string') {
- actions.setEmailNormalized(false)
- actions.normalizeEmailWithDelay(value)
- }
+ resetSignupCredentials: () => {
+ actions.setPasskeyRegistered(false)
+ actions.setPasskeyError(null)
+ actions.resetSignupPanelAuth()
},
setPasskeyRegistered: ({ registered }) => {
if (registered) {
@@ -684,7 +671,7 @@ export const signupLogic = kea<signupLogicType>([
}
},
registerPasskey: async () => {
- const email = values.signupPanelEmail.email
+ const email = values.signupEmail
if (!email) {
actions.setPasskeyError('Email is required')
return
@@ -738,47 +725,28 @@ export const signupLogic = kea<signupLogicType>([
})),
urlToAction(({ actions, values }) => ({
'/signup': (_, { email, maintenanceRedirect }) => {
- if (values.preflight?.cloud) {
- // Redirect to a different region if we are doing maintenance on one of them
- const regionOverrideFlag = values.featureFlags[FEATURE_FLAGS.REDIRECT_SIGNUPS_TO_INSTANCE]
- const regionsAllowList = ['eu', 'us']
- const isRegionOverrideValid =
- typeof regionOverrideFlag === 'string' && regionsAllowList.includes(regionOverrideFlag)
- // KLUDGE: the backend can technically return null
- // and, we don't want to redirect to the app unless the preflight region is valid
- const isPreflightRegionValid =
- values.preflight?.region && regionsAllowList.includes(values.preflight?.region)
-
- if (
- isRegionOverrideValid &&
- isPreflightRegionValid &&
- regionOverrideFlag !== values.preflight?.region?.toLowerCase()
- ) {
- window.location.href = `https://${
- CLOUD_HOSTNAMES[regionOverrideFlag.toUpperCase() as keyof typeof CLOUD_HOSTNAMES]
- }${urls.signup()}?maintenanceRedirect=true`
- }
- if (maintenanceRedirect && isRegionOverrideValid) {
- lemonToast.info(
- `You've been redirected to signup on our ${regionOverrideFlag.toUpperCase()} instance while we perform maintenance on our other instance.`
- )
- }
+ const redirectUrl = maintenanceSignupRedirectUrl(values.preflight, values.featureFlags, email)
+ if (redirectUrl) {
+ window.location.href = redirectUrl
}
- if (email) {
- if (values.preflight?.demo) {
- // In demo mode no password is needed, so we can log in right away
- // This allows us to give a quick login link in the `generate_demo_data` command
- // X and Y are placeholders, irrelevant because the account should already exists
- actions.setSignupPanelEmailValues({ email })
- actions.setSignupPanelOnboardingValues({
- name: 'X',
- organization_name: 'Y',
- role_at_organization: 'other',
- })
- actions.submitSignupPanelOnboarding()
- } else {
- actions.setSignupPanelEmailValue('email', email)
- }
+ const region = maintenanceSignupRegion(values.preflight, values.featureFlags)
+ if (maintenanceRedirect && region) {
+ lemonToast.info(
+ `You've been redirected to signup on our ${region.toUpperCase()} instance while we perform maintenance on our other instance.`
+ )
+ }
+ // Outside demo mode, `authLogic` puts `?email=` into the shared email field
+ if (email && values.preflight?.demo) {
+ // In demo mode no password is needed, so we can log in right away
+ // This allows us to give a quick login link in the `generate_demo_data` command
+ // X and Y are placeholders, irrelevant because the account should already exists
+ actions.setSignupEmail(email)
+ actions.setSignupPanelOnboardingValues({
+ name: 'X',
+ organization_name: 'Y',
+ role_at_organization: 'other',
+ })
+ actions.submitSignupPanelOnboarding()
}
},
})),
diff --git a/frontend/src/scenes/authentication/auth/steps/EmailStep.tsx b/frontend/src/scenes/authentication/auth/steps/EmailStep.tsx
new file mode 100644
index 000000000000..92afb9522114
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/steps/EmailStep.tsx
@@ -0,0 +1,166 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useState } from 'react'
+
+import { SocialLoginButtons } from 'lib/components/SocialLoginButton/SocialLoginButton'
+import { usePrevious } from 'lib/hooks/usePrevious'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
+import { Link } from 'lib/lemon-ui/Link'
+import { isWebKitBrowser } from 'lib/utils/dom'
+import { isEmail } from 'lib/utils/url'
+import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'
+import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'
+import { AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
+import { RegionField } from 'scenes/authentication/shared/authScene/RegionField'
+import { useLastLoginMethod } from 'scenes/authentication/shared/lastLoginMethod'
+import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+
+import { authLogic } from '../authLogic'
+import { ConnectTitle } from '../components/ConnectTitle'
+import { HighlightedName } from '../components/HighlightedName'
+import { LoginErrorBanner } from '../components/LoginErrorBanner'
+import { SessionRiskBanner } from '../components/SessionRiskBanner'
+import { loginLogic } from '../loginLogic'
+import { signupLogic } from '../signupLogic'
+
+function EmailStepTitle(): JSX.Element {
+ const { entry } = useValues(authLogic)
+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)
+ const isReturning = useLastLoginMethod() !== null
+
+ if (pendingConnection) {
+ return (
+ <AuthCardTitle
+ title={<ConnectTitle lead="Log in or sign up to connect" clientName={pendingConnection.clientName} />}
+ sub={`${pendingConnection.clientName} saved you a seat.`}
+ />
+ )
+ }
+ if (entry === 'signup') {
+ return <AuthCardTitle title="Get started" sub="Make your product self-driving." />
+ }
+ return (
+ <AuthCardTitle
+ title={
+ <>
+ <span>{isReturning ? 'Log in to ' : 'Log in or sign up to '}</span>
+ <HighlightedName>@PostHog</HighlightedName>
+ </>
+ }
+ sub={isReturning ? "Welcome back. Let's go ship something." : 'Hedgehogs of all kinds welcome.'}
+ />
+ )
+}
+
+export function EmailStep(): JSX.Element {
+ const { login, precheckResponse } = useValues(loginLogic)
+ const { setLoginValue, precheck } = useActions(loginLogic)
+ const { entry, emailError, isEmailSubmitting } = useValues(authLogic)
+ const { continueWithEmail, chooseAccountPath } = useActions(authLogic)
+ const { signupEmailTaken } = useValues(signupLogic)
+ const { preflight } = useValues(preflightLogic)
+ const lastLoginMethod = useLastLoginMethod()
+ const prevEmail = usePrevious(login.email)
+ const [showJoinOrg, setShowJoinOrg] = useState(false)
+
+ // An autofilled address is prechecked at once, so a passkey prompt can open before Continue
+ useEffect(() => {
+ const charDelta = login.email.length - (prevEmail?.length ?? 0)
+ const isAutofill = charDelta > 1
+
+ if (isAutofill && isEmail(login.email, { requireTLD: true }) && precheckResponse.status === 'pending') {
+ precheck({ email: login.email })
+ }
+ }, [login.email, prevEmail, precheckResponse.status, precheck])
+
+ return (
+ <AuthSceneCard>
+ <EmailStepTitle />
+ <SessionRiskBanner className="mb-4" />
+ <LoginErrorBanner />
+ <form
+ className="flex flex-col gap-4"
+ noValidate
+ onSubmit={(e) => {
+ e.preventDefault()
+ continueWithEmail()
+ }}
+ >
+ <RegionField />
+ <LemonField.Pure label="Email" htmlFor="auth-email" error={emailError}>
+ <LemonInput
+ id="auth-email"
+ className="ph-ignore-input"
+ // pinned: Playwright and autocapture select these per entry URL
+ data-attr={entry === 'signup' ? 'signup-email' : 'login-email'}
+ type="email"
+ autoFocus
+ placeholder="[email protected]"
+ // The `webauthn` token enables passkey autofill (conditional UI),
+ // which we only offer on WebKit; elsewhere the auto-modal handles passkeys.
+ autoComplete={isWebKitBrowser() ? 'username webauthn' : 'username'}
+ value={login.email}
+ onChange={(value) => setLoginValue('email', value)}
+ status={emailError ? 'danger' : 'default'}
+ fullWidth
+ />
+ </LemonField.Pure>
+ {signupEmailTaken && (
+ <p className="-mt-2 mb-0 text-sm text-secondary">
+ <Link
+ onClick={() => chooseAccountPath('login', true)}
+ data-attr="auth-email-taken-login"
+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
+ >
+ Log in instead
+ </Link>
+ <span>
+ . Signed up with a version of this address with dots or a +tag? Log in with that one.
+ </span>
+ </p>
+ )}
+ <LemonButton
+ type="primary"
+ size="large"
+ center
+ fullWidth
+ htmlType="submit"
+ // pinned: `signup-start` is the signup funnel's existing first-step attribute
+ data-attr={entry === 'signup' ? 'signup-start' : 'login-email-continue'}
+ loading={isEmailSubmitting}
+ >
+ Continue
+ </LemonButton>
+ </form>
+ {!preflight?.demo && (
+ <SocialLoginButtons
+ topDivider
+ caption="or continue with"
+ captionLocation="top"
+ lastUsedProvider={lastLoginMethod}
+ showPasskey={entry === 'login'}
+ />
+ )}
+ {entry === 'signup' && !preflight?.demo && (
+ <div className="mt-4 text-center">
+ <button
+ type="button"
+ data-attr="signup-join-existing-org"
+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-secondary text-xs"
+ onClick={() => setShowJoinOrg((v) => !v)}
+ >
+ Trying to join an existing organization?
+ </button>
+ {showJoinOrg && (
+ <AuthBanner variant="note" className="mt-3">
+ You'll need your invite link. When a teammate invites you, we email you a personal link.
+ Didn't get one? Check spam, or ask them to resend it from their members settings.
+ </AuthBanner>
+ )}
+ </div>
+ )}
+ </AuthSceneCard>
+ )
+}
diff --git a/frontend/src/scenes/authentication/auth/steps/LoginCodeStep.tsx b/frontend/src/scenes/authentication/auth/steps/LoginCodeStep.tsx
new file mode 100644
index 000000000000..79dbb8b0e28b
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/steps/LoginCodeStep.tsx
@@ -0,0 +1,118 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass'
+import { IconCheckCircle } from '@posthog/icons'
+
+import { pngHoggie } from 'lib/brand/hoggies'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { Link } from 'lib/lemon-ui/Link'
+import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'
+import { AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
+import { isValidVerificationCode, normalizeVerificationCode } from 'scenes/authentication/shared/verificationCode'
+import { VerificationCodeInput } from 'scenes/authentication/shared/VerificationCodeInput'
+
+import { LoginErrorBanner } from '../components/LoginErrorBanner'
+import { loginLogic } from '../loginLogic'
+
+const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)
+
+export function LoginCodeStep(): JSX.Element {
+ const { exitCodeVerification, resendCodeBasedVerification, submitCodeVerification } = useActions(loginLogic)
+ const {
+ codeVerificationEmail,
+ resendResponseLoading,
+ resendResponse,
+ isCodeVerificationSubmitting,
+ codeVerification,
+ } = useValues(loginLogic)
+
+ return (
+ <AuthSceneCard>
+ <HedgehogMagnifyingGlass className="block w-auto mx-auto mb-3 h-28" />
+ <AuthCardTitle
+ className="mb-2"
+ title="Check your inbox"
+ sub={
+ <>
+ For your security, we've emailed a 6-digit verification code to{' '}
+ <strong>{codeVerificationEmail}</strong>.
+ </>
+ }
+ />
+ <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>
+ <LoginErrorBanner />
+ <Form
+ 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"
+ 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"
+ disabled={isCodeVerificationSubmitting}
+ onComplete={() => {
+ if (!isCodeVerificationSubmitting) {
+ submitCodeVerification()
+ }
+ }}
+ />
+ </LemonField>
+ <LemonButton
+ type="primary"
+ status="alt"
+ htmlType="submit"
+ data-attr="code-verification-submit"
+ fullWidth
+ 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">
+ <Link
+ onClick={() => exitCodeVerification()}
+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-secondary"
+ >
+ Back to login
+ </Link>
+ </div>
+ </Form>
+ </AuthSceneCard>
+ )
+}
diff --git a/frontend/src/scenes/authentication/auth/steps/LoginStep.tsx b/frontend/src/scenes/authentication/auth/steps/LoginStep.tsx
new file mode 100644
index 000000000000..e2f2638b4c22
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/steps/LoginStep.tsx
@@ -0,0 +1,242 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { SocialLoginButtons, SSOEnforcedLoginButton } from 'lib/components/SocialLoginButton/SocialLoginButton'
+import { SSO_PROVIDER_NAMES } from 'lib/constants'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
+import { Link } from 'lib/lemon-ui/Link'
+import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'
+import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'
+import { AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
+import { useLastLoginMethod } from 'scenes/authentication/shared/lastLoginMethod'
+import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'
+import { urls } from 'scenes/urls'
+
+import { authLogic } from '../authLogic'
+import { ConnectTitle } from '../components/ConnectTitle'
+import { LoginErrorBanner } from '../components/LoginErrorBanner'
+import { OtherRegionNotice } from '../components/OtherRegionNotice'
+import { UseDifferentEmailLink } from '../components/UseDifferentEmailLink'
+import { PrecheckResponseType, loginLogic } from '../loginLogic'
+
+function hasSingleSignOn(precheck: PrecheckResponseType): boolean {
+ return !!precheck.sso_enforcement || precheck.saml_available || !!precheck.oidc_available
+}
+
+function LoginStepTitle(): JSX.Element {
+ const { login, precheckResponse } = useValues(loginLogic)
+ const { entry, accountExists } = useValues(authLogic)
+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)
+ const email = <span className="AuthScene__mono">{login.email}</span>
+
+ const greeting =
+ accountExists === false ? (
+ <>
+ <span>Nice to meet you,</span> {email}
+ <span>.</span>
+ </>
+ ) : accountExists === null ? (
+ <>
+ <span>Hi,</span> {email}
+ <span>.</span>
+ </>
+ ) : entry === 'signup' ? (
+ <>
+ <span>Plot twist:</span> {email} <span>already has an account.</span>
+ </>
+ ) : (
+ <>
+ <span>Good to see you,</span> {email}
+ <span>.</span>
+ </>
+ )
+ if (pendingConnection) {
+ return (
+ <AuthCardTitle
+ title={<ConnectTitle lead="Log in to connect" clientName={pendingConnection.clientName} />}
+ sub={greeting}
+ />
+ )
+ }
+ if (accountExists === false) {
+ return (
+ <AuthCardTitle
+ title={hasSingleSignOn(precheckResponse) ? 'Your team uses single sign-on' : 'No account here yet'}
+ sub={greeting}
+ />
+ )
+ }
+ return <AuthCardTitle title={accountExists === null ? 'Log in' : 'Welcome back'} sub={greeting} />
+}
+
+export function LoginStep(): JSX.Element {
+ const { chooseAccountPath } = useActions(authLogic)
+ const { canSignUpWithEmail, accountExists } = useValues(authLogic)
+ const {
+ precheckResponse,
+ login,
+ isLoginSubmitting,
+ generalError,
+ isPasswordLoginUnavailable,
+ hasNoConfiguredLoginMethod,
+ restrictToProviders,
+ autoRedirectingToProvider,
+ } = useValues(loginLogic)
+ const lastLoginMethod = useLastLoginMethod()
+
+ // A new person reaches this step on a SAML or OIDC domain, where the IdP creates the account, or
+ // where nobody may sign up with email, such as a self-hosted instance with signups off
+ const isNewAccount = accountExists === false
+ // The precheck failed, so this may be a new person. Signup still refuses an email that has an account.
+ const isAccountUnknown = accountExists === null
+ const isPasswordHidden = !!precheckResponse.sso_enforcement || isPasswordLoginUnavailable || isNewAccount
+
+ return (
+ <AuthSceneCard footer={<UseDifferentEmailLink />}>
+ <LoginStepTitle />
+ <LoginErrorBanner />
+ {generalError?.code === 'invalid_credentials' && (
+ <OtherRegionNotice email={login.email} reason="login_failed" />
+ )}
+ <Form logic={loginLogic} formKey="login" enableFormOnSubmit className="flex flex-col gap-4">
+ {/* Password managers pair the saved password with this username */}
+ <input type="email" name="email" autoComplete="username" value={login.email} readOnly hidden />
+ {!isPasswordHidden && (
+ <LemonField
+ name="password"
+ label={
+ <div className="flex items-baseline justify-between w-full">
+ <span>Password</span>
+ <Link
+ to={[urls.passwordReset(), { email: login.email }]}
+ data-attr="forgot-password"
+ className="text-xs font-semibold text-warning"
+ tabIndex={-1}
+ >
+ Forgot password?
+ </Link>
+ </div>
+ }
+ >
+ {({ value, onChange, error, id }) => (
+ <LemonInput
+ id={id}
+ className="ph-ignore-input"
+ data-attr="password"
+ type="password"
+ autoFocus
+ placeholder="••••••••••"
+ autoComplete="current-password"
+ value={value ?? ''}
+ onChange={onChange}
+ status={error ? 'danger' : 'default'}
+ fullWidth
+ />
+ )}
+ </LemonField>
+ )}
+ {isNewAccount && !hasSingleSignOn(precheckResponse) && (
+ <AuthBanner variant="note">
+ There's no account for this email. Ask your PostHog admin for an invite.
+ </AuthBanner>
+ )}
+ {hasNoConfiguredLoginMethod && (
+ <AuthBanner variant="warning">
+ <span>No sign-in method is set up for this account. Use</span>{' '}
+ <Link
+ to={[urls.passwordReset(), { email: login.email }]}
+ // Autocapture reports the click. Each reset entry point has its
+ // own `data-attr`, so one funnel can tell them apart.
+ data-attr="login-no-method-reset-password"
+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
+ >
+ Forgot password?
+ </Link>{' '}
+ <span>to set a password by email.</span>
+ </AuthBanner>
+ )}
+ {autoRedirectingToProvider && (
+ <p className="text-sm text-secondary text-center mb-0">
+ Redirecting to {SSO_PROVIDER_NAMES[autoRedirectingToProvider]}…
+ </p>
+ )}
+ {/* No password to submit means this button would do nothing */}
+ {!isPasswordHidden && (
+ <LemonButton
+ type="primary"
+ size="large"
+ center
+ fullWidth
+ htmlType="submit"
+ data-attr="password-login"
+ loading={isLoginSubmitting}
+ >
+ Log in
+ </LemonButton>
+ )}
+ {precheckResponse.sso_enforcement && (
+ <SSOEnforcedLoginButton
+ provider={precheckResponse.sso_enforcement}
+ email={login.email}
+ isLastUsed={lastLoginMethod === precheckResponse.sso_enforcement}
+ />
+ )}
+ {precheckResponse.saml_available && !precheckResponse.sso_enforcement && (
+ <SSOEnforcedLoginButton
+ provider="saml"
+ email={login.email}
+ isLastUsed={lastLoginMethod === 'saml'}
+ />
+ )}
+ {precheckResponse.oidc_available && !precheckResponse.sso_enforcement && (
+ <SSOEnforcedLoginButton
+ provider="oidc"
+ email={login.email}
+ isLastUsed={lastLoginMethod === 'oidc'}
+ />
+ )}
+ </Form>
+ {isAccountUnknown && canSignUpWithEmail && (
+ <p className="mt-4 mb-0 text-sm text-secondary text-center">
+ <span>New to PostHog?</span>{' '}
+ <Link
+ onClick={() => chooseAccountPath('signup', null)}
+ data-attr="auth-unknown-account-signup"
+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
+ >
+ Create an account
+ </Link>
+ </p>
+ )}
+ {isNewAccount && canSignUpWithEmail && (
+ <p className="mt-4 mb-0 text-sm text-secondary text-center">
+ <Link
+ onClick={() => chooseAccountPath('signup', false)}
+ data-attr="auth-sso-domain-signup-with-email"
+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
+ >
+ Sign up with email instead
+ </Link>
+ </p>
+ )}
+ {/* Normally SAML replaces this row, but when the account has no password we need to
+ show whatever it does have. */}
+ {!isNewAccount &&
+ !precheckResponse.sso_enforcement &&
+ (!precheckResponse.saml_available || isPasswordLoginUnavailable) && (
+ <SocialLoginButtons
+ topDivider
+ caption={isPasswordLoginUnavailable ? 'Log in with' : 'Or log in with'}
+ captionLocation="top"
+ lastUsedProvider={lastLoginMethod}
+ restrictToProviders={restrictToProviders}
+ // Once we know the account's methods, only offer a passkey if it actually has
+ // one — otherwise this is the same dead button we're removing.
+ showPasskey={!isPasswordLoginUnavailable || !!precheckResponse.webauthn_credentials?.length}
+ />
+ )}
+ </AuthSceneCard>
+ )
+}
diff --git a/frontend/src/scenes/authentication/auth/steps/PendingInviteStep.tsx b/frontend/src/scenes/authentication/auth/steps/PendingInviteStep.tsx
new file mode 100644
index 000000000000..2e007ff3791b
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/steps/PendingInviteStep.tsx
@@ -0,0 +1,59 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'
+import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'
+import { AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
+
+import { UseDifferentEmailLink } from '../components/UseDifferentEmailLink'
+import { signupLogic } from '../signupLogic'
+
+export function PendingInviteStep(): JSX.Element {
+ const { signupEmail, pendingInvite, pendingInviteResent, isPendingInviteResending } = useValues(signupLogic)
+ const { resendPendingInvite, dismissPendingInvite } = useActions(signupLogic)
+ const org = pendingInvite?.organization_name ?? 'your team'
+
+ return (
+ <AuthSceneCard footer={<UseDifferentEmailLink />}>
+ <AuthCardTitle
+ title="You've already been invited"
+ sub={
+ <span>
+ <b className="text-primary">{org}</b> <span>invited</span>{' '}
+ <span className="AuthScene__mono">{signupEmail}</span>{' '}
+ <span>to join them on PostHog. The invite link is in your inbox.</span>
+ </span>
+ }
+ className="mb-5"
+ />
+ {pendingInviteResent ? (
+ <AuthBanner variant="success">
+ {`Sent. Look for an email from ${org}. The link inside takes you straight in.`}
+ </AuthBanner>
+ ) : (
+ <div className="flex flex-col gap-2.5">
+ <LemonButton
+ type="primary"
+ size="large"
+ center
+ fullWidth
+ data-attr="pending-invite-resend"
+ loading={isPendingInviteResending}
+ onClick={() => resendPendingInvite(signupEmail)}
+ >
+ Resend invite email
+ </LemonButton>
+ <LemonButton
+ size="large"
+ center
+ fullWidth
+ data-attr="pending-invite-create-own-org"
+ onClick={() => dismissPendingInvite()}
+ >
+ I'd rather create my own organization
+ </LemonButton>
+ </div>
+ )}
+ </AuthSceneCard>
+ )
+}
diff --git a/frontend/src/scenes/authentication/auth/steps/SignupCredentialsStep.tsx b/frontend/src/scenes/authentication/auth/steps/SignupCredentialsStep.tsx
new file mode 100644
index 000000000000..1ee2f7ec1ed5
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/steps/SignupCredentialsStep.tsx
@@ -0,0 +1,149 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import PasswordStrength from 'lib/components/PasswordStrength'
+import passkeyLogo from 'lib/components/SocialLoginButton/passkey.svg'
+import { SocialLoginButtons } from 'lib/components/SocialLoginButton/SocialLoginButton'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
+import { Link } from 'lib/lemon-ui/Link'
+import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'
+import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'
+import { AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
+import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'
+
+import { ConnectTitle } from '../components/ConnectTitle'
+import { OtherRegionNotice } from '../components/OtherRegionNotice'
+import { UseDifferentEmailLink } from '../components/UseDifferentEmailLink'
+import { signupLogic } from '../signupLogic'
+
+export function SignupCredentialsStep(): JSX.Element {
+ const {
+ signupEmail,
+ isSignupPanelAuthSubmitting,
+ validatedPassword,
+ passkeyRegistered,
+ isPasskeyRegistering,
+ passkeyError,
+ } = useValues(signupLogic)
+ const { registerPasskey } = useActions(signupLogic)
+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)
+
+ const footer = (
+ <>
+ <p className="AuthScene__terms mt-5 mb-0 text-xs leading-relaxed text-tertiary text-center">
+ <span>By creating an account, you agree to our</span>{' '}
+ <Link to="https://posthog.com/terms" target="_blank">
+ Terms of Service ↗
+ </Link>{' '}
+ <span>and</span>{' '}
+ <Link to="https://posthog.com/privacy" target="_blank">
+ Privacy Policy ↗
+ </Link>
+ <span>.</span>
+ </p>
+ <UseDifferentEmailLink />
+ </>
+ )
+
+ const greeting = (
+ <>
+ <span>Nice to meet you,</span> <span className="AuthScene__mono">{signupEmail}</span>
+ <span>.</span>
+ </>
+ )
+
+ return (
+ <AuthSceneCard footer={footer}>
+ <AuthCardTitle
+ title={
+ pendingConnection ? (
+ <ConnectTitle lead="Create your account to connect" clientName={pendingConnection.clientName} />
+ ) : (
+ 'Create your account'
+ )
+ }
+ sub={greeting}
+ />
+ {passkeyError && (
+ <AuthBanner variant="danger" className="mb-4">
+ {passkeyError}
+ </AuthBanner>
+ )}
+ {passkeyRegistered ? (
+ <AuthBanner variant="success">Passkey registered. Continue below.</AuthBanner>
+ ) : (
+ <LemonButton
+ type="secondary"
+ size="large"
+ fullWidth
+ icon={<img src={passkeyLogo} alt="Passkey" className="object-contain w-7 h-7" />}
+ onClick={registerPasskey}
+ loading={isPasskeyRegistering}
+ disabled={isPasskeyRegistering}
+ data-attr="signup-passkey"
+ center
+ >
+ Sign up with a passkey
+ </LemonButton>
+ )}
+ {!passkeyRegistered && (
+ <div className="my-4 flex gap-3 items-center">
+ <span className="flex-1 h-px bg-[#e0e1d9]" />
+ <span className="text-xs text-secondary whitespace-nowrap">or use a password</span>
+ <span className="flex-1 h-px bg-[#e0e1d9]" />
+ </div>
+ )}
+ <Form logic={signupLogic} formKey="signupPanelAuth" enableFormOnSubmit className="flex flex-col gap-4">
+ {/* Password managers save the new password under this username */}
+ <input type="email" name="email" autoComplete="username" value={signupEmail} readOnly hidden />
+ {!passkeyRegistered && (
+ <LemonField
+ name="password"
+ label={
+ <div className="flex items-baseline justify-between w-full">
+ <span>Password</span>
+ <PasswordStrength validatedPassword={validatedPassword} />
+ </div>
+ }
+ >
+ {({ value, onChange, error, id }) => (
+ <LemonInput
+ id={id}
+ className="ph-ignore-input"
+ data-attr="password"
+ type="password"
+ autoFocus
+ autoComplete="new-password"
+ placeholder="••••••••••"
+ value={value ?? ''}
+ onChange={onChange}
+ status={error ? 'danger' : 'default'}
+ fullWidth
+ />
+ )}
+ </LemonField>
+ )}
+ <LemonButton
+ type="primary"
+ size="large"
+ center
+ fullWidth
+ htmlType="submit"
+ data-attr="signup-auth-continue"
+ loading={isSignupPanelAuthSubmitting}
+ disabledReason={
+ !passkeyRegistered && validatedPassword.feedback ? validatedPassword.feedback : undefined
+ }
+ >
+ Create account
+ </LemonButton>
+ <OtherRegionNotice email={signupEmail} reason="no_account" />
+ </Form>
+ {/* A verified company domain with auto-join adds people who sign in with Google, GitHub or
+ GitLab to their team's organization. An email signup creates a new organization instead. */}
+ <SocialLoginButtons topDivider caption="or sign up with" captionLocation="top" />
+ </AuthSceneCard>
+ )
+}
diff --git a/frontend/src/scenes/authentication/auth/steps/SignupProfileStep.tsx b/frontend/src/scenes/authentication/auth/steps/SignupProfileStep.tsx
new file mode 100644
index 000000000000..ff5874e39ad9
--- /dev/null
+++ b/frontend/src/scenes/authentication/auth/steps/SignupProfileStep.tsx
@@ -0,0 +1,163 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import SignupReferralSource from 'lib/components/SignupReferralSource'
+import SignupRoleSelect from 'lib/components/SignupRoleSelect'
+import { supportLogic } from 'lib/components/Support/supportLogic'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
+import { Link } from 'lib/lemon-ui/Link'
+import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'
+import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'
+import { AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
+import { TurnstileChallenge } from 'scenes/authentication/shared/TurnstileChallenge'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+
+import { signupLogic } from '../signupLogic'
+
+export function SignupProfileStep(): JSX.Element {
+ const {
+ isSignupPanelOnboardingSubmitting,
+ signupPanelOnboardingManualErrors,
+ challengeRequired,
+ turnstileSiteKey,
+ turnstileToken,
+ signupEmail,
+ } = useValues(signupLogic)
+ const { preflight } = useValues(preflightLogic)
+ const { setTurnstileToken, setPanel } = useActions(signupLogic)
+ const { openSupportForm } = useActions(supportLogic)
+
+ const submitLabel = !preflight?.demo
+ ? 'Create account'
+ : !isSignupPanelOnboardingSubmitting
+ ? 'Enter the demo environment'
+ : 'Preparing demo data…'
+
+ const footer = (
+ <>
+ <p className="AuthScene__terms mt-5 mb-0 text-xs leading-relaxed text-tertiary text-center">
+ <span>
+ By {preflight?.demo ? 'entering the demo environment' : 'creating an account'}, you agree to our
+ </span>{' '}
+ <Link to="https://posthog.com/terms" target="_blank">
+ Terms of Service ↗
+ </Link>{' '}
+ <span>and</span>{' '}
+ <Link to="https://posthog.com/privacy" target="_blank">
+ Privacy Policy ↗
+ </Link>
+ <span>.</span>
+ </p>
+ {!preflight?.demo && (
+ <p className="mt-5 mb-0 text-sm text-secondary text-center">
+ <Link
+ onClick={() => setPanel(1)}
+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
+ >
+ ← or go back
+ </Link>
+ </p>
+ )}
+ </>
+ )
+
+ return (
+ <AuthSceneCard footer={footer}>
+ <AuthCardTitle
+ title="Tell us about yourself"
+ sub={
+ <span>
+ <span>Setting up the account for</span> <span className="AuthScene__mono">{signupEmail}</span>
+ </span>
+ }
+ />
+ {signupPanelOnboardingManualErrors?.generic && (
+ <AuthBanner variant="danger" className="mb-4">
+ <span>{signupPanelOnboardingManualErrors.generic.detail || 'Could not complete your signup.'}</span>
+ {preflight?.cloud && (
+ <>
+ {' '}
+ <Link
+ // The login banner uses `login-error-contact-support`. A shared
+ // attribute would mix both pages into one autocapture funnel arm.
+ data-attr="signup-error-contact-support"
+ onClick={(e) => {
+ e.preventDefault()
+ openSupportForm({
+ kind: 'support',
+ email: signupEmail,
+ })
+ }}
+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
+ >
+ Contact us
+ </Link>{' '}
+ <span>to resolve this.</span>
+ </>
+ )}
+ </AuthBanner>
+ )}
+ <Form
+ logic={signupLogic}
+ formKey="signupPanelOnboarding"
+ enableFormOnSubmit
+ className="flex flex-col gap-4"
+ >
+ <LemonField name="name" label="Your name">
+ {({ value, onChange, error, id }) => (
+ <LemonInput
+ id={id}
+ className="ph-ignore-input"
+ data-attr="signup-name"
+ autoFocus
+ placeholder="Jane Doe"
+ autoComplete="name"
+ value={value ?? ''}
+ onChange={onChange}
+ status={error ? 'danger' : 'default'}
+ fullWidth
+ />
+ )}
+ </LemonField>
+ <LemonField name="organization_name" label="Organization name">
+ {({ value, onChange, error, id }) => (
+ <LemonInput
+ id={id}
+ className="ph-ignore-input"
+ data-attr="signup-organization-name"
+ placeholder="Hogflix Movies"
+ value={value ?? ''}
+ onChange={onChange}
+ status={error ? 'danger' : 'default'}
+ fullWidth
+ />
+ )}
+ </LemonField>
+ <SignupRoleSelect />
+ <SignupReferralSource disabled={isSignupPanelOnboardingSubmitting} />
+ {challengeRequired && turnstileSiteKey ? (
+ <TurnstileChallenge
+ siteKey={turnstileSiteKey}
+ onSuccess={setTurnstileToken}
+ tokenReceived={!!turnstileToken}
+ email={signupEmail}
+ />
+ ) : (
+ <LemonButton
+ type="primary"
+ size="large"
+ center
+ fullWidth
+ htmlType="submit"
+ data-attr="signup-submit"
+ loading={isSignupPanelOnboardingSubmitting}
+ >
+ {submitLabel}
+ </LemonButton>
+ )}
+ </Form>
+ </AuthSceneCard>
+ )
+}
diff --git a/frontend/src/scenes/authentication/invite-signup/InviteSignupForm.tsx b/frontend/src/scenes/authentication/invite-signup/InviteSignupForm.tsx
index ea3d4e7a63c8..ebb15d40ff71 100644
--- a/frontend/src/scenes/authentication/invite-signup/InviteSignupForm.tsx
+++ b/frontend/src/scenes/authentication/invite-signup/InviteSignupForm.tsx
@@ -19,11 +19,11 @@ import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
import { Link } from 'lib/lemon-ui/Link'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
-import { loginLogic } from 'scenes/authentication/login/loginLogic'
+import { loginLogic } from 'scenes/authentication/auth/loginLogic'
import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'
import { AuthScene, AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
import { OrgTile } from 'scenes/authentication/shared/authScene/OrgTile'
-import { TurnstileChallenge } from 'scenes/authentication/signup/signupForm/TurnstileChallenge'
+import { TurnstileChallenge } from 'scenes/authentication/shared/TurnstileChallenge'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
diff --git a/frontend/src/scenes/authentication/login-2fa/login2FALogic.ts b/frontend/src/scenes/authentication/login-2fa/login2FALogic.ts
index ed75078a25cd..68921b0b95b7 100644
--- a/frontend/src/scenes/authentication/login-2fa/login2FALogic.ts
+++ b/frontend/src/scenes/authentication/login-2fa/login2FALogic.ts
@@ -7,7 +7,7 @@ import { urlToAction } from 'kea-router'
import api, { ApiError } from 'lib/api'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { redirectAfterLogin } from 'scenes/authentication/login/loginLogic'
+import { redirectAfterLogin } from 'scenes/authentication/auth/loginLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { getPasskeyErrorMessage, isWebAuthnCancellation } from 'scenes/settings/user/passkeys/utils'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/authentication/login/Login.stories.tsx b/frontend/src/scenes/authentication/login/Login.stories.tsx
deleted file mode 100644
index a9452f968e31..000000000000
--- a/frontend/src/scenes/authentication/login/Login.stories.tsx
+++ /dev/null
@@ -1,173 +0,0 @@
-import { WEBSITE_REFERRER, setDocumentReferrer } from 'scenes/authentication/shared/authReferrer.mock'
-import { setLastLoginMethodCookie } from 'scenes/authentication/shared/lastLoginMethod.mock'
-import {
- PENDING_OAUTH_CONNECTION_FIXTURE,
- setPendingOAuthConnectionCookie,
-} from 'scenes/authentication/shared/pendingOAuthConnection.mock'
-
-import type { Meta, StoryFn } from '@storybook/react'
-import { useEffect } from 'react'
-
-import { useStorybookMocks } from '~/mocks/browser'
-import preflightJson from '~/mocks/fixtures/_preflight.json'
-
-import { arrivedFromWebsiteLogic } from '../shared/arrivedFromWebsiteLogic'
-import { Login } from './Login'
-import { loginLogic } from './loginLogic'
-
-type StoryArgs = {
- cloud: boolean
- region: 'US' | 'EU'
- googleOAuth: boolean
- github: boolean
- gitlab: boolean
- samlAvailable: boolean
- ssoEnforcement: 'none' | 'google-oauth2' | 'github' | 'gitlab' | 'saml'
- generalError: 'none' | 'invalid_credentials' | 'code_based_verification_sent'
- pendingOAuthConnection: boolean
- arrivedFromWebsite: boolean
- hasLoggedInBefore: boolean
-}
-
-const meta: Meta<StoryArgs> = {
- title: 'Scenes-Other/Login',
- tags: ['test-skip'],
- parameters: {
- layout: 'fullscreen',
- viewMode: 'story',
- },
- argTypes: {
- cloud: { control: 'boolean', name: 'Cloud' },
- region: { control: 'select', options: ['US', 'EU'], name: 'Region', if: { arg: 'cloud' } },
- googleOAuth: { control: 'boolean', name: 'Google OAuth' },
- github: { control: 'boolean', name: 'GitHub' },
- gitlab: { control: 'boolean', name: 'GitLab' },
- samlAvailable: { control: 'boolean', name: 'SAML available' },
- ssoEnforcement: {
- control: 'select',
- name: 'SSO enforcement',
- options: ['none', 'google-oauth2', 'github', 'gitlab', 'saml'],
- },
- generalError: {
- control: 'select',
- name: 'General error',
- options: ['none', 'invalid_credentials', 'code_based_verification_sent'],
- },
- pendingOAuthConnection: { control: 'boolean', name: 'Pending OAuth connection' },
- arrivedFromWebsite: { control: 'boolean', name: 'Arrived from posthog.com' },
- hasLoggedInBefore: { control: 'boolean', name: 'Has logged in before' },
- },
- args: {
- cloud: true,
- region: 'US',
- googleOAuth: true,
- github: true,
- gitlab: true,
- samlAvailable: false,
- ssoEnforcement: 'none',
- generalError: 'none',
- pendingOAuthConnection: false,
- arrivedFromWebsite: false,
- hasLoggedInBefore: true,
- },
-}
-export default meta
-
-const Template: StoryFn<StoryArgs> = ({
- cloud,
- region,
- googleOAuth,
- github,
- gitlab,
- samlAvailable,
- ssoEnforcement,
- generalError,
- pendingOAuthConnection,
- arrivedFromWebsite,
- hasLoggedInBefore,
-}) => {
- const enforcement = ssoEnforcement === 'none' ? null : ssoEnforcement
- // Set synchronously: the scene reads the cookie while it mounts during this same render.
- setPendingOAuthConnectionCookie(pendingOAuthConnection ? PENDING_OAUTH_CONNECTION_FIXTURE : null)
- setDocumentReferrer(arrivedFromWebsite ? WEBSITE_REFERRER : '')
- setLastLoginMethodCookie(hasLoggedInBefore ? 'password' : null)
-
- useStorybookMocks({
- get: {
- '/_preflight': {
- ...preflightJson,
- cloud,
- region: cloud ? region : undefined,
- realm: cloud ? 'cloud' : 'hosted-clickhouse',
- is_debug: cloud,
- can_create_org: cloud,
- available_social_auth_providers: {
- 'google-oauth2': googleOAuth,
- github,
- gitlab,
- saml: samlAvailable,
- },
- },
- },
- post: {
- '/api/login/precheck': { sso_enforcement: enforcement, saml_available: samlAvailable },
- },
- })
-
- useEffect(() => {
- arrivedFromWebsiteLogic.findMounted()?.actions.setArrivedFromWebsite(arrivedFromWebsite)
- }, [arrivedFromWebsite])
-
- useEffect(() => {
- if (enforcement) {
- loginLogic.actions.setLoginValue('email', '[email protected]')
- loginLogic.actions.precheck({ email: '[email protected]' })
- }
- }, [enforcement])
-
- useEffect(() => {
- if (generalError !== 'none') {
- const messages: Record<string, string> = {
- invalid_credentials: 'Invalid email or password.',
- code_based_verification_sent: 'Check your email to verify your account.',
- }
- loginLogic.actions.setGeneralError(generalError, messages[generalError] ?? '')
- } else {
- loginLogic.actions.clearGeneralError()
- }
- }, [generalError])
-
- return <Login key={String(hasLoggedInBefore)} />
-}
-
-export const Default: StoryFn<StoryArgs> = Template.bind({})
-
-export const SelfHosted: StoryFn<StoryArgs> = Template.bind({})
-SelfHosted.args = { cloud: false, googleOAuth: false, github: false, gitlab: false, samlAvailable: false }
-
-export const CloudEU: StoryFn<StoryArgs> = Template.bind({})
-CloudEU.args = { region: 'EU' }
-
-export const SSOEnforced: StoryFn<StoryArgs> = Template.bind({})
-SSOEnforced.args = { ssoEnforcement: 'google-oauth2' }
-
-export const SAMLAvailable: StoryFn<StoryArgs> = Template.bind({})
-SAMLAvailable.args = { samlAvailable: true }
-
-export const LoginError: StoryFn<StoryArgs> = Template.bind({})
-LoginError.args = { generalError: 'invalid_credentials' }
-
-export const PendingOAuthConnection: StoryFn<StoryArgs> = Template.bind({})
-PendingOAuthConnection.storyName = 'Pending OAuth connection'
-PendingOAuthConnection.args = { pendingOAuthConnection: true }
-
-export const EmailVerification: StoryFn<StoryArgs> = Template.bind({})
-EmailVerification.args = { generalError: 'code_based_verification_sent' }
-
-export const ArrivedFromWebsite: StoryFn<StoryArgs> = Template.bind({})
-ArrivedFromWebsite.storyName = 'Arrived from posthog.com'
-ArrivedFromWebsite.args = { arrivedFromWebsite: true }
-
-export const FirstLoginOnThisBrowser: StoryFn<StoryArgs> = Template.bind({})
-FirstLoginOnThisBrowser.storyName = 'First login on this browser'
-FirstLoginOnThisBrowser.args = { hasLoggedInBefore: false }
diff --git a/frontend/src/scenes/authentication/login/Login.tsx b/frontend/src/scenes/authentication/login/Login.tsx
deleted file mode 100644
index 676345d10b79..000000000000
--- a/frontend/src/scenes/authentication/login/Login.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import { useActions, useMountedLogic } from 'kea'
-import { useEffect } from 'react'
-
-import { loginTelemetryLogic } from 'scenes/authentication/shared/loginTelemetryLogic'
-import { passkeyLogic } from 'scenes/authentication/shared/passkeyLogic'
-import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'
-import { SceneExport } from 'scenes/sceneTypes'
-
-import { LoginForm } from './LoginForm'
-import { loginLogic } from './loginLogic'
-
-export const scene: SceneExport = {
- component: Login,
- logic: loginLogic,
-}
-
-export function Login(): JSX.Element {
- // Mounted here so the login funnel is only reported from the auth scenes
- useMountedLogic(loginTelemetryLogic)
- // Mounted at the scene root so the cookie is read once, not on every form state change
- useMountedLogic(pendingOAuthConnectionLogic)
- const { startConditionalPasskeyLogin } = useActions(passkeyLogic)
-
- // WebKit (Safari/iOS) can't open the passkey modal without a user gesture, so we show
- // passkeys via the email field's autofill instead. Other browsers keep the auto-modal.
- useEffect(() => {
- startConditionalPasskeyLogin()
- }, [startConditionalPasskeyLogin])
-
- return <LoginForm />
-}
diff --git a/frontend/src/scenes/authentication/login/LoginForm.tsx b/frontend/src/scenes/authentication/login/LoginForm.tsx
deleted file mode 100644
index 1e0e35f0ac95..000000000000
--- a/frontend/src/scenes/authentication/login/LoginForm.tsx
+++ /dev/null
@@ -1,454 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { Form } from 'kea-forms'
-import { useEffect } from 'react'
-
-import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass'
-import { IconCheckCircle } from '@posthog/icons'
-
-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'
-import { usePrevious } from 'lib/hooks/usePrevious'
-import { LemonButton } from 'lib/lemon-ui/LemonButton'
-import { LemonField } from 'lib/lemon-ui/LemonField'
-import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
-import { Link } from 'lib/lemon-ui/Link'
-import { isWebKitBrowser } from 'lib/utils/dom'
-import { isEmail } from 'lib/utils/url'
-import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'
-import { AuthScene, AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
-import { RegionField } from 'scenes/authentication/shared/authScene/RegionField'
-import { useLastLoginMethod } from 'scenes/authentication/shared/lastLoginMethod'
-import { ERROR_MESSAGES } from 'scenes/authentication/shared/loginErrorMessages'
-import { OtherRegionHint } from 'scenes/authentication/shared/OtherRegionHint'
-import { pendingOAuthConnectionLogic, reviewAccessCopy } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'
-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'
-
-import { LoginMethod, Region, SSOProvider } from '~/types'
-
-import { loginLogic } from './loginLogic'
-import { SessionRiskBanner } from './SessionRiskBanner'
-
-const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)
-
-function loginGreeting(isReturning: boolean): { note: string; sub: string } {
- return isReturning
- ? { note: '// welcome back', sub: "Welcome back. Let's go ship something." }
- : { note: '// hey, good to see you', sub: "Let's go ship something." }
-}
-
-function loginMethodLabel(method: LoginMethod): string {
- if (method === 'password') {
- return 'password'
- }
- if (method === 'passkey') {
- return 'passkey'
- }
- return method ? SSO_PROVIDER_NAMES[method] : ''
-}
-
-// The support form starts empty for the person, so a login-error ticket loses the context the page
-// already holds. Prefill the message with the error code, region, and login methods, so support can
-// triage without a round trip.
-function buildLoginSupportMessage({
- errorCode,
- region,
- ssoEnforcement,
- availableLoginMethods,
- precheckTrusted,
- codeVerificationPending,
-}: {
- errorCode?: string
- region?: Region | null
- ssoEnforcement?: SSOProvider | null
- availableLoginMethods: LoginMethod[]
- precheckTrusted: boolean
- codeVerificationPending: boolean
-}): string {
- const lines = ['I need help logging in.']
- if (errorCode) {
- lines.push(`Error code: ${errorCode}`)
- }
- if (region) {
- lines.push(`Data region: ${region}`)
- }
- // Only state the account's methods when the precheck is trustworthy. A failed or stale one
- // reports permissive defaults (e.g. password login for an SSO-only account), which would point
- // support the wrong way.
- if (precheckTrusted) {
- if (ssoEnforcement) {
- lines.push(`Login method: SSO enforced (${SSO_PROVIDER_NAMES[ssoEnforcement]})`)
- } else {
- const labels = availableLoginMethods.map(loginMethodLabel).filter(Boolean)
- if (labels.length) {
- lines.push(`Login methods available: ${labels.join(', ')}`)
- }
- }
- }
- if (codeVerificationPending) {
- lines.push('Waiting on an emailed verification code.')
- }
- return lines.join('\n')
-}
-
-// Bare text nodes below are wrapped in <span>s: in-page translation replaces text nodes with
-// <font> elements, which crashes React's sibling insert/remove operations (removeChild /
-// 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, submitCodeVerification } =
- useActions(loginLogic)
- const { openSupportForm } = useActions(supportLogic)
- const { sendSupportRequest } = useValues(supportLogic)
- const {
- precheckResponse,
- precheckResponseLoading,
- login,
- isLoginSubmitting,
- generalError,
- signupUrl,
- resendResponseLoading,
- resendResponse,
- codeVerificationRequired,
- isCodeVerificationSubmitting,
- isPasswordLoginUnavailable,
- codeVerificationEmail,
- codeVerification,
- hasNoConfiguredLoginMethod,
- restrictToProviders,
- autoRedirectingToProvider,
- availableLoginMethods,
- } = useValues(loginLogic)
- const { preflight } = useValues(preflightLogic)
- const { pendingConnection } = useValues(pendingOAuthConnectionLogic({ screen: 'login' }))
-
- const isPasswordHidden = !!precheckResponse.sso_enforcement || isPasswordLoginUnavailable
- const isCodeSent = codeVerificationRequired
- const lastLoginMethod = useLastLoginMethod()
- const greeting = loginGreeting(lastLoginMethod !== null)
- const prevEmail = usePrevious(login.email)
-
- useEffect(() => {
- const charDelta = login.email.length - (prevEmail?.length ?? 0)
- const isAutofill = charDelta > 1
-
- if (isAutofill && isEmail(login.email, { requireTLD: true }) && precheckResponse.status === 'pending') {
- precheck({ email: login.email })
- }
- }, [login.email, prevEmail, precheckResponse.status, precheck])
-
- const footer = (
- <p className="mt-5 mb-0 text-sm text-secondary text-center">
- <span>New to PostHog?</span>{' '}
- <Link
- to={[signupUrl, { email: login.email }]}
- data-attr="signup"
- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
- >
- Create an account →
- </Link>
- </p>
- )
-
- return (
- <AuthScene notes={[greeting.note, '// 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 ? (
- 'Check your inbox'
- ) : (
- <>
- {/* This whole fragment is deleted when the title flips to the code-sent
- string, so even the separator space lives inside an element */}
- <span>{pendingConnection ? 'Log in to connect ' : 'Log in to '}</span>
- <span className="px-1 rounded-md bg-[color-mix(in_srgb,var(--color-blue-500)_10%,transparent)] text-[var(--color-blue-500)]">
- {pendingConnection ? pendingConnection.clientName : '@PostHog'}
- </span>
- </>
- )
- }
- sub={
- isCodeSent ? (
- <>
- For your security, we've emailed a 6-digit verification code to{' '}
- <strong>{codeVerificationEmail}</strong>.
- </>
- ) : pendingConnection ? (
- reviewAccessCopy(pendingConnection, 'After you log in')
- ) : (
- greeting.sub
- )
- }
- />
- <SessionRiskBanner className="mb-4" />
- {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] ||
- 'Could not complete your login. Please try again.'}
- </span>
- {preflight?.cloud && (
- <>
- {' '}
- <Link
- data-attr="login-error-contact-support"
- onClick={(e) => {
- e.preventDefault()
- // Trust the precheck only when it resolved for the email now
- // in the form: a failed precheck reports permissive defaults,
- // and a stale one still holds the previous email's account.
- const precheckTrusted =
- precheckResponse.status === 'completed' &&
- !precheckResponse.precheckFailed &&
- precheckResponse.email === login.email
- openSupportForm({
- kind: 'support',
- email: login.email,
- // Prefill only into an empty form. Passing no message lets
- // openSupportForm keep a draft the person already started,
- // so reopening this link never overwrites their text.
- message: sendSupportRequest.message
- ? undefined
- : buildLoginSupportMessage({
- errorCode: generalError.code,
- region: preflight?.region,
- ssoEnforcement: precheckResponse.sso_enforcement,
- availableLoginMethods,
- precheckTrusted,
- codeVerificationPending: codeVerificationRequired,
- }),
- })
- }}
- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
- >
- Need help?
- </Link>
- </>
- )}
- </div>
- )}
- {generalError?.code === 'invalid_credentials' && (
- <div className="mb-4">
- <OtherRegionHint />
- </div>
- )}
- {isCodeSent ? (
- <Form
- 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"
- 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"
- disabled={isCodeVerificationSubmitting}
- onComplete={() => {
- if (!isCodeVerificationSubmitting) {
- submitCodeVerification()
- }
- }}
- />
- </LemonField>
- <LemonButton
- type="primary"
- status="alt"
- htmlType="submit"
- data-attr="code-verification-submit"
- fullWidth
- 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">
- <Link
- onClick={() => exitCodeVerification()}
- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-secondary"
- >
- Back to login
- </Link>
- </div>
- </Form>
- ) : (
- <Form logic={loginLogic} formKey="login" enableFormOnSubmit className="flex flex-col gap-4">
- <RegionField />
- <LemonField name="email" label="Email">
- {({ value, onChange, error, id }) => (
- <LemonInput
- id={id}
- className="ph-ignore-input"
- data-attr="login-email"
- type="email"
- autoFocus
- placeholder="[email protected]"
- // The `webauthn` token enables passkey autofill (conditional UI),
- // which we only offer on WebKit; elsewhere the auto-modal handles passkeys.
- autoComplete={isWebKitBrowser() ? 'username webauthn' : 'email'}
- value={value ?? ''}
- onChange={onChange}
- // `autoAttempt` is only ever set on this explicit gesture, so
- // autofill or a mistyped address can't bounce the user out to an
- // identity provider.
- onBlur={() => precheck({ email: login.email, autoAttempt: true })}
- status={error ? 'danger' : 'default'}
- fullWidth
- />
- )}
- </LemonField>
- {!isPasswordHidden && (
- <LemonField
- name="password"
- label={
- <div className="flex items-baseline justify-between w-full">
- <span>Password</span>
- <Link
- to={[urls.passwordReset(), { email: login.email }]}
- data-attr="forgot-password"
- className="text-xs font-semibold text-warning"
- tabIndex={-1}
- >
- Forgot password?
- </Link>
- </div>
- }
- >
- {({ value, onChange, error, id }) => (
- <LemonInput
- id={id}
- className="ph-ignore-input"
- data-attr="password"
- type="password"
- placeholder="••••••••••"
- autoComplete="current-password"
- value={value ?? ''}
- onChange={onChange}
- status={error ? 'danger' : 'default'}
- fullWidth
- />
- )}
- </LemonField>
- )}
- {hasNoConfiguredLoginMethod && (
- <div className="py-2.5 px-3 text-sm leading-normal text-primary text-left bg-warning-highlight border border-warning rounded">
- <span>No sign-in method is set up for this account. Use</span>{' '}
- <Link
- to={[urls.passwordReset(), { email: login.email }]}
- // Autocapture reports the click. Each reset entry point has its
- // own `data-attr`, so one funnel can tell them apart.
- data-attr="login-no-method-reset-password"
- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
- >
- Forgot password?
- </Link>{' '}
- <span>to set a password by email.</span>
- </div>
- )}
- {autoRedirectingToProvider && (
- <p className="text-sm text-secondary text-center mb-0">
- Redirecting to {SSO_PROVIDER_NAMES[autoRedirectingToProvider]}…
- </p>
- )}
- {/* No password to submit means this button would do nothing */}
- {!precheckResponse.sso_enforcement && !isPasswordLoginUnavailable && (
- <LemonButton
- type="primary"
- size="large"
- center
- fullWidth
- htmlType="submit"
- data-attr="password-login"
- loading={isLoginSubmitting || precheckResponseLoading}
- >
- Log in
- </LemonButton>
- )}
- {precheckResponse.sso_enforcement && (
- <SSOEnforcedLoginButton
- provider={precheckResponse.sso_enforcement}
- email={login.email}
- isLastUsed={lastLoginMethod === precheckResponse.sso_enforcement}
- />
- )}
- {precheckResponse.saml_available && !precheckResponse.sso_enforcement && (
- <SSOEnforcedLoginButton
- provider="saml"
- email={login.email}
- isLastUsed={lastLoginMethod === 'saml'}
- />
- )}
- {precheckResponse.oidc_available && !precheckResponse.sso_enforcement && (
- <SSOEnforcedLoginButton
- provider="oidc"
- email={login.email}
- isLastUsed={lastLoginMethod === 'oidc'}
- />
- )}
- </Form>
- )}
- {/* Normally SAML replaces this row, but when the account has no password we need to
- show whatever it does have. */}
- {!isCodeSent &&
- !precheckResponse.sso_enforcement &&
- (!precheckResponse.saml_available || isPasswordLoginUnavailable) && (
- <SocialLoginButtons
- topDivider
- caption={isPasswordLoginUnavailable ? 'Log in with' : 'Or log in with'}
- captionLocation="top"
- lastUsedProvider={lastLoginMethod}
- restrictToProviders={restrictToProviders}
- // Once we know the account's methods, only offer a passkey if it actually has
- // one — otherwise this is the same dead button we're removing.
- showPasskey={!isPasswordLoginUnavailable || !!precheckResponse.webauthn_credentials?.length}
- />
- )}
- </AuthSceneCard>
- </AuthScene>
- )
-}
diff --git a/frontend/src/scenes/authentication/signup/signupForm/TurnstileChallenge.tsx b/frontend/src/scenes/authentication/shared/TurnstileChallenge.tsx
similarity index 100%
rename from frontend/src/scenes/authentication/signup/signupForm/TurnstileChallenge.tsx
rename to frontend/src/scenes/authentication/shared/TurnstileChallenge.tsx
diff --git a/frontend/src/scenes/authentication/shared/authScene/AuthBanner.tsx b/frontend/src/scenes/authentication/shared/authScene/AuthBanner.tsx
new file mode 100644
index 000000000000..98bbd2e6e6ea
--- /dev/null
+++ b/frontend/src/scenes/authentication/shared/authScene/AuthBanner.tsx
@@ -0,0 +1,58 @@
+import clsx from 'clsx'
+import { type ReactNode } from 'react'
+
+import { IconCheckCircle, IconWarning } from '@posthog/icons'
+
+import { IconErrorOutline } from 'lib/lemon-ui/icons'
+
+export type AuthBannerVariant = 'note' | 'warning' | 'danger' | 'success'
+
+// Every variant shares the note's surface, so banners read as part of the auth card. A solid outline
+// mixed from the variant's color and the icon carry its meaning. The scene remaps `text-warning` to
+// the primary text color, so the colors read the global `--warning`, `--danger` and `--success`.
+const VARIANT_CLASSES: Record<AuthBannerVariant, string> = {
+ note: 'border-[color:var(--auth-scene-note-border)] text-secondary',
+ warning: 'border-[color:color-mix(in_srgb,var(--warning)_55%,transparent)] text-primary',
+ danger: 'border-[color:color-mix(in_srgb,var(--danger)_55%,transparent)] text-primary',
+ success: 'border-[color:color-mix(in_srgb,var(--success)_55%,transparent)] text-primary',
+}
+
+const VARIANT_ICONS: Partial<Record<AuthBannerVariant, ReactNode>> = {
+ warning: <IconWarning className="text-[var(--warning)]" />,
+ danger: <IconErrorOutline className="text-[var(--danger)]" />,
+ success: <IconCheckCircle className="text-[var(--success)]" />,
+}
+
+export function AuthBanner({
+ variant,
+ icon,
+ className,
+ children,
+}: {
+ variant: AuthBannerVariant
+ /** Replaces the variant's own icon. */
+ icon?: ReactNode
+ className?: string
+ children: ReactNode
+}): JSX.Element {
+ const shownIcon = icon ?? VARIANT_ICONS[variant]
+
+ return (
+ <div
+ role={variant === 'danger' ? 'alert' : undefined}
+ className={clsx(
+ 'flex gap-2.5 items-start py-3 px-3.5 text-sm leading-relaxed text-left rounded',
+ 'bg-[var(--auth-scene-note-bg)] border',
+ VARIANT_CLASSES[variant],
+ className
+ )}
+ >
+ {shownIcon && (
+ <span className="shrink-0 text-base leading-none mt-0.5" aria-hidden>
+ {shownIcon}
+ </span>
+ )}
+ <div className="flex-1 min-w-0">{children}</div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/authentication/shared/authStepViewed.ts b/frontend/src/scenes/authentication/shared/authStepViewed.ts
new file mode 100644
index 000000000000..d81df31384ca
--- /dev/null
+++ b/frontend/src/scenes/authentication/shared/authStepViewed.ts
@@ -0,0 +1,29 @@
+import posthog from 'posthog-js'
+
+import { readPendingOAuthConnection } from './pendingOAuthConnectionLogic'
+
+/** The URL a person opened the auth page on. Both URLs render the same page with different copy.
+ * pinned: analytics property value on `auth step viewed` and `auth email submitted` */
+export type AuthEntry = 'login' | 'signup'
+
+/** pinned: analytics property value on `auth step viewed` */
+export type AuthStep =
+ | 'email'
+ | 'login'
+ | 'login_code'
+ | 'signup_credentials'
+ | 'signup_profile'
+ | 'signup_pending_invite'
+ | 'verify_email'
+
+/** The OAuth client a signed-out `/oauth/authorize` sent the person from, for every auth event.
+ * pinned: analytics property names */
+export function pendingOAuthConnectionProperties(): { oauth_client_name?: string; oauth_client_id?: string } {
+ const connection = readPendingOAuthConnection()
+ return { oauth_client_name: connection?.clientName, oauth_client_id: connection?.clientId }
+}
+
+export function captureAuthStepViewed(step: AuthStep, entry: AuthEntry | null): void {
+ // pinned: analytics event name
+ posthog.capture('auth step viewed', { step, entry, ...pendingOAuthConnectionProperties() })
+}
diff --git a/frontend/src/scenes/authentication/shared/devLoginLogic.ts b/frontend/src/scenes/authentication/shared/devLoginLogic.ts
index 096142b22ce1..93186eb1b3a6 100644
--- a/frontend/src/scenes/authentication/shared/devLoginLogic.ts
+++ b/frontend/src/scenes/authentication/shared/devLoginLogic.ts
@@ -151,7 +151,7 @@ export const devLoginLogic = kea<devLoginLogicType>([
listeners(({ actions }) => ({
devLogin: async ({ email }) => {
// Dynamic import to avoid a circular dependency: loginLogic statically imports this logic.
- const { loginLogic, redirectAfterLogin } = await import('scenes/authentication/login/loginLogic')
+ const { loginLogic, redirectAfterLogin } = await import('scenes/authentication/auth/loginLogic')
loginLogic.actions.clearGeneralError()
try {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
diff --git a/frontend/src/scenes/authentication/shared/loginTelemetryLogic.test.ts b/frontend/src/scenes/authentication/shared/loginTelemetryLogic.test.ts
index 9ec636b5fa62..518e1138a661 100644
--- a/frontend/src/scenes/authentication/shared/loginTelemetryLogic.test.ts
+++ b/frontend/src/scenes/authentication/shared/loginTelemetryLogic.test.ts
@@ -2,8 +2,8 @@ import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
+import { loginLogic } from 'scenes/authentication/auth/loginLogic'
import { login2FALogic } from 'scenes/authentication/login-2fa/login2FALogic'
-import { loginLogic } from 'scenes/authentication/login/loginLogic'
import { passwordResetLogic } from 'scenes/authentication/password-reset/passwordResetLogic'
import { LISTENED_ACTIONS, loginTelemetryLogic } from 'scenes/authentication/shared/loginTelemetryLogic'
diff --git a/frontend/src/scenes/authentication/shared/loginTelemetryLogic.ts b/frontend/src/scenes/authentication/shared/loginTelemetryLogic.ts
index c056d4ba3163..be802dbb38b2 100644
--- a/frontend/src/scenes/authentication/shared/loginTelemetryLogic.ts
+++ b/frontend/src/scenes/authentication/shared/loginTelemetryLogic.ts
@@ -1,7 +1,7 @@
import { MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'
import posthog from 'posthog-js'
-import { loginLogic } from 'scenes/authentication/login/loginLogic'
+import { loginLogic } from 'scenes/authentication/auth/loginLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { PreflightStatus } from '~/types'
@@ -32,9 +32,9 @@ let reportedError: { code: string; detail: string } | null = null
* matches, when an action is renamed, or when a logic's module moves.
*/
export const LISTENED_ACTIONS = {
- submitLoginRequest: 'submit login request (scenes.authentication.login.loginLogic)',
- loginError: 'set general error (scenes.authentication.login.loginLogic)',
- codeVerificationFailure: 'submit code verification failure (scenes.authentication.login.loginLogic)',
+ submitLoginRequest: 'submit login request (scenes.authentication.auth.loginLogic)',
+ loginError: 'set general error (scenes.authentication.auth.loginLogic)',
+ codeVerificationFailure: 'submit code verification failure (scenes.authentication.auth.loginLogic)',
twoFactorError: 'set general error (scenes.authentication.login-2fa.login2FALogic)',
resetRequested: 'submit request password reset success (scenes.authentication.password-reset.passwordResetLogic)',
} as const
diff --git a/frontend/src/scenes/authentication/shared/passkeyLogic.test.ts b/frontend/src/scenes/authentication/shared/passkeyLogic.test.ts
index c2d2d040a3e2..b12f4b7053ea 100644
--- a/frontend/src/scenes/authentication/shared/passkeyLogic.test.ts
+++ b/frontend/src/scenes/authentication/shared/passkeyLogic.test.ts
@@ -2,7 +2,7 @@ import { browserSupportsWebAuthnAutofill, startAuthentication } from '@simpleweb
import { expectLogic } from 'kea-test-utils'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
-import { loginLogic } from 'scenes/authentication/login/loginLogic'
+import { loginLogic } from 'scenes/authentication/auth/loginLogic'
import { passkeyLogic } from 'scenes/authentication/shared/passkeyLogic'
import { useMocks } from '~/mocks/jest'
diff --git a/frontend/src/scenes/authentication/shared/passkeyLogic.ts b/frontend/src/scenes/authentication/shared/passkeyLogic.ts
index 4dbb11c04a2c..b57385e65b10 100644
--- a/frontend/src/scenes/authentication/shared/passkeyLogic.ts
+++ b/frontend/src/scenes/authentication/shared/passkeyLogic.ts
@@ -13,7 +13,7 @@ import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { isWebKitBrowser } from 'lib/utils/dom'
-import { loginLogic, redirectAfterLogin } from 'scenes/authentication/login/loginLogic'
+import { loginLogic, redirectAfterLogin } from 'scenes/authentication/auth/loginLogic'
import { ssoEnforcedMessage } from 'scenes/authentication/shared/loginErrorMessages'
import { getPasskeyErrorMessage, isWebAuthnCancellation } from 'scenes/settings/user/passkeys/utils'
import { urls } from 'scenes/urls'
diff --git a/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.test.ts b/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.test.ts
index c7aba995ef9d..05b87dfe9741 100644
--- a/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.test.ts
+++ b/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.test.ts
@@ -1,15 +1,11 @@
import { setPendingOAuthConnectionCookie as setCookie } from './pendingOAuthConnection.mock'
-import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
-import posthog from 'posthog-js'
import { initKeaTests } from '~/test/init'
import { pendingOAuthConnectionLogic, readPendingOAuthConnection } from './pendingOAuthConnectionLogic'
-jest.mock('posthog-js')
-
const CLIENT_ID = 'https://claude.example.com/.well-known/oauth-client'
function encoded(payload: unknown): string {
@@ -20,17 +16,15 @@ describe('pendingOAuthConnectionLogic', () => {
beforeEach(() => {
initKeaTests()
setCookie(null)
- jest.mocked(posthog.capture).mockClear()
})
- it('reads the cookie the authorize endpoint set and reports which screen showed it', async () => {
+ it('reads the cookie the authorize endpoint set', async () => {
setCookie({
client_name: 'Claude &amp; Co',
client_id: CLIENT_ID,
logo_uri: 'https://claude.example.com/logo.png',
redirect_host: 'claude.example.com',
})
- router.actions.push('/login')
const logic = pendingOAuthConnectionLogic()
logic.mount()
@@ -42,33 +36,6 @@ describe('pendingOAuthConnectionLogic', () => {
redirectHost: 'claude.example.com',
},
})
- expect(posthog.capture).toHaveBeenCalledTimes(1)
- expect(posthog.capture).toHaveBeenCalledWith('oauth pending connection viewed', {
- screen: 'login',
- client_name: 'Claude & Co',
- client_id: CLIENT_ID,
- })
- })
-
- it('reports nothing when no connection is pending', async () => {
- router.actions.push('/signup')
- const logic = pendingOAuthConnectionLogic()
- logic.mount()
-
- await expectLogic(logic).toMatchValues({ pendingConnection: null })
- expect(posthog.capture).not.toHaveBeenCalled()
- })
-
- it('reports nothing from a screen outside the auth flow', async () => {
- setCookie({ client_name: 'Claude', client_id: CLIENT_ID })
- router.actions.push('/organization/confirm-creation')
- const logic = pendingOAuthConnectionLogic()
- logic.mount()
-
- await expectLogic(logic).toMatchValues({
- pendingConnection: expect.objectContaining({ clientName: 'Claude' }),
- })
- expect(posthog.capture).not.toHaveBeenCalled()
})
it.each([
diff --git a/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.ts b/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.ts
index d29033009f61..c87406ee4e66 100644
--- a/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.ts
+++ b/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.ts
@@ -1,18 +1,12 @@
import { decode } from 'he'
import { LogicWrapper, MakeLogicType, actions, afterMount, kea, path, reducers } from 'kea'
-import { router } from 'kea-router'
-import posthog from 'posthog-js'
import { getCookie } from 'lib/api'
import { tryJsonParse } from 'lib/utils/json'
-import { urls } from 'scenes/urls'
// pinned: the backend sets this cookie (posthog/helpers/oauth_pending_connection.py) and the website reads it
export const PENDING_OAUTH_CONNECTION_COOKIE = 'ph_pending_oauth_connection'
-// pinned: analytics property value on `oauth pending connection viewed`
-export type PendingOAuthConnectionScreen = 'login' | 'signup' | 'verify_email'
-
/** The OAuth application a signed-out visitor was asked to authorize before they reached login or signup. */
export interface PendingOAuthConnection {
clientName: string
@@ -53,27 +47,6 @@ export function readPendingOAuthConnection(): PendingOAuthConnection | null {
}
}
-/** `lead` opens the sentence, for example "After you log in". */
-export function reviewAccessCopy(connection: PendingOAuthConnection, lead: string): string {
- const back = connection.redirectHost ? `, then go back to ${connection.redirectHost}` : ''
- return `${lead}, you'll review what ${connection.clientName} can access${back}.`
-}
-
-/** Taken from the path so that a component mounting this logic outside the three auth screens
- * cannot label the event as one of them. */
-function screenForPath(pathname: string): PendingOAuthConnectionScreen | null {
- if (pathname === urls.login()) {
- return 'login'
- }
- if (pathname === urls.signup()) {
- return 'signup'
- }
- if (pathname.startsWith(urls.verifyEmail())) {
- return 'verify_email'
- }
- return null
-}
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface pendingOAuthConnectionLogicValues {
pendingConnection: PendingOAuthConnection | null
@@ -91,8 +64,7 @@ export type pendingOAuthConnectionLogicType = MakeLogicType<
pendingOAuthConnectionLogicActions
>
-/** One instance for the whole auth flow, so a panel change inside a scene does not re-read the
- * cookie or report the view again. */
+/** One instance for the whole auth flow, so a step change inside a scene does not re-read the cookie. */
export const pendingOAuthConnectionLogic: LogicWrapper<pendingOAuthConnectionLogicType> =
kea<pendingOAuthConnectionLogicType>([
path(['scenes', 'authentication', 'shared', 'pendingOAuthConnectionLogic']),
@@ -113,13 +85,5 @@ export const pendingOAuthConnectionLogic: LogicWrapper<pendingOAuthConnectionLog
return
}
actions.setPendingConnection(pendingConnection)
- const screen = screenForPath(router.values.location.pathname)
- if (screen) {
- posthog.capture('oauth pending connection viewed', {
- screen,
- client_name: pendingConnection.clientName,
- client_id: pendingConnection.clientId,
- })
- }
}),
])
diff --git a/frontend/src/scenes/authentication/signup/Signup.stories.tsx b/frontend/src/scenes/authentication/signup/Signup.stories.tsx
deleted file mode 100644
index 1339c1fe3e8d..000000000000
--- a/frontend/src/scenes/authentication/signup/Signup.stories.tsx
+++ /dev/null
@@ -1,136 +0,0 @@
-import {
- PENDING_OAUTH_CONNECTION_FIXTURE,
- setPendingOAuthConnectionCookie,
-} from 'scenes/authentication/shared/pendingOAuthConnection.mock'
-
-import type { Meta, StoryFn } from '@storybook/react'
-import { HttpResponse, delay } from 'msw'
-import { useEffect } from 'react'
-
-import { useDelayedOnMountEffect } from 'lib/hooks/useOnMountEffect'
-import { userLogic } from 'scenes/userLogic'
-
-import { mswDecorator, useStorybookMocks } from '~/mocks/browser'
-import preflightJson from '~/mocks/fixtures/_preflight.json'
-
-import { Signup } from './Signup'
-import { signupLogic } from './signupForm/signupLogic'
-
-type PanelOption = '1: Email' | '2: Password' | '3: Profile'
-
-const PANEL_INDEX: Record<PanelOption, 0 | 1 | 2> = {
- '1: Email': 0,
- '2: Password': 1,
- '3: Profile': 2,
-}
-
-type StoryArgs = {
- cloud: boolean
- region: 'US' | 'EU'
- googleOAuth: boolean
- github: boolean
- gitlab: boolean
- panel: PanelOption
- pendingOAuthConnection: boolean
-}
-
-const meta: Meta<StoryArgs> = {
- title: 'Scenes-Other/Signup',
- tags: ['test-skip'],
- parameters: {
- layout: 'fullscreen',
- viewMode: 'story',
- },
- decorators: [
- mswDecorator({
- get: { '/api/users/@me': () => [500, null] },
- post: {
- '/api/signup': async () => {
- await delay(1000)
- return HttpResponse.json({ success: true })
- },
- },
- }),
- ],
- argTypes: {
- cloud: { control: 'boolean', name: 'Cloud' },
- region: { control: 'select', options: ['US', 'EU'], name: 'Region', if: { arg: 'cloud' } },
- googleOAuth: { control: 'boolean', name: 'Google OAuth' },
- github: { control: 'boolean', name: 'GitHub' },
- gitlab: { control: 'boolean', name: 'GitLab' },
- panel: {
- control: 'select',
- name: 'Step',
- options: ['1: Email', '2: Password', '3: Profile'] satisfies PanelOption[],
- },
- pendingOAuthConnection: { control: 'boolean', name: 'Pending OAuth connection' },
- },
- args: {
- cloud: true,
- region: 'US',
- googleOAuth: true,
- github: true,
- gitlab: true,
- panel: '1: Email',
- pendingOAuthConnection: false,
- },
-}
-export default meta
-
-const Template: StoryFn<StoryArgs> = ({
- cloud,
- region,
- googleOAuth,
- github,
- gitlab,
- panel: panelOption,
- pendingOAuthConnection,
-}) => {
- const panel = PANEL_INDEX[panelOption]
- // Set synchronously: the scene reads the cookie while it mounts during this same render.
- setPendingOAuthConnectionCookie(pendingOAuthConnection ? PENDING_OAUTH_CONNECTION_FIXTURE : null)
- useStorybookMocks({
- get: {
- '/_preflight': {
- ...preflightJson,
- cloud,
- region: cloud ? region : undefined,
- realm: cloud ? 'cloud' : 'hosted-clickhouse',
- is_debug: cloud,
- can_create_org: cloud,
- available_social_auth_providers: {
- 'google-oauth2': googleOAuth,
- github,
- gitlab,
- saml: false,
- },
- },
- },
- })
-
- useDelayedOnMountEffect(() => userLogic.actions.loadUserSuccess(null))
-
- useEffect(() => {
- signupLogic.actions.setPanel(panel)
- if (panel > 0) {
- signupLogic.actions.setSignupPanelEmailValue('email', '[email protected]')
- }
- }, [panel])
-
- return <Signup />
-}
-
-export const Default: StoryFn<StoryArgs> = Template.bind({})
-
-export const SelfHosted: StoryFn<StoryArgs> = Template.bind({})
-SelfHosted.args = { cloud: false, googleOAuth: false, github: false, gitlab: false }
-
-export const PasswordStep: StoryFn<StoryArgs> = Template.bind({})
-PasswordStep.args = { panel: '2: Password' }
-
-export const ProfileStep: StoryFn<StoryArgs> = Template.bind({})
-ProfileStep.args = { panel: '3: Profile' }
-
-export const PendingOAuthConnection: StoryFn<StoryArgs> = Template.bind({})
-PendingOAuthConnection.storyName = 'Pending OAuth connection'
-PendingOAuthConnection.args = { pendingOAuthConnection: true }
diff --git a/frontend/src/scenes/authentication/signup/Signup.tsx b/frontend/src/scenes/authentication/signup/Signup.tsx
deleted file mode 100644
index ddadc7799236..000000000000
--- a/frontend/src/scenes/authentication/signup/Signup.tsx
+++ /dev/null
@@ -1,493 +0,0 @@
-import { useActions, useMountedLogic, useValues } from 'kea'
-import { Form } from 'kea-forms'
-import { useState } from 'react'
-
-import PasswordStrength from 'lib/components/PasswordStrength'
-import SignupReferralSource from 'lib/components/SignupReferralSource'
-import SignupRoleSelect from 'lib/components/SignupRoleSelect'
-import passkeyLogo from 'lib/components/SocialLoginButton/passkey.svg'
-import { SocialLoginButtons } from 'lib/components/SocialLoginButton/SocialLoginButton'
-import { supportLogic } from 'lib/components/Support/supportLogic'
-import { LemonButton } from 'lib/lemon-ui/LemonButton'
-import { LemonField } from 'lib/lemon-ui/LemonField'
-import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
-import { Link } from 'lib/lemon-ui/Link'
-import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'
-import { AuthScene, AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
-import { RegionField } from 'scenes/authentication/shared/authScene/RegionField'
-import { useLastLoginMethod } from 'scenes/authentication/shared/lastLoginMethod'
-import { pendingOAuthConnectionLogic, reviewAccessCopy } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'
-import { TurnstileChallenge } from 'scenes/authentication/signup/signupForm/TurnstileChallenge'
-import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
-import { SceneExport } from 'scenes/sceneTypes'
-import { userLogic } from 'scenes/userLogic'
-
-import { signupLogic } from './signupForm/signupLogic'
-
-export const scene: SceneExport = {
- component: Signup,
-}
-
-// Bare text nodes below are wrapped in <span>s: Chrome's in-page translation replaces text
-// nodes with <font> elements, which crashes React's sibling insert/remove operations
-// (removeChild/insertBefore NotFoundError, see react#11538). Text inside its own element is safe.
-const NOTES: Record<number, string[]> = {
- 0: ['// create an account', '// 1M events free, every month'],
- 1: ['// step 2 of 2', '// make it a good one'],
- 2: ['// almost there', '// last step'],
-}
-
-/** Step 1 — email (+ region, social, pending-invite branch). */
-function SignupEmailPanel(): JSX.Element {
- const { isSignupPanelEmailSubmitting, signupPanelEmailManualErrors, pendingInvite, loginUrl, emailCaseNotice } =
- useValues(signupLogic)
- const { preflight } = useValues(preflightLogic)
- const { pendingConnection } = useValues(pendingOAuthConnectionLogic)
- const [showJoinOrg, setShowJoinOrg] = useState(false)
- const lastLoginMethod = useLastLoginMethod()
- const accountExists = !!signupPanelEmailManualErrors?.email
-
- if (pendingInvite) {
- return <PendingInvitePanel />
- }
-
- const footer = preflight?.demo ? undefined : (
- <p className="mt-5 mb-0 text-sm text-secondary text-center">
- <span>Already have an account?</span>{' '}
- <Link
- to={loginUrl}
- data-attr="signup-login-link"
- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
- >
- Log in →
- </Link>
- </p>
- )
-
- return (
- <AuthSceneCard footer={footer}>
- <AuthCardTitle
- title={
- pendingConnection ? `Create your account to connect ${pendingConnection.clientName}` : 'Get started'
- }
- sub={
- pendingConnection
- ? reviewAccessCopy(pendingConnection, 'Once your account is ready')
- : 'Make your product self-driving.'
- }
- />
- <Form logic={signupLogic} formKey="signupPanelEmail" enableFormOnSubmit className="flex flex-col gap-4">
- <RegionField />
- <LemonField
- name="email"
- label="Email"
- help={emailCaseNotice && <span className="text-warning">{emailCaseNotice}</span>}
- >
- {({ value, onChange, error, id }) => (
- <LemonInput
- id={id}
- className="ph-ignore-input"
- data-attr="signup-email"
- type="email"
- autoFocus
- autoComplete="email"
- placeholder="[email protected]"
- value={value ?? ''}
- onChange={onChange}
- status={error ? 'danger' : 'default'}
- fullWidth
- />
- )}
- </LemonField>
- {accountExists && (
- <p className="text-xs text-danger -mt-2">
- <span>{signupPanelEmailManualErrors.email}</span>{' '}
- <Link
- to={loginUrl}
- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
- >
- Log in instead →
- </Link>
- </p>
- )}
- <LemonButton
- type="primary"
- size="large"
- center
- fullWidth
- htmlType="submit"
- data-attr="signup-start"
- loading={isSignupPanelEmailSubmitting}
- >
- Continue
- </LemonButton>
- </Form>
- {!preflight?.demo && (
- <SocialLoginButtons
- topDivider
- caption="or sign up with"
- lastUsedProvider={lastLoginMethod ?? undefined}
- captionLocation="top"
- />
- )}
- {!preflight?.demo && (
- <div className="mt-4 text-center">
- <button
- type="button"
- data-attr="signup-join-existing-org"
- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-secondary text-xs"
- onClick={() => setShowJoinOrg((v) => !v)}
- >
- Trying to join an existing organization?
- </button>
- {showJoinOrg && (
- <p className="AuthScene__note mt-3 py-3 px-3.5 text-xs leading-relaxed text-secondary text-left border border-dashed rounded">
- You'll need your invite link. When a teammate invites you, we email you a personal link.
- Didn't get one? Check spam, or ask them to resend it from their members settings.
- </p>
- )}
- </div>
- )}
- </AuthSceneCard>
- )
-}
-
-function PendingInvitePanel(): JSX.Element {
- const { signupPanelEmail, pendingInvite, pendingInviteResent, isPendingInviteResending } = useValues(signupLogic)
- const { resendPendingInvite, dismissPendingInvite } = useActions(signupLogic)
- const org = pendingInvite?.organization_name ?? 'your team'
-
- return (
- <AuthSceneCard>
- <AuthCardTitle
- title="You've already been invited"
- sub={
- <span>
- <b className="text-primary">{org}</b> <span>invited</span>{' '}
- <span className="AuthScene__mono">{signupPanelEmail.email}</span>{' '}
- <span>to join them on PostHog. The invite link is in your inbox.</span>
- </span>
- }
- className="mb-5"
- />
- {pendingInviteResent ? (
- <div className="flex gap-2 items-start py-2.5 px-3 text-sm text-primary text-left bg-success-highlight border border-success rounded">
- <span className="font-bold text-success">✓</span>
- <span>Sent. Look for an email from {org}. The link inside takes you straight in.</span>
- </div>
- ) : (
- <div className="flex flex-col gap-2.5">
- <LemonButton
- type="primary"
- size="large"
- center
- fullWidth
- data-attr="pending-invite-resend"
- loading={isPendingInviteResending}
- onClick={() => resendPendingInvite(signupPanelEmail.email)}
- >
- Resend invite email
- </LemonButton>
- <LemonButton
- size="large"
- center
- fullWidth
- data-attr="pending-invite-create-own-org"
- onClick={() => dismissPendingInvite()}
- >
- I'd rather create my own organization
- </LemonButton>
- </div>
- )}
- </AuthSceneCard>
- )
-}
-
-/** Step 2 — passkey or password. */
-function SignupAuthPanel(): JSX.Element {
- const {
- signupPanelEmail,
- isSignupPanelAuthSubmitting,
- validatedPassword,
- passkeyRegistered,
- isPasskeyRegistering,
- passkeyError,
- } = useValues(signupLogic)
- const { registerPasskey, setPanel } = useActions(signupLogic)
-
- const footer = (
- <>
- <p className="AuthScene__terms mt-5 mb-0 text-xs leading-relaxed text-tertiary text-center">
- <span>By creating an account, you agree to our</span>{' '}
- <Link to="https://posthog.com/terms" target="_blank">
- Terms of Service ↗
- </Link>{' '}
- <span>and</span>{' '}
- <Link to="https://posthog.com/privacy" target="_blank">
- Privacy Policy ↗
- </Link>
- <span>.</span>
- </p>
- <p className="mt-3 mb-0 text-sm text-secondary text-center">
- <Link
- onClick={() => setPanel(0)}
- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
- >
- ← Use a different email
- </Link>
- </p>
- </>
- )
-
- return (
- <AuthSceneCard footer={footer}>
- <AuthCardTitle
- title="Secure your account"
- sub={
- <span>
- <span>Signing up as</span> <span className="AuthScene__mono">{signupPanelEmail.email}</span>
- </span>
- }
- />
- {passkeyError && (
- <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>{passkeyError}</span>
- </div>
- )}
- {passkeyRegistered ? (
- <div className="AuthScene__note text-center py-3 px-3.5 text-xs leading-relaxed text-secondary border border-dashed rounded">
- Passkey registered. Continue below.
- </div>
- ) : (
- <LemonButton
- type="secondary"
- size="large"
- fullWidth
- icon={<img src={passkeyLogo} alt="Passkey" className="object-contain w-7 h-7" />}
- onClick={registerPasskey}
- loading={isPasskeyRegistering}
- disabled={isPasskeyRegistering}
- data-attr="signup-passkey"
- center
- >
- Sign up with a passkey
- </LemonButton>
- )}
- {!passkeyRegistered && (
- <div className="my-4 flex gap-3 items-center">
- <span className="flex-1 h-px bg-[#e0e1d9]" />
- <span className="text-xs text-secondary whitespace-nowrap">or use a password</span>
- <span className="flex-1 h-px bg-[#e0e1d9]" />
- </div>
- )}
- <Form logic={signupLogic} formKey="signupPanelAuth" enableFormOnSubmit className="flex flex-col gap-4">
- {!passkeyRegistered && (
- <LemonField
- name="password"
- label={
- <div className="flex items-baseline justify-between w-full">
- <span>Password</span>
- <PasswordStrength validatedPassword={validatedPassword} />
- </div>
- }
- >
- {({ value, onChange, error, id }) => (
- <LemonInput
- id={id}
- className="ph-ignore-input"
- data-attr="password"
- type="password"
- autoFocus
- autoComplete="new-password"
- placeholder="••••••••••"
- value={value ?? ''}
- onChange={onChange}
- status={error ? 'danger' : 'default'}
- fullWidth
- />
- )}
- </LemonField>
- )}
- <LemonButton
- type="primary"
- size="large"
- center
- fullWidth
- htmlType="submit"
- data-attr="signup-auth-continue"
- loading={isSignupPanelAuthSubmitting}
- disabledReason={
- !passkeyRegistered && validatedPassword.feedback ? validatedPassword.feedback : undefined
- }
- >
- Create account
- </LemonButton>
- </Form>
- </AuthSceneCard>
- )
-}
-
-/** Step 3 — profile (name, organization, role, referral), like the legacy onboarding. */
-function SignupProfilePanel(): JSX.Element {
- const {
- isSignupPanelOnboardingSubmitting,
- signupPanelOnboardingManualErrors,
- challengeRequired,
- turnstileSiteKey,
- turnstileToken,
- signupPanelEmail,
- } = useValues(signupLogic)
- const { preflight } = useValues(preflightLogic)
- const { setTurnstileToken, setPanel } = useActions(signupLogic)
- const { openSupportForm } = useActions(supportLogic)
-
- const submitLabel = !preflight?.demo
- ? 'Create account'
- : !isSignupPanelOnboardingSubmitting
- ? 'Enter the demo environment'
- : 'Preparing demo data…'
-
- const footer = (
- <>
- <p className="AuthScene__terms mt-5 mb-0 text-xs leading-relaxed text-tertiary text-center">
- <span>
- By {preflight?.demo ? 'entering the demo environment' : 'creating an account'}, you agree to our
- </span>{' '}
- <Link to="https://posthog.com/terms" target="_blank">
- Terms of Service ↗
- </Link>{' '}
- <span>and</span>{' '}
- <Link to="https://posthog.com/privacy" target="_blank">
- Privacy Policy ↗
- </Link>
- <span>.</span>
- </p>
- {!preflight?.demo && (
- <p className="mt-5 mb-0 text-sm text-secondary text-center">
- <Link
- onClick={() => setPanel(1)}
- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
- >
- ← or go back
- </Link>
- </p>
- )}
- </>
- )
-
- return (
- <AuthSceneCard footer={footer}>
- <AuthCardTitle
- title="Tell us about yourself"
- sub={
- <span>
- <span>Setting up the account for</span>{' '}
- <span className="AuthScene__mono">{signupPanelEmail.email}</span>
- </span>
- }
- />
- {signupPanelOnboardingManualErrors?.generic && (
- <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>{signupPanelOnboardingManualErrors.generic.detail || 'Could not complete your signup.'}</span>
- {preflight?.cloud && (
- <>
- {' '}
- <Link
- // The login banner uses `login-error-contact-support`. A shared
- // attribute would mix both pages into one autocapture funnel arm.
- data-attr="signup-error-contact-support"
- onClick={(e) => {
- e.preventDefault()
- openSupportForm({
- kind: 'support',
- email: signupPanelEmail.email,
- })
- }}
- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
- >
- Contact us
- </Link>{' '}
- <span>to resolve this.</span>
- </>
- )}
- </div>
- )}
- <Form
- logic={signupLogic}
- formKey="signupPanelOnboarding"
- enableFormOnSubmit
- className="flex flex-col gap-4"
- >
- <LemonField name="name" label="Your name">
- {({ value, onChange, error, id }) => (
- <LemonInput
- id={id}
- className="ph-ignore-input"
- data-attr="signup-name"
- autoFocus
- placeholder="Jane Doe"
- autoComplete="name"
- value={value ?? ''}
- onChange={onChange}
- status={error ? 'danger' : 'default'}
- fullWidth
- />
- )}
- </LemonField>
- <LemonField name="organization_name" label="Organization name">
- {({ value, onChange, error, id }) => (
- <LemonInput
- id={id}
- className="ph-ignore-input"
- data-attr="signup-organization-name"
- placeholder="Hogflix Movies"
- value={value ?? ''}
- onChange={onChange}
- status={error ? 'danger' : 'default'}
- fullWidth
- />
- )}
- </LemonField>
- <SignupRoleSelect />
- <SignupReferralSource disabled={isSignupPanelOnboardingSubmitting} />
- {challengeRequired && turnstileSiteKey ? (
- <TurnstileChallenge
- siteKey={turnstileSiteKey}
- onSuccess={setTurnstileToken}
- tokenReceived={!!turnstileToken}
- email={signupPanelEmail.email}
- />
- ) : (
- <LemonButton
- type="primary"
- size="large"
- center
- fullWidth
- htmlType="submit"
- data-attr="signup-submit"
- loading={isSignupPanelOnboardingSubmitting}
- >
- {submitLabel}
- </LemonButton>
- )}
- </Form>
- </AuthSceneCard>
- )
-}
-
-export function Signup(): JSX.Element | null {
- const { user } = useValues(userLogic)
- const { panel } = useValues(signupLogic)
- // Mounted at the scene root so the cookie is read once, not on every panel change
- useMountedLogic(pendingOAuthConnectionLogic)
-
- if (user) {
- return null
- }
-
- return (
- <AuthScene notes={NOTES[panel] ?? NOTES[0]}>
- {panel === 0 ? <SignupEmailPanel /> : panel === 1 ? <SignupAuthPanel /> : <SignupProfilePanel />}
- </AuthScene>
- )
-}
diff --git a/frontend/src/scenes/authentication/two-factor-reset/twoFactorResetLogic.ts b/frontend/src/scenes/authentication/two-factor-reset/twoFactorResetLogic.ts
index 6509509d97f2..02d1157ce769 100644
--- a/frontend/src/scenes/authentication/two-factor-reset/twoFactorResetLogic.ts
+++ b/frontend/src/scenes/authentication/two-factor-reset/twoFactorResetLogic.ts
@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'
import api from 'lib/api'
-import { loginLogic } from 'scenes/authentication/login/loginLogic'
+import { loginLogic } from 'scenes/authentication/auth/loginLogic'
import { urls } from 'scenes/urls'
export interface ValidatedTokenResponse {
diff --git a/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx b/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx
index 396fd73d11a2..9d872ba7237e 100644
--- a/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx
+++ b/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx
@@ -11,7 +11,7 @@ import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { Link } from 'lib/lemon-ui/Link'
import { AuthScene, AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
-import { pendingOAuthConnectionLogic, reviewAccessCopy } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'
+import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'
import { getPendingVerificationEmail, isValidVerificationCode } from 'scenes/authentication/shared/verificationCode'
import { VerificationCodeInput } from 'scenes/authentication/shared/VerificationCodeInput'
import { urls } from 'scenes/urls'
@@ -209,7 +209,9 @@ function CheckYourInbox(): JSX.Element {
</p>
{pendingConnection && (
<p className="AuthScene__sub -mt-2 mb-4 text-sm text-secondary text-center text-pretty">
- {reviewAccessCopy(pendingConnection, 'After you verify')}
+ {`After you verify, you'll review what ${pendingConnection.clientName} can access${
+ pendingConnection.redirectHost ? `, then go back to ${pendingConnection.redirectHost}` : ''
+ }.`}
</p>
)}
<VerificationCodeEntry />
diff --git a/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts b/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts
index 80e35e076941..eb02fc569766 100644
--- a/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts
+++ b/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts
@@ -5,6 +5,7 @@ import { router, urlToAction } from 'kea-router'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { getRelativeNextPath } from 'lib/utils/url'
+import { captureAuthStepViewed } from 'scenes/authentication/shared/authStepViewed'
import {
clearPendingVerificationEmail,
isValidVerificationCode,
@@ -281,6 +282,7 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([
searchParams.email_sent !== 'false'
)
actions.setView('pending')
+ captureAuthStepViewed('verify_email', null)
}
}
return {
diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsx
index 05f5f071400e..bec3405d6da1 100644
--- a/frontend/src/scenes/sceneLogic.tsx
+++ b/frontend/src/scenes/sceneLogic.tsx
@@ -56,7 +56,7 @@ import { isSharedView } from '~/exporter/exporterViewLogic'
import { FileSystemIconType, ProductKey } from '~/queries/schema/schema-general'
import { AccessControlLevel, UserType } from '~/types'
-import { handleLoginRedirect } from './authentication/login/loginLogic'
+import { handleLoginRedirect } from './authentication/auth/loginLogic'
import { parseCouponCampaign } from './coupons/utils'
import { isOnboardingRedirectSuppressed } from './onboarding/onboardingDelegationState'
import { organizationLogic } from './organizationLogic'
diff --git a/playwright/e2e/auth-password-reset.spec.ts b/playwright/e2e/auth-password-reset.spec.ts
index 75566cf22c93..522cd67c0acb 100644
--- a/playwright/e2e/auth-password-reset.spec.ts
+++ b/playwright/e2e/auth-password-reset.spec.ts
@@ -21,11 +21,11 @@ test.describe('Password Reset', () => {
})
test('Can request password reset', async ({ page }) => {
- await loginPage.enterUsername('[email protected]')
- await page.locator('[data-attr=login-email]').blur()
- await expect(page.locator('[data-attr=forgot-password]')).toBeVisible({ timeout: 5000 })
+ // Only an existing account reaches the password step, where the reset link lives
+ await loginPage.enterUsername(workspace!.user_email)
+ await loginPage.continueWithEmail()
await page.click('[data-attr="forgot-password"]')
- await expect(page).toHaveURL('/reset?email=fake%40posthog.com')
+ await expect(page).toHaveURL(`/reset?email=${encodeURIComponent(workspace!.user_email)}`)
// Use a unique email so the per-email reset throttle (6/day) doesn't trip under repeated runs
const resetEmail = `${randomString('reset')}@posthog.com`
await page.fill('[data-attr="reset-email"]', resetEmail)
diff --git a/playwright/e2e/auth.spec.ts b/playwright/e2e/auth.spec.ts
index 220523c59a30..43f8fe5ddd85 100644
--- a/playwright/e2e/auth.spec.ts
+++ b/playwright/e2e/auth.spec.ts
@@ -44,8 +44,7 @@ test.describe('Auth', () => {
await loginPage.enterUsername(LOGIN_USERNAME)
await expect(page.locator('[data-attr=login-email]')).toHaveValue(LOGIN_USERNAME)
- await page.locator('[data-attr=login-email]').blur()
- await page.locator('[data-attr=password]').waitFor({ state: 'visible', timeout: 5000 })
+ await loginPage.continueWithEmail()
await loginPage.enterPassword(LOGIN_PASSWORD)
await expect(page.locator('[data-attr=password]')).toHaveValue(LOGIN_PASSWORD)
@@ -87,8 +86,7 @@ test.describe('Auth', () => {
await loginPage.enterUsername(LOGIN_USERNAME)
await expect(page.locator('[data-attr=login-email]')).toHaveValue(LOGIN_USERNAME)
- await page.locator('[data-attr=login-email]').blur()
- await page.locator('[data-attr=password]').waitFor({ state: 'visible', timeout: 5000 })
+ await loginPage.continueWithEmail()
await loginPage.enterPassword('wrong password')
await expect(page.locator('[data-attr=password]')).toHaveValue('wrong password')
@@ -108,8 +106,7 @@ test.describe('Auth', () => {
await expect(page).toHaveURL(/\/login/)
await loginPage.enterUsername(LOGIN_USERNAME)
- await page.locator('[data-attr=login-email]').blur()
- await page.locator('[data-attr=password]').waitFor({ state: 'visible', timeout: 5000 })
+ await loginPage.continueWithEmail()
await loginPage.enterPassword(LOGIN_PASSWORD)
await loginPage.clickLogin()
@@ -123,8 +120,7 @@ test.describe('Auth', () => {
await expect(page).toHaveURL(/\/login/)
await loginPage.enterUsername(LOGIN_USERNAME)
- await page.locator('[data-attr=login-email]').blur()
- await page.locator('[data-attr=password]').waitFor({ state: 'visible', timeout: 5000 })
+ await loginPage.continueWithEmail()
await loginPage.enterPassword(LOGIN_PASSWORD)
await loginPage.clickLogin()
@@ -142,8 +138,7 @@ test.describe('Auth', () => {
await expect(page).toHaveURL(/\/login/)
await loginPage.enterUsername(workspace!.user_email)
- await page.locator('[data-attr=login-email]').blur()
- await page.locator('[data-attr=password]').waitFor({ state: 'visible', timeout: 5000 })
+ await loginPage.continueWithEmail()
await loginPage.enterPassword(LOGIN_PASSWORD)
await loginPage.clickLogin()
diff --git a/playwright/e2e/signup.spec.ts b/playwright/e2e/signup.spec.ts
index 066bfb837c82..37bf42ce67ff 100644
--- a/playwright/e2e/signup.spec.ts
+++ b/playwright/e2e/signup.spec.ts
@@ -30,11 +30,11 @@ const startSignupFlow = async (page: Page, email: string, password: string): Pro
await expect(page.locator('[data-attr=signup-name]')).toBeVisible()
}
-const submitEmailAndExpectExistingAccount = async (page: Page, email: string): Promise<void> => {
+const submitEmailAndExpectLoginStep = async (page: Page, email: string): Promise<void> => {
await page.locator('[data-attr=signup-email]').fill(email)
await page.locator('[data-attr=signup-start]').click()
- await expect(page.getByText('There is already an account with this email address.')).toBeVisible()
+ await expect(page.locator('[data-attr=password-login]')).toBeVisible()
await expect(page.locator('[data-attr=signup-auth-continue]')).not.toBeVisible()
}
@@ -55,9 +55,9 @@ test.describe('Signup', () => {
await page.goto('/signup')
})
- test('Cannot create account with existing email', async ({ page, request }) => {
+ test('An existing email goes to the login step', async ({ page, request }) => {
await ensureExistingUser(request, '[email protected]')
- await submitEmailAndExpectExistingAccount(page, '[email protected]')
+ await submitEmailAndExpectLoginStep(page, '[email protected]')
})
test('Can create user account with first name, last name and organization name', async ({ page }) => {
@@ -119,8 +119,9 @@ test.describe('Signup', () => {
await expect(page).toHaveURL(/\/verify_email\/[a-zA-Z0-9_.-]*/)
await page.goto('/signup')
- // Try to recreate account with same email- should fail
- await submitEmailAndExpectExistingAccount(page, email)
+ // The same email now has an account, so it goes to the login step instead of signup
+ await submitEmailAndExpectLoginStep(page, email)
+ await page.locator('[data-attr=auth-use-different-email]').click()
// Update email to generic email and retry
const newEmail = `${randomString('new_user')}@posthog.com`
diff --git a/playwright/e2e/two-factor.spec.ts b/playwright/e2e/two-factor.spec.ts
index 6b19d1906271..c8ae7b668981 100644
--- a/playwright/e2e/two-factor.spec.ts
+++ b/playwright/e2e/two-factor.spec.ts
@@ -55,6 +55,7 @@ test.describe('Two-factor authentication', () => {
await test.step('password login lands on the 2FA challenge instead of the app', async () => {
const loginPage = new LoginPage(page)
await loginPage.enterUsername(workspace.user_email)
+ await loginPage.continueWithEmail()
await loginPage.enterPassword(LOGIN_PASSWORD)
await loginPage.clickLogin()
await expect(page.locator('[data-attr=token]')).toBeVisible({ timeout: 15000 })
diff --git a/playwright/page-models/loginPage.ts b/playwright/page-models/loginPage.ts
index 7581423dc8cb..1bb69b944075 100644
--- a/playwright/page-models/loginPage.ts
+++ b/playwright/page-models/loginPage.ts
@@ -7,6 +7,11 @@ export class LoginPage {
await this.page.locator('[data-attr=login-email]').fill(username)
}
+ async continueWithEmail(): Promise<void> {
+ await this.page.locator('[data-attr=login-email-continue]').click()
+ await this.page.locator('[data-attr=password]').waitFor({ state: 'visible', timeout: 5000 })
+ }
+
async enterPassword(password: string): Promise<void> {
await this.page.locator('[data-attr=password]').fill(password)
}
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.py
index 21fca8393d51..d1d51158e426 100644
--- a/posthog/api/authentication.py
+++ b/posthog/api/authentication.py
@@ -525,20 +525,20 @@ class LoginPrecheckSerializer(serializers.Serializer):
@staticmethod
def _available_local_methods(email: str, *, saml_available: bool, oidc_available: bool = False) -> dict[str, Any]:
"""
- Report whether this account can log in with a password, and which of its linked social
- identities are actually usable on this instance, so the login form can stop offering a
- password box (or a dead SSO button) to an account that cannot use it.
+ Report whether an account exists for this email, whether it can log in with a password,
+ and which of its linked social identities are actually usable on this instance.
- An email with no active user looks identical to a user who does have a password — a typo
- must never be a dead end, and it keeps the account-existence signal limited to accounts
- that are genuinely passwordless.
+ The auth page asks for the email first and uses `account_exists` to choose between the
+ login step and the signup step. Signup already refuses an email that has an account, so
+ this tells a caller nothing the signup precheck does not.
"""
# Same lookup login itself uses (`UserManager.get_by_natural_key`), so precheck can never
# describe a different account than the one a password would authenticate: case-insensitive,
- # and deterministic (active first, then last logged in) if case variations coexist.
- user = EmailLookupHandler.get_user_by_email(email)
+ # and deterministic (active first, then last logged in) if case variations coexist. A
+ # deactivated account counts as existing, because signup cannot reuse its email either.
+ user = EmailLookupHandler.get_user_by_email(email, is_active=None)
if user is None:
- return {"password_login_available": True, "social_providers": []}
+ return {"account_exists": False, "password_login_available": True, "social_providers": []}
# Mirrors `UserSerializer.get_has_password`: `has_usable_password()` is True for an empty
# password, so the `bool(...)` half of the check is load-bearing.
@@ -555,6 +555,7 @@ class LoginPrecheckSerializer(serializers.Serializer):
usable_providers.add("oidc")
return {
+ "account_exists": True,
"password_login_available": password_login_available,
"social_providers": sorted(linked_providers & usable_providers),
}
diff --git a/posthog/api/signup.py b/posthog/api/signup.py
index dfa2bcb95646..0975483c647c 100644
--- a/posthog/api/signup.py
+++ b/posthog/api/signup.py
@@ -34,7 +34,12 @@ from posthog.api.webauthn import (
from posthog.email import is_email_available
from posthog.event_usage import alias_invite_id, report_user_joined_organization, report_user_signed_up
from posthog.exceptions_capture import capture_exception
-from posthog.helpers.email_utils import EmailValidationHelper, reject_plus_addressed_email, validate_display_name
+from posthog.helpers.email_utils import (
+ EmailLookupHandler,
+ EmailValidationHelper,
+ reject_plus_addressed_email,
+ validate_display_name,
+)
from posthog.helpers.oauth_pending_connection import (
apply_connector_signup_onboarding_skip,
read_pending_oauth_connection,
@@ -452,9 +457,13 @@ class SignupEmailPrecheckViewset(generics.GenericAPIView):
# Mirror SignupSerializer.validate_email. Without this the form clears the email step,
# the user fills in the rest, and only then hits the rejection on submit.
reject_plus_addressed_email(email)
- email_exists = EmailValidationHelper.user_exists_with_stripped_alias(
- email
- ) or EmailValidationHelper.user_exists_with_gmail_canonical(email)
+ email_exists = (
+ EmailValidationHelper.user_exists_with_stripped_alias(email)
+ or EmailValidationHelper.user_exists_with_gmail_canonical(email)
+ # The alias checks only see active accounts, but the email column is unique across
+ # all of them, so a deactivated account would otherwise fail signup at the last step
+ or EmailLookupHandler.get_user_by_email(email, is_active=None) is not None
+ )
if email_exists:
return response.Response(
{
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index 9761cf92353b..76da48f305a1 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -108,6 +108,7 @@ class TestLoginPrecheckAPI(APIBaseTest):
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
+ "account_exists": False,
"password_login_available": True,
"social_providers": [],
},
@@ -132,6 +133,7 @@ class TestLoginPrecheckAPI(APIBaseTest):
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
+ "account_exists": True,
"password_login_available": True,
"social_providers": [],
},
@@ -268,6 +270,7 @@ class TestLoginPrecheckAPI(APIBaseTest):
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
+ "account_exists": True,
"password_login_available": False,
"social_providers": [],
},
@@ -305,22 +308,30 @@ class TestLoginPrecheckAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["social_providers"], [])
- def test_login_precheck_treats_unknown_email_as_password_login_available(self):
- # An unknown email must be indistinguishable from a user who has a password, so a typo is
- # never a dead end and we don't leak which addresses have accounts.
- response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["password_login_available"], True)
- self.assertEqual(response.json()["social_providers"], [])
-
- def test_login_precheck_treats_inactive_passwordless_user_as_unknown(self):
- user = User.objects.create_and_join(self.organization, "[email protected]", None)
- user.is_active = False
- user.save()
-
- response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+ @parameterized.expand(
+ [
+ ("active", True, True),
+ ("deactivated", False, True),
+ ("unknown", None, False),
+ ]
+ )
+ def test_login_precheck_reports_whether_an_account_exists(
+ self, _name: str, user_is_active: bool | None, expected_account_exists: bool
+ ) -> None:
+ # The auth page sends `account_exists: false` to the signup step. Signup cannot reuse a
+ # deactivated account's email, so that account must route to the login step instead.
+ email = "[email protected]"
+ if user_is_active is not None:
+ user = User.objects.create_and_join(self.organization, email, None)
+ user.is_active = user_is_active
+ user.save()
+
+ response = self.client.post("/api/login/precheck", {"email": email.upper()})
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["password_login_available"], True)
+ self.assertEqual(response.json()["account_exists"], expected_account_exists)
+ if not expected_account_exists:
+ self.assertEqual(response.json()["password_login_available"], True)
+ self.assertEqual(response.json()["social_providers"], [])
def test_login_precheck_is_rate_limited_by_ip(self):
cache.clear()
diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.py
index d49518197e49..8153ba1d8f08 100644
--- a/posthog/api/test/test_signup.py
+++ b/posthog/api/test/test_signup.py
@@ -3513,14 +3513,15 @@ class TestSignupPrecheckPendingInvite(APIBaseTest):
@parameterized.expand(
[
- ("aliased_account", "[email protected]", "[email protected]"),
- ("dotted_gmail_account", "[email protected]", "[email protected]"),
+ ("aliased_account", "[email protected]", "[email protected]", True),
+ ("dotted_gmail_account", "[email protected]", "[email protected]", True),
+ ("deactivated_account", "[email protected]", "[email protected]", False),
]
)
def test_precheck_reports_collision_with_the_same_mailbox(
- self, _name: str, stored_email: str, looked_up_email: str
+ self, _name: str, stored_email: str, looked_up_email: str, is_active: bool
) -> None:
- User.objects.create_user(email=stored_email, password=None, first_name="Dupe")
+ User.objects.create_user(email=stored_email, password=None, first_name="Dupe", is_active=is_active)
response = self.client.post("/api/signup/precheck", {"email": looked_up_email})
self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
self.assertTrue(response.json()["email_exists"])
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index b61924eee76c..b3aa833ddc51 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -402,8 +402,8 @@ class LoginPrecheckThrottle(IPThrottle):
"""
Rate limit login precheck requests by IP.
- The response reveals which sign-in methods a passwordless account has, so cap it per-IP to make
- bulk enumeration expensive. Per-email throttling would be useless here — enumeration uses a
+ The response reveals whether an account exists and which sign-in methods it has, so cap it
+ per-IP to make bulk enumeration expensive. Per-email throttling would be useless here — enumeration uses a
different email on every request.
"""