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): add dev fresh-account creation, collapse and cap login tools (#74957)

Fernando Gomes5f5a9dcc5b75
diff --git a/frontend/src/scenes/authentication/shared/devLoginLogic.ts b/frontend/src/scenes/authentication/shared/devLoginLogic.ts
index be472988a90e..9af059d3d4ce 100644
--- a/frontend/src/scenes/authentication/shared/devLoginLogic.ts
+++ b/frontend/src/scenes/authentication/shared/devLoginLogic.ts
@@ -2,6 +2,7 @@ import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } fro
import { loaders } from 'kea-loaders'
import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
export interface DevUser {
email: string
@@ -15,6 +16,7 @@ export const DEV_LOGIN_DEFAULT_EMAIL = '[email protected]'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface devLoginLogicValues {
+ createFreshAccountLoading: boolean
devLoginCount: number
devLoginTimeSavedLabel: string | null
devUsers: DevUser[]
@@ -23,6 +25,15 @@ export interface devLoginLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface devLoginLogicActions {
+ createFreshAccount: () => {
+ value: true
+ }
+ createFreshAccountFailure: (error: string) => {
+ error: string
+ }
+ createFreshAccountSuccess: () => {
+ value: true
+ }
devLogin: (email: string) => {
email: string
}
@@ -61,6 +72,9 @@ export const devLoginLogic = kea<devLoginLogicType>([
path(['scenes', 'authentication', 'shared', 'devLoginLogic']),
actions({
devLogin: (email: string) => ({ email }),
+ createFreshAccount: true,
+ createFreshAccountSuccess: true,
+ createFreshAccountFailure: (error: string) => ({ error }),
}),
reducers({
devLoginCount: [
@@ -70,6 +84,14 @@ export const devLoginLogic = kea<devLoginLogicType>([
devLogin: (count) => count + 1,
},
],
+ createFreshAccountLoading: [
+ false,
+ {
+ createFreshAccount: () => true,
+ createFreshAccountSuccess: () => false,
+ createFreshAccountFailure: () => false,
+ },
+ ],
}),
loaders(() => ({
devUsers: [
@@ -115,7 +137,7 @@ export const devLoginLogic = kea<devLoginLogicType>([
},
],
})),
- listeners(() => ({
+ listeners(({ actions }) => ({
devLogin: async ({ email }) => {
// Dynamic import to avoid a circular dependency: loginLogic statically imports this logic.
const { loginLogic, handleLoginRedirect } = await import('scenes/authentication/login/loginLogic')
@@ -130,5 +152,17 @@ export const devLoginLogic = kea<devLoginLogicType>([
handleLoginRedirect()
window.location.reload()
},
+ createFreshAccount: async () => {
+ try {
+ await api.create<any>('api/login/dev', { create_fresh_account: true })
+ } catch (e) {
+ actions.createFreshAccountFailure((e as Record<string, any>).detail || 'Failed to create account')
+ lemonToast.error('Failed to create fresh account')
+ return
+ }
+ actions.createFreshAccountSuccess()
+ // Fresh accounts always land on onboarding; skip login redirect handling.
+ window.location.href = '/onboarding'
+ },
})),
])
diff --git a/frontend/src/scenes/authentication/shared/paperDesk/DevLoginPanel.tsx b/frontend/src/scenes/authentication/shared/paperDesk/DevLoginPanel.tsx
index 3739751db3bc..11db01c4c9e5 100644
--- a/frontend/src/scenes/authentication/shared/paperDesk/DevLoginPanel.tsx
+++ b/frontend/src/scenes/authentication/shared/paperDesk/DevLoginPanel.tsx
@@ -10,23 +10,27 @@ import { Region } from '~/types'
import { devLoginLogic } from '../devLoginLogic'
+// The panel holds a scrollable list of dev users that can grow very long locally,
+// so cap it to roughly half the viewport height (minus the fixed sections).
+const DEV_USERS_LIST_MAX_HEIGHT = 'max-h-[45vh]'
+
/** Floating dev-only panel (top-right) combining dev-login shortcuts and OAuth prod-data login. */
export function DevLoginPanel(): JSX.Element | null {
const { preflight } = useValues(preflightLogic)
- const { devUsers, devUsersLoading } = useValues(devLoginLogic)
- const { devLogin, loadDevUsers } = useActions(devLoginLogic)
+ const { devUsers, devUsersLoading, createFreshAccountLoading } = useValues(devLoginLogic)
+ const { devLogin, loadDevUsers, createFreshAccount } = useActions(devLoginLogic)
const { loginInProgress } = useValues(oauthLogic)
const { beginLogin } = useActions(oauthLogic)
- const [open, setOpen] = useState(true)
+ const [open, setOpen] = useState(false)
const isDebug = !!preflight?.is_debug
const allowDevLogin = !!preflight?.allow_dev_login
useEffect(() => {
- if (allowDevLogin) {
+ if (allowDevLogin && open) {
loadDevUsers(null)
}
- }, [allowDevLogin, loadDevUsers])
+ }, [allowDevLogin, open, loadDevUsers])
if (!isDebug) {
return null
@@ -37,57 +41,80 @@ export function DevLoginPanel(): JSX.Element | null {
return (
<div className="fixed top-4 right-4 z-50">
{open ? (
- <div className="w-64 bg-white border rounded shadow p-3">
+ <div className={`w-64 bg-white border rounded shadow p-3 flex flex-col ${DEV_USERS_LIST_MAX_HEIGHT}`}>
<div className="flex items-center justify-between mb-3">
<span className="text-xs font-semibold text-muted">Login tools</span>
<button type="button" className="text-muted" onClick={() => setOpen(false)} aria-label="Close">
✕
</button>
</div>
- {showDevLogin && (
- <div className="mb-4">
- <p className="text-xs font-medium text-muted mb-1.5">Login as</p>
+ <div className="flex-1 overflow-y-auto min-h-0">
+ {showDevLogin && (
+ <div className="mb-4">
+ <p className="text-xs font-medium text-muted mb-1.5">Login as</p>
+ <div className="flex flex-col gap-1">
+ {devUsers.map((u) => (
+ <button
+ key={u.email}
+ type="button"
+ onClick={() => devLogin(u.email)}
+ data-attr={`dev-login-${u.email}`}
+ className="flex items-center gap-2 w-full text-left px-2.5 py-1.5 rounded border border-border bg-bg-light hover:border-accent hover:bg-accent-highlight transition-colors"
+ >
+ <span className="flex-1 truncate text-xs">{u.email}</span>
+ {u.label && <span className="text-xs text-muted">{u.label}</span>}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ {showDevLogin && <div className="border-t border-border my-3" />}
+ {allowDevLogin && (
+ <div className="mb-4">
+ <p className="text-xs font-medium text-muted mb-1.5">Onboarding testing</p>
+ <button
+ type="button"
+ disabled={createFreshAccountLoading}
+ onClick={createFreshAccount}
+ data-attr="dev-create-fresh-account"
+ className="flex items-center gap-2 w-full text-left px-2.5 py-1.5 rounded border border-border bg-bg-light hover:border-accent hover:bg-accent-highlight disabled:opacity-50 disabled:hover:border-border disabled:hover:bg-bg-light transition-colors"
+ >
+ <span className="flex-1 text-xs">
+ {createFreshAccountLoading
+ ? 'Creating account…'
+ : 'Create fresh account & start onboarding'}
+ </span>
+ </button>
+ <p className="text-xs text-muted mt-1">
+ Random account + org (password: 12345678), lands you straight in onboarding.
+ </p>
+ </div>
+ )}
+ <div>
+ <p className="text-xs font-medium text-muted mb-1.5">Login via OAuth</p>
<div className="flex flex-col gap-1">
- {devUsers.map((u) => (
- <button
- key={u.email}
- type="button"
- onClick={() => devLogin(u.email)}
- data-attr={`dev-login-${u.email}`}
- className="flex items-center gap-2 w-full text-left px-2.5 py-1.5 rounded border border-border bg-bg-light hover:border-accent hover:bg-accent-highlight transition-colors"
- >
- <span className="flex-1 truncate text-xs">{u.email}</span>
- {u.label && <span className="text-xs text-muted">{u.label}</span>}
- </button>
- ))}
+ <button
+ type="button"
+ disabled={loginInProgress}
+ onClick={() => beginLogin(Region.US)}
+ data-attr="dev-oauth-us"
+ className="flex items-center gap-2 w-full text-left px-2.5 py-1.5 rounded border border-border bg-bg-light hover:border-accent hover:bg-accent-highlight disabled:opacity-50 disabled:hover:border-border disabled:hover:bg-bg-light transition-colors"
+ >
+ <span className="text-base leading-none">{OAUTH_REGIONS[Region.US].flag}</span>
+ <span className="text-xs">US Cloud</span>
+ </button>
+ <button
+ type="button"
+ disabled={loginInProgress}
+ onClick={() => beginLogin(Region.EU)}
+ data-attr="dev-oauth-eu"
+ className="flex items-center gap-2 w-full text-left px-2.5 py-1.5 rounded border border-border bg-bg-light hover:border-accent hover:bg-accent-highlight disabled:opacity-50 disabled:hover:border-border disabled:hover:bg-bg-light transition-colors"
+ >
+ <span className="text-base leading-none">{OAUTH_REGIONS[Region.EU].flag}</span>
+ <span className="text-xs">EU Cloud</span>
+ </button>
</div>
</div>
- )}
- {showDevLogin && <div className="border-t border-border my-3" />}
- <div>
- <p className="text-xs font-medium text-muted mb-1.5">Login via OAuth</p>
- <div className="flex flex-col gap-1">
- <button
- type="button"
- disabled={loginInProgress}
- onClick={() => beginLogin(Region.US)}
- data-attr="dev-oauth-us"
- className="flex items-center gap-2 w-full text-left px-2.5 py-1.5 rounded border border-border bg-bg-light hover:border-accent hover:bg-accent-highlight disabled:opacity-50 disabled:hover:border-border disabled:hover:bg-bg-light transition-colors"
- >
- <span className="text-base leading-none">{OAUTH_REGIONS[Region.US].flag}</span>
- <span className="text-xs">US Cloud</span>
- </button>
- <button
- type="button"
- disabled={loginInProgress}
- onClick={() => beginLogin(Region.EU)}
- data-attr="dev-oauth-eu"
- className="flex items-center gap-2 w-full text-left px-2.5 py-1.5 rounded border border-border bg-bg-light hover:border-accent hover:bg-accent-highlight disabled:opacity-50 disabled:hover:border-border disabled:hover:bg-bg-light transition-colors"
- >
- <span className="text-base leading-none">{OAUTH_REGIONS[Region.EU].flag}</span>
- <span className="text-xs">EU Cloud</span>
- </button>
- </div>
</div>
</div>
) : (
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.py
index 1d7d69399ef7..fd10535372e9 100644
--- a/posthog/api/authentication.py
+++ b/posthog/api/authentication.py
@@ -1,6 +1,7 @@
import re
import json
import time
+import random
import datetime
import unicodedata
from typing import Any, TypedDict, cast
@@ -455,19 +456,89 @@ DEV_LOGIN_KNOWN_EMAIL_LABELS = {
"[email protected]": "Default test user",
}
+# Name pools for dev-login fresh account creation, so test accounts are easy to
+# tell apart in the login tools list.
+DEV_ACCOUNT_FIRST_NAMES = [
+ "Ada",
+ "Byron",
+ "Cleo",
+ "Dorian",
+ "Edith",
+ "Felix",
+ "Greta",
+ "Hugo",
+ "Iris",
+ "Jonas",
+ "Kira",
+ "Linus",
+ "Mira",
+ "Nico",
+ "Opal",
+ "Pablo",
+ "Quinn",
+ "Rosa",
+ "Silas",
+ "Tessa",
+]
+
+DEV_ACCOUNT_ORGANIZATION_NAMES = [
+ "Acme Analytics",
+ "Bluebird Labs",
+ "Cindercone Systems",
+ "Driftwood Data",
+ "Ember Metrics",
+ "Ferrous Works",
+ "Glimmer Grove",
+ "Halcyon House",
+ "Ironwood Insights",
+ "Juniper Junction",
+ "Kestrel Kollective",
+ "Lumen Loft",
+ "Marble & Moss",
+ "Northlight Co.",
+ "Obsidian Oak",
+ "Pinnacle Patch",
+ "Quartz Quarry",
+ "Riverstone Research",
+ "Solstice Software",
+ "Timberline Tools",
+]
+
class DevLoginSerializer(serializers.Serializer):
email = serializers.EmailField(
+ required=False,
write_only=True,
help_text="Email of the active user to log in as. Only honored when dev login is allowed (DEBUG and ALLOW_DEV_LOGIN).",
)
+ create_fresh_account = serializers.BooleanField(
+ required=False,
+ default=False,
+ write_only=True,
+ help_text="Create a fresh account/org with random names (password: 12345678) and log in directly, without signup. Only honored when dev login is allowed.",
+ )
def to_representation(self, instance: Any) -> dict[str, Any]:
return {"success": True}
- def create(self, validated_data: dict[str, str]) -> Any:
+ def validate(self, data: dict[str, Any]) -> dict[str, Any]:
+ # Gate first, before any field-level validation: when dev login is disabled the
+ # endpoint must look nonexistent (404) regardless of the request body, so a
+ # missing-email 400 can't leak that the route exists.
if not is_dev_login_allowed():
raise Http404()
+ if not data.get("create_fresh_account") and not data.get("email"):
+ raise serializers.ValidationError(
+ {"email": serializers.ErrorDetail("This field is required.", code="required")}
+ )
+ return data
+
+ def create(self, validated_data: dict[str, Any]) -> Any:
+ if not is_dev_login_allowed():
+ raise Http404()
+
+ if validated_data.get("create_fresh_account"):
+ return self._create_fresh_account()
request = self.context["request"]
try:
@@ -481,6 +552,27 @@ class DevLoginSerializer(serializers.Serializer):
report_user_logged_in(user, social_provider="")
return user
+ def _create_fresh_account(self) -> Any:
+ first_name = random.choice(DEV_ACCOUNT_FIRST_NAMES)
+ email = f"{first_name.lower()}-{uuid4().hex[:8]}@posthog.dev"
+ organization_name = random.choice(DEV_ACCOUNT_ORGANIZATION_NAMES)
+
+ with transaction.atomic():
+ _, _, user = User.objects.bootstrap(
+ organization_name=organization_name,
+ email=email,
+ password="12345678",
+ first_name=first_name,
+ is_email_verified=True,
+ )
+
+ request = self.context["request"]
+ login(request, user, backend="django.contrib.auth.backends.ModelBackend")
+ request.session["reauth"] = "false"
+ request.session.save()
+ report_user_logged_in(user, social_provider="")
+ return user
+
class DevLoginViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):
"""
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index 979c6f2c899b..00599c7870c7 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -448,6 +448,41 @@ class TestDevLoginAPI(APIBaseTest):
response = self.client.post("/api/login/dev", {"email": self.user.email})
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ @override_settings(DEBUG=True, ALLOW_DEV_LOGIN=True)
+ def test_dev_login_create_fresh_account(self):
+ user_count = User.objects.count()
+ organization_count = Organization.objects.count()
+
+ response = self.client.post("/api/login/dev", {"create_fresh_account": True})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"success": True})
+
+ self.assertEqual(User.objects.count(), user_count + 1)
+ self.assertEqual(Organization.objects.count(), organization_count + 1)
+
+ new_user = User.objects.latest("id")
+ self.assertTrue(new_user.is_email_verified)
+ self.assertTrue(new_user.check_password("12345678"))
+ self.assertIsNotNone(new_user.organization)
+
+ # Logged in as the fresh user
+ response = self.client.get("/api/users/@me")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["email"], new_user.email)
+
+ @override_settings(DEBUG=True, ALLOW_DEV_LOGIN=False)
+ def test_dev_login_create_fresh_account_hidden_when_not_allowed(self):
+ response = self.client.post("/api/login/dev", {"create_fresh_account": True})
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ @override_settings(DEBUG=True, ALLOW_DEV_LOGIN=False)
+ def test_dev_login_disabled_returns_404_regardless_of_body(self):
+ # A body that would normally fail field validation (no email, no
+ # create_fresh_account) must still surface as 404, not a 400, so the
+ # endpoint's existence isn't leaked by request-shape differences.
+ response = self.client.post("/api/login/dev", {})
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
@override_settings(DEBUG=False, ALLOW_DEV_LOGIN=True)
def test_dev_login_hidden_when_not_debug(self):
response = self.client.get("/api/login/dev")