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(login): add dev-only one-click login UI (#59127)

Rafael Audiberte960bb42dcc6
diff --git a/.env.development b/.env.development
index ed32d209cfa1..bedc04cb1093 100644
--- a/.env.development
+++ b/.env.development
@@ -8,6 +8,7 @@
# Core
DEBUG=1
+ALLOW_DEV_LOGIN=1
SKIP_SERVICE_VERSION_REQUIREMENTS=1
# Object storage (host-side only — container endpoint is in .env.services)
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5307829bac8d..a053540e9ccd 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5479,9 +5479,9 @@ snapshots:
scenes-app-settings-organization--settings-organization-members--light:
hash: v1.k794b7964.5b4183e801fc106d0df5f41e0a21b513a86906f468f92236658f46a0cef8ac24.8u6wWHEalzC08AtritFBefYGmF-KWD0DyY6fY96rk1Y
scenes-app-settings-organization--settings-organization-proxy--dark:
- hash: v1.k794b7964.66fb57201253606ddd7e95e686889327007341a84f2ba6636562d7cec9a57996.VdWe17vV4LDDiORUTUEbeFQ7J6zm7G-pI3nwW8E9SGI
+ hash: v1.k794b7964.90a8a61debda46387820db39b004cda666a0e36e91df08a8163d95699550f945.r1Pn-9cIaBGsPPwOcQAALbBHMTNnMccOoORNBULaZWo
scenes-app-settings-organization--settings-organization-proxy--light:
- hash: v1.k794b7964.2f5d7bf68070e65cc1d03341f3b8430135ef5d85836a2e155e7c5109d010d18d.QwG-WvpdPzeBN9HwxIgCcvovVnzb2byi8d-wHUSMtxg
+ hash: v1.k794b7964.e2d4c2449c7d39d7bf12145fbc26bc388b7e95c1f5aea5a9e7c39d744fe00004.51TaFuYH7Ov0yCmbxtj72Nx0_zY-88n0zU3goHtkNK4
scenes-app-settings-organization--settings-organization-roles--dark:
hash: v1.k794b7964.b16569f8b5cac7752273a09c69f183b9fe4f23670f29b835830ab6f27be4e709.IpNJ8c__GdbETkiqPjxvFbpyvZKDoFXgra4-EywdBh8
scenes-app-settings-organization--settings-organization-roles--light:
diff --git a/frontend/src/mocks/fixtures/_preflight.json b/frontend/src/mocks/fixtures/_preflight.json
index aa5420f4e164..276be72c68f5 100644
--- a/frontend/src/mocks/fixtures/_preflight.json
+++ b/frontend/src/mocks/fixtures/_preflight.json
@@ -464,6 +464,7 @@
},
"opt_out_capture": false,
"is_debug": true,
+ "allow_dev_login": false,
"licensed_users_available": 21311,
"site_url": "http://localhost:6006",
"instance_preferences": {
diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.ts
index 74e0084b8b4c..2854f84854f3 100644
--- a/frontend/src/mocks/handlers.ts
+++ b/frontend/src/mocks/handlers.ts
@@ -184,6 +184,12 @@ export const defaultMocks: Mocks = {
'/api/projects/:team_id/comments/count': { count: 0 },
'/api/projects/:team_id/comments': { results: [] },
'/_preflight': require('./fixtures/_preflight.json'),
+ '/api/login/dev': {
+ users: [
+ { email: '[email protected]', is_staff: true, label: 'Default test user' },
+ { email: '[email protected]', is_staff: true, label: null },
+ ],
+ },
'/_system_status': require('./fixtures/_system_status.json'),
'/api/instance_status': require('./fixtures/_instance_status.json'),
// TODO: Add a real mock once we know why this endpoint returns an error inside a 200 response
diff --git a/frontend/src/scenes/authentication/Login.tsx b/frontend/src/scenes/authentication/Login.tsx
index 9dac1fc25caf..032e4a17bfb3 100644
--- a/frontend/src/scenes/authentication/Login.tsx
+++ b/frontend/src/scenes/authentication/Login.tsx
@@ -5,7 +5,7 @@ import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
import { useEffect, useRef } from 'react'
-import { LemonButton, LemonInput } from '@posthog/lemon-ui'
+import { LemonButton, LemonInput, LemonTag } from '@posthog/lemon-ui'
import { getCookie } from 'lib/api'
import { SSOEnforcedLoginButton, SocialLoginButtons } from 'lib/components/SocialLoginButton/SocialLoginButton'
@@ -14,6 +14,7 @@ import { usePrevious } from 'lib/hooks/usePrevious'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { Link } from 'lib/lemon-ui/Link'
+import { Skeleton } from 'lib/ui/quill'
import { isEmail } from 'lib/utils'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { SceneExport } from 'scenes/sceneTypes'
@@ -72,7 +73,7 @@ export const scene: SceneExport = {
}
export function Login(): JSX.Element {
- const { precheck, resendEmailMFA, clearGeneralError, resetLogin } = useActions(loginLogic)
+ const { precheck, resendEmailMFA, clearGeneralError, resetLogin, devLogin, loadDevUsers } = useActions(loginLogic)
const { openSupportForm } = useActions(supportLogic)
const {
precheckResponse,
@@ -82,8 +83,18 @@ export function Login(): JSX.Element {
generalError,
signupUrl,
resendResponseLoading,
+ devUsers,
+ devUsersLoading,
+ devLoginTimeSavedLabel,
} = useValues(loginLogic)
const { preflight } = useValues(preflightLogic)
+ const allowDevLogin = !!preflight?.allow_dev_login
+
+ useEffect(() => {
+ if (allowDevLogin) {
+ loadDevUsers(null)
+ }
+ }, [allowDevLogin, loadDevUsers])
const passwordInputRef = useRef<HTMLInputElement>(null)
const preventPasswordError = useRef(false)
@@ -297,6 +308,45 @@ export function Login(): JSX.Element {
showPasskey
/>
)}
+ {allowDevLogin && (
+ <div className="deprecated-space-y-2 border-t border-dashed pt-4 mt-4">
+ <div className="flex items-center justify-between">
+ <h4 className="m-0">Dev login</h4>
+ </div>
+ <p className="text-muted text-sm m-0">
+ Click a user to log in without a password. This list is only exposed in development mode.
+ </p>
+ {!devUsersLoading && devLoginTimeSavedLabel && (
+ <p className="text-muted text-sm m-0">{devLoginTimeSavedLabel}</p>
+ )}
+ {devUsersLoading && <Skeleton className="w-full h-10" />}
+ <div className="deprecated-space-y-1">
+ {devUsers.map((u) => (
+ <LemonButton
+ key={u.email}
+ type="secondary"
+ fullWidth
+ data-attr={`dev-login-${u.email}`}
+ onClick={() => devLogin(u.email)}
+ >
+ <span className="flex items-center gap-2 w-full">
+ <span className="flex-1 text-left truncate">{u.email}</span>
+ {u.label && (
+ <LemonTag type="success" size="small">
+ {u.label}
+ </LemonTag>
+ )}
+ {u.is_staff && !u.label && (
+ <LemonTag type="default" size="small">
+ Staff
+ </LemonTag>
+ )}
+ </span>
+ </LemonButton>
+ ))}
+ </div>
+ </div>
+ )}
</div>
</AuthShell>
)
diff --git a/frontend/src/scenes/authentication/loginLogic.ts b/frontend/src/scenes/authentication/loginLogic.ts
index 0dc782d4e921..79ae8cc3de09 100644
--- a/frontend/src/scenes/authentication/loginLogic.ts
+++ b/frontend/src/scenes/authentication/loginLogic.ts
@@ -30,6 +30,14 @@ export interface PrecheckResponseType {
webauthn_credentials?: PublicKeyCredentialDescriptorJSON[]
}
+export interface DevUser {
+ email: string
+ is_staff: boolean
+ label: string | null
+}
+
+export const DEV_LOGIN_SECONDS_SAVED_PER_CLICK = 5
+
// Routes that should be handled by Django, not the React router
const BACKEND_ONLY_ROUTES = [
'/login/vercel/continue',
@@ -80,6 +88,7 @@ export const loginLogic = kea<loginLogicType>([
actions({
setGeneralError: (code: string, detail: string) => ({ code, detail }),
clearGeneralError: true,
+ devLogin: (email: string) => ({ email }),
}),
reducers({
// This is separate from the login form, so that the form can be submitted even if a general error is present
@@ -90,6 +99,13 @@ export const loginLogic = kea<loginLogicType>([
clearGeneralError: () => null,
},
],
+ devLoginCount: [
+ 0,
+ { persist: true },
+ {
+ devLogin: (count) => count + 1,
+ },
+ ],
}),
loaders(() => ({
precheckResponse: [
@@ -113,6 +129,22 @@ export const loginLogic = kea<loginLogicType>([
},
},
],
+ devUsers: [
+ [] as DevUser[],
+ {
+ // Not fired on an `onMount` because we don't always need it.
+ loadDevUsers: async (_, breakpoint) => {
+ breakpoint()
+ try {
+ const response = await api.get<{ users: DevUser[] }>('api/login/dev')
+ return response.users
+ } catch {
+ // Endpoint is unavailable unless allow_dev_login is set in preflight.
+ return []
+ }
+ },
+ },
+ ],
resendResponse: [
null as { success: boolean; message: string } | null,
{
@@ -143,6 +175,24 @@ export const loginLogic = kea<loginLogicType>([
return nextParam ? `/signup?next=${encodeURIComponent(nextParam)}` : '/signup'
},
],
+ devLoginTimeSavedLabel: [
+ (s) => [s.devLoginCount],
+ (devLoginCount): string | null => {
+ if (devLoginCount === 0) {
+ return null
+ }
+
+ const totalSeconds = devLoginCount * DEV_LOGIN_SECONDS_SAVED_PER_CLICK
+ if (totalSeconds < 60) {
+ const unit = totalSeconds === 1 ? 'second' : 'seconds'
+ return `You've saved ${totalSeconds} ${unit} by clicking this button.`
+ }
+
+ const minutes = Math.floor(totalSeconds / 60)
+ const unit = minutes === 1 ? 'minute' : 'minutes'
+ return `You've saved ${minutes} ${unit} by clicking this button.`
+ },
+ ],
})),
forms(({ actions, values }) => ({
login: {
@@ -190,12 +240,24 @@ export const loginLogic = kea<loginLogicType>([
},
},
})),
- listeners(({ values }) => ({
+ listeners(({ actions, values }) => ({
submitLoginSuccess: () => {
handleLoginRedirect()
// Reload the page after login to ensure POSTHOG_APP_CONTEXT is set correctly.
window.location.reload()
},
+ devLogin: async ({ email }) => {
+ actions.clearGeneralError()
+ try {
+ await api.create<any>('api/login/dev', { email })
+ } catch (e) {
+ const { code, detail } = e as Record<string, any>
+ actions.setGeneralError(code || 'dev_login_failed', detail || 'Dev login failed')
+ return
+ }
+ handleLoginRedirect()
+ window.location.reload()
+ },
precheckSuccess: async (_, breakpoint) => {
const { precheckResponse } = values
// Auto-trigger passkey prompt if user has passkeys and SSO is not enforced
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 22f397c29cef..88df352e320e 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4305,6 +4305,8 @@ export interface PreflightStatus {
}
/** Whether PostHog is running in settings.DEBUG or settings.E2E_TESTING. */
is_debug?: boolean
+ /** Whether one-click dev login is enabled (DEBUG and ALLOW_DEV_LOGIN). */
+ allow_dev_login?: boolean
/** Whether PostHog is running with settings.TEST. */
is_test?: boolean
licensed_users_available?: number | null
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index b9b359b54d78..24d68642dc6a 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -760,6 +760,7 @@ organizations_router.register(
# General endpoints (shared across CH & PG)
router.register(r"login", authentication.LoginViewSet, "login")
+router.register(r"login/dev", authentication.DevLoginViewSet, "login_dev")
router.register(r"login/token", authentication.TwoFactorViewSet, "login_token")
router.register(r"login/precheck", authentication.LoginPrecheckViewSet, "login_precheck")
router.register(r"login/email-mfa", authentication.EmailMFAViewSet, "login_email_mfa")
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.py
index a3857e2cf228..2fef8161c3aa 100644
--- a/posthog/api/authentication.py
+++ b/posthog/api/authentication.py
@@ -19,7 +19,7 @@ from django.core.exceptions import ValidationError
from django.core.signing import BadSignature
from django.db import transaction
from django.dispatch import receiver
-from django.http import HttpRequest, HttpResponse, JsonResponse
+from django.http import Http404, HttpRequest, HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.utils import timezone
from django.utils.http import url_has_allowed_host_and_scheme
@@ -52,6 +52,7 @@ from posthog.email import is_email_available
from posthog.event_usage import report_user_logged_in, report_user_password_reset
from posthog.exceptions_capture import capture_exception
from posthog.geoip import get_geoip_properties
+from posthog.helpers.dev_login import is_dev_login_allowed
from posthog.helpers.two_factor_session import (
_obfuscate_token,
clear_two_factor_session_flags,
@@ -447,6 +448,61 @@ class LoginViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):
raise
+# Known good emails seeded by setup_dev / generate_demo_data so the frontend can
+# label them. Anything else is shown without a label.
+DEV_LOGIN_KNOWN_EMAIL_LABELS = {
+ "[email protected]": "Default test user",
+}
+
+
+class DevLoginSerializer(serializers.Serializer):
+ email = serializers.EmailField(
+ 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).",
+ )
+
+ def to_representation(self, instance: Any) -> dict[str, Any]:
+ return {"success": True}
+
+ def create(self, validated_data: dict[str, str]) -> Any:
+ if not is_dev_login_allowed():
+ raise Http404()
+
+ request = self.context["request"]
+ try:
+ user = User.objects.get(email__iexact=validated_data["email"], is_active=True)
+ except User.DoesNotExist:
+ raise serializers.ValidationError("User not found", code="user_not_found")
+
+ 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):
+ """
+ Dev-only convenience endpoint. Lists active users and lets the login UI
+ one-click sign in as any of them without a password. Returns 404 unless
+ both DEBUG and ALLOW_DEV_LOGIN are enabled.
+ """
+
+ queryset = User.objects.none()
+ serializer_class = DevLoginSerializer
+ permission_classes = (permissions.AllowAny,)
+
+ def list(self, request: Request) -> Response:
+ if not is_dev_login_allowed():
+ raise Http404()
+
+ users = list(User.objects.filter(is_active=True).order_by("email").values("email", "is_staff")[:50])
+ for entry in users:
+ entry["label"] = DEV_LOGIN_KNOWN_EMAIL_LABELS.get(entry["email"])
+
+ return Response({"users": users})
+
+
class TwoFactorSerializer(serializers.Serializer):
token = serializers.CharField(write_only=True)
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index b05925e03979..79730693c101 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -396,6 +396,35 @@ class TestLoginAPI(APIBaseTest):
self.assertNotEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+class TestDevLoginAPI(APIBaseTest):
+ CONFIG_AUTO_LOGIN = False
+
+ @override_settings(DEBUG=True, ALLOW_DEV_LOGIN=True)
+ def test_dev_login_list_and_create_when_allowed(self):
+ response = self.client.get("/api/login/dev")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ emails = {user["email"] for user in response.json()["users"]}
+ self.assertIn(self.user.email, emails)
+
+ self.client.logout()
+ response = self.client.post("/api/login/dev", {"email": self.user.email})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"success": True})
+
+ @override_settings(DEBUG=True, ALLOW_DEV_LOGIN=False)
+ def test_dev_login_hidden_when_allow_dev_login_disabled(self):
+ response = self.client.get("/api/login/dev")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ response = self.client.post("/api/login/dev", {"email": self.user.email})
+ 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")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+
class TestLogoutRedirect(APIBaseTest):
"""
Tests that /logout preserves a safe `next` param so users return to where they were
diff --git a/posthog/api/test/test_preflight.py b/posthog/api/test/test_preflight.py
index 2e6128a356ff..274e4110cb5f 100644
--- a/posthog/api/test/test_preflight.py
+++ b/posthog/api/test/test_preflight.py
@@ -6,11 +6,13 @@ import pytest
from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_queries
from unittest.mock import patch
+from django.test import override_settings
from django.utils import timezone
from rest_framework import status
from posthog.cloud_utils import TEST_clear_instance_license_cache
+from posthog.helpers.dev_login import is_dev_login_allowed
from posthog.models.instance_setting import set_instance_setting
from posthog.models.organization import Organization
from posthog.models.organization_invite import OrganizationInvite
@@ -340,3 +342,18 @@ class TestPreflight(APIBaseTest, QueryMatchingTest):
"available": True,
"client_id": "client-id",
}
+
+ @override_settings(DEBUG=True, ALLOW_DEV_LOGIN=True)
+ def test_preflight_includes_allow_dev_login_when_enabled(self):
+ with self.is_cloud(False):
+ response = self.client.get("/_preflight/")
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["allow_dev_login"] is True
+ assert is_dev_login_allowed()
+
+ @override_settings(DEBUG=True, ALLOW_DEV_LOGIN=False)
+ def test_preflight_omits_allow_dev_login_when_disabled(self):
+ with self.is_cloud(False):
+ response = self.client.get("/_preflight/")
+ assert response.status_code == status.HTTP_200_OK
+ assert "allow_dev_login" not in response.json()
diff --git a/posthog/helpers/dev_login.py b/posthog/helpers/dev_login.py
new file mode 100644
index 000000000000..116e8ba3ebc4
--- /dev/null
+++ b/posthog/helpers/dev_login.py
@@ -0,0 +1,5 @@
+from django.conf import settings
+
+
+def is_dev_login_allowed() -> bool:
+ return settings.DEBUG and settings.ALLOW_DEV_LOGIN
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index ad7632e62d6b..fe64d2553a0a 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -684,6 +684,9 @@ PRESTOP_MARKER_FILE = get_from_env("PRESTOP_MARKER_FILE", "/tmp/posthog_prestop"
# disables frontend side navigation hooks to make hot-reload work seamlessly
DEV_DISABLE_NAVIGATION_HOOKS = get_from_env("DEV_DISABLE_NAVIGATION_HOOKS", False, type_cast=bool)
+# one-click passwordless login on the login page (also requires DEBUG)
+ALLOW_DEV_LOGIN = get_from_env("ALLOW_DEV_LOGIN", False, type_cast=str_to_bool)
+
####
# Random/temporary
# Everything that is supposed to be removed eventually
diff --git a/posthog/views.py b/posthog/views.py
index d569cee476ee..509ea29261a8 100644
--- a/posthog/views.py
+++ b/posthog/views.py
@@ -30,6 +30,7 @@ from posthog.cloud_utils import is_cloud
from posthog.email import is_email_available
from posthog.exceptions_capture import capture_exception
from posthog.health import is_clickhouse_connected
+from posthog.helpers.dev_login import is_dev_login_allowed
from posthog.models import Organization, User
from posthog.models.activity_logging.activity_log import Detail, log_activity
from posthog.models.integration import SlackIntegration
@@ -233,6 +234,9 @@ def preflight_check(request: HttpRequest) -> JsonResponse:
if settings.DEBUG or settings.E2E_TESTING:
response["is_debug"] = True
+ if is_dev_login_allowed():
+ response["allow_dev_login"] = True
+
if settings.TEST:
response["is_test"] = True