:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { redirectAfterLogin } from 'lib/utils/loginRedirect'
import { urls } from 'scenes/urls'
export interface DevUser {
email: string
first_name: string
is_staff: boolean
label: string | null
last_login: string | null
}
export interface DevOAuthConnector {
client_id: string
client_name: string
logo_uri: string | null
redirect_host: string | null
authorize_path: string
}
export interface DevLoginOptions {
users: DevUser[]
oauth_connectors?: DevOAuthConnector[]
}
export const DEV_LOGIN_SECONDS_SAVED_PER_CLICK = 5
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface devLoginLogicValues {
createFreshAccountLoading: boolean
devLoginCount: number
devLoginOptions: DevLoginOptions
devLoginOptionsLoading: boolean
devLoginPanelOpen: boolean
devLoginTimeSavedLabel: string | null
devOAuthConnectors: DevOAuthConnector[]
devUsers: DevUser[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface devLoginLogicActions {
clearPendingOAuthConnection: () => {
value: true
}
createFreshAccount: () => {
value: true
}
createFreshAccountFailure: (error: string) => {
error: string
}
createFreshAccountSuccess: () => {
value: true
}
devLogin: (email: string) => {
email: string
}
loadDevLoginOptions: (_: any) => any
loadDevLoginOptionsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadDevLoginOptionsSuccess: (
devLoginOptions: DevLoginOptions,
payload?: any
) => {
devLoginOptions: DevLoginOptions
payload?: any
}
setDevLoginPanelOpen: (open: boolean) => {
open: boolean
}
startPendingOAuthConnection: (connector: DevOAuthConnector) => {
connector: DevOAuthConnector
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface devLoginLogicMeta {
__keaTypeGenInternalSelectorTypes: {
devUsers: (devLoginOptions: DevLoginOptions) => DevUser[]
devOAuthConnectors: (devLoginOptions: DevLoginOptions) => DevOAuthConnector[]
devLoginTimeSavedLabel: (devLoginCount: number) => string | null
}
}
export type devLoginLogicType = MakeLogicType<
devLoginLogicValues,
devLoginLogicActions,
Record<string, any>,
devLoginLogicMeta
>
export const devLoginLogic = kea<devLoginLogicType>([
path(['scenes', 'authentication', 'shared', 'devLoginLogic']),
actions({
devLogin: (email: string) => ({ email }),
createFreshAccount: true,
createFreshAccountSuccess: true,
createFreshAccountFailure: (error: string) => ({ error }),
setDevLoginPanelOpen: (open: boolean) => ({ open }),
clearPendingOAuthConnection: true,
startPendingOAuthConnection: (connector: DevOAuthConnector) => ({ connector }),
}),
reducers({
devLoginCount: [
0,
{ persist: true },
{
devLogin: (count) => count + 1,
},
],
// Open out of the box — the panel is the fastest way into a local instance. Persisted so
// that closing it sticks for anyone who'd rather type credentials.
devLoginPanelOpen: [
true,
{ persist: true },
{
setDevLoginPanelOpen: (_, { open }) => open,
},
],
createFreshAccountLoading: [
false,
{
createFreshAccount: () => true,
createFreshAccountSuccess: () => false,
createFreshAccountFailure: () => false,
},
],
}),
loaders(() => ({
devLoginOptions: [
{ users: [] } as DevLoginOptions,
{
// Not fired on an `onMount` because we don't always need it. The whole list comes
// down in one go — this only ever runs against a local instance.
loadDevLoginOptions: async (_, breakpoint) => {
breakpoint()
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.get<DevLoginOptions>('api/login/dev')
breakpoint()
return response
} catch {
// Endpoint is unavailable unless allow_dev_login is set in preflight.
return { users: [] }
}
},
},
],
})),
selectors(() => ({
devUsers: [(s) => [s.devLoginOptions], (devLoginOptions: DevLoginOptions): DevUser[] => devLoginOptions.users],
devOAuthConnectors: [
(s) => [s.devLoginOptions],
(devLoginOptions: DevLoginOptions): DevOAuthConnector[] => devLoginOptions.oauth_connectors ?? [],
],
devLoginTimeSavedLabel: [
(s) => [s.devLoginCount],
(devLoginCount: number): 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.`
},
],
})),
listeners(({ actions }) => ({
clearPendingOAuthConnection: async () => {
// Dynamic import: loginLogic, which the boot path loads, imports this logic, and the
// pending connection logic pulls in an HTML entity decoder that /login does not need
const { PENDING_OAUTH_CONNECTION_COOKIE, pendingOAuthConnectionLogic } =
await import('./pendingOAuthConnectionLogic')
// Locally the backend sets the cookie on the request host with no `Domain`, so a
// host-only deletion on `/` matches it
document.cookie = `${PENDING_OAUTH_CONNECTION_COOKIE}=; Max-Age=0; path=/`
pendingOAuthConnectionLogic.findMounted()?.actions.clearPendingConnection()
},
startPendingOAuthConnection: async ({ connector }) => {
const { PENDING_OAUTH_CONNECTION_COOKIE, pendingOAuthConnectionLogic } =
await import('./pendingOAuthConnectionLogic')
const payload = {
client_name: connector.client_name,
client_id: connector.client_id,
logo_uri: connector.logo_uri ?? undefined,
redirect_host: connector.redirect_host ?? undefined,
}
// Matches the backend's encoding and one-hour lifetime (posthog/helpers/oauth_pending_connection.py)
document.cookie = `${PENDING_OAUTH_CONNECTION_COOKIE}=${encodeURIComponent(JSON.stringify(payload))}; Max-Age=3600; path=/; SameSite=Lax`
pendingOAuthConnectionLogic.findMounted()?.actions.setPendingConnection({
clientName: connector.client_name,
clientId: connector.client_id,
logoUri: connector.logo_uri,
redirectHost: connector.redirect_host,
})
const { pathname } = router.values.location
const authPath = pathname === urls.signup() ? urls.signup() : urls.login()
router.actions.push(authPath, { next: connector.authorize_path })
},
devLogin: async ({ email }) => {
// Dynamic import to avoid a circular dependency: loginLogic statically imports this logic.
const { loginLogic } = 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.
await api.create<any>('api/login/dev', { email })
} catch (e) {
const { code, detail } = e as Record<string, any>
loginLogic.actions.setGeneralError(code || 'dev_login_failed', detail || 'Dev login failed')
return
}
redirectAfterLogin()
},
createFreshAccount: async () => {
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.
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'
},
})),
])