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.

fix(oauth): let accounts with no organization create one on consent (#129781)

Rafael Audibert434bc553e791
diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx
index 0ba07ce0275a..d151bd3826a1 100644
--- a/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx
+++ b/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx
@@ -100,7 +100,6 @@ const meta: Meta = {
withScopeResolution,
mswDecorator({
get: {
- // The logic loads projects per organization for users that have organizations
'/api/organizations/:organization_id/projects/': {
results: [
{
@@ -110,28 +109,6 @@ const meta: Meta = {
},
],
},
- '/api/projects/': {
- results: [
- {
- id: 1,
- name: 'Default Project',
- organization: {
- id: '1',
- name: 'Default Organization',
- slug: 'default-org',
- },
- },
- {
- id: 2,
- name: 'Analytics Project',
- organization: {
- id: '1',
- name: 'Default Organization',
- slug: 'default-org',
- },
- },
- ],
- },
},
post: {
'/oauth/authorize/': {
@@ -260,3 +237,29 @@ export const EveryScopeRequested: Story = {
return <App />
},
}
+
+export const NoOrganization: Story = {
+ parameters: { testOptions: { snapshotBrowsers: [] } },
+ decorators: [
+ withOAuthApplication({ required_scopes: [] }),
+ mswDecorator({
+ get: {
+ '/api/users/@me/': () => [
+ 200,
+ {
+ uuid: '018e1b6b-0000-0000-0000-000000000002',
+ email: '[email protected]',
+ first_name: 'Test',
+ organization: null,
+ organizations: [],
+ team: null,
+ },
+ ],
+ },
+ }),
+ ],
+ render: () => {
+ useDelayedOnMountEffect(() => pushAuthorize())
+ return <App />
+ },
+}
diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.tsx
index 70e22e4bdecc..fbd1f992b1dd 100644
--- a/frontend/src/scenes/oauth/OAuthAuthorize.tsx
+++ b/frontend/src/scenes/oauth/OAuthAuthorize.tsx
@@ -25,12 +25,21 @@ import { SceneExport } from '../sceneTypes'
import { OAuthAuthorizeLayout } from './OAuthAuthorizeLayout'
import { oauthAuthorizeLogic } from './oauthAuthorizeLogic'
-export const OAuthAuthorizeError = ({ title, description }: { title: string; description: string }): JSX.Element => {
+export const OAuthAuthorizeError = ({
+ title,
+ description,
+ action,
+}: {
+ title: string
+ description: string
+ action?: JSX.Element
+}): JSX.Element => {
return (
<div className="AuthScene__card flex flex-col items-center gap-4 p-8 text-center">
<IconWarning className="text-muted-alt text-4xl" />
<div className="text-xl font-semibold">{title}</div>
<div className="text-sm text-muted">{description}</div>
+ {action}
</div>
)
}
@@ -83,7 +92,7 @@ const InlineCreateForm = ({
placeholder: string
loading: boolean
onSubmit: (name: string) => void
- onCancel: () => void
+ onCancel?: () => void
}): JSX.Element => {
const [name, setName] = useState('')
@@ -103,7 +112,7 @@ const InlineCreateForm = ({
onSubmit(name.trim())
}
if (e.key === 'Escape') {
- onCancel()
+ onCancel?.()
}
}}
disabled={loading}
@@ -117,9 +126,11 @@ const InlineCreateForm = ({
>
Create
</LemonButton>
- <LemonButton type="secondary" size="small" onClick={onCancel} disabled={loading}>
- Cancel
- </LemonButton>
+ {onCancel && (
+ <LemonButton type="secondary" size="small" onClick={onCancel} disabled={loading}>
+ Cancel
+ </LemonButton>
+ )}
</div>
</div>
)
@@ -152,6 +163,7 @@ export const OAuthAuthorize = (): JSX.Element => {
accessControlsApply,
showCreateProject,
newProjectLoading,
+ newOrganizationLoading,
selectedOrganization,
user,
} = useValues(oauthAuthorizeLogic)
@@ -159,6 +171,7 @@ export const OAuthAuthorize = (): JSX.Element => {
cancel,
submitOauthAuthorization,
createNewProject,
+ createNewOrganization,
setShowCreateProject,
setSelectedOrganization,
setOauthAuthorizationValue,
@@ -259,6 +272,39 @@ export const OAuthAuthorize = (): JSX.Element => {
)
}
+ if (user && allOrganizations.length === 0) {
+ return (
+ <OAuthAuthorizeLayout>
+ <OAuthAuthorizeError
+ title="Create an organization to continue"
+ description={`${appName} needs access to a PostHog organization, and your account doesn't belong to one yet. Create one here and PostHog adds a project to it. If your team already uses PostHog, ask an admin to invite you instead.`}
+ action={
+ <div className="w-full flex flex-col items-center gap-2">
+ <div className="w-full text-left" data-attr="oauth-authorize-create-organization">
+ <InlineCreateForm
+ label="Organization name"
+ placeholder="e.g. Acme"
+ loading={newOrganizationLoading}
+ onSubmit={createNewOrganization}
+ />
+ </div>
+ <LemonButton
+ type="tertiary"
+ size="small"
+ onClick={cancel}
+ loading={isCanceling}
+ disabledReason={newOrganizationLoading ? 'Creating the organization' : undefined}
+ data-attr="oauth-authorize-no-organization-cancel"
+ >
+ Cancel and return to {appName}
+ </LemonButton>
+ </div>
+ }
+ />
+ </OAuthAuthorizeLayout>
+ )
+ }
+
return (
<OAuthAuthorizeLayout>
<div className="shrink-0 mb-3">
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
index fe099bc6672d..edf973516232 100644
--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
@@ -1,11 +1,14 @@
import { MOCK_DEFAULT_USER } from 'lib/api.mock'
import { decodeParams, router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { DEFAULT_OAUTH_SCOPES, getScopeGroupLabel, scopeGroupLevel, scopeGroupTooltip } from 'lib/scopes'
import { userLogic } from 'scenes/userLogic'
import { useMocks } from '~/mocks/jest'
+import type { MockSignature } from '~/mocks/utils'
import { initKeaTests } from '~/test/init'
import { AppContext } from '~/types'
@@ -302,6 +305,70 @@ describe('oauthAuthorizeLogic', () => {
expect(logic.values.effectiveScopes).toEqual(['openid', 'insight:write'])
})
+ it('loads an empty project list instead of failing for a user with no organization', async () => {
+ useMocks({
+ get: {
+ '/api/projects/': () => [404, { detail: 'You need to belong to an organization.' }],
+ },
+ })
+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, organization: null, organizations: [] })
+
+ await expectLogic(logic, () => logic.actions.loadAllTeams())
+ .toDispatchActions(['loadAllTeamsSuccess'])
+ .toNotHaveDispatchedActions(['loadAllTeamsFailure'])
+ expect(logic.values.allTeams).toEqual([])
+ })
+
+ it('creates an organization inline and selects its new project for a team-level grant', async () => {
+ const newOrganization = { id: 'new-org', name: 'New org' }
+ const newTeam = { id: 501, organization: newOrganization.id, name: 'Default project' }
+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, organization: null, organizations: [], team: null })
+ logic.actions.setRequiredAccessLevel('team')
+ useMocks({
+ get: {
+ '/api/users/@me/': { ...MOCK_DEFAULT_USER, organizations: [newOrganization], team: newTeam },
+ '/api/organizations/new-org/projects/': { results: [newTeam], next: null },
+ },
+ post: {
+ '/api/organizations/': newOrganization,
+ },
+ })
+
+ await expectLogic(logic, () => logic.actions.createNewOrganization('New org')).toFinishAllListeners()
+
+ expect(logic.values.selectedOrganization).toBe(newOrganization.id)
+ expect(logic.values.oauthAuthorization.scoped_teams).toEqual([newTeam.id])
+ expect(logic.values.newOrganizationLoading).toBe(false)
+ })
+
+ it.each<{ failing: string; get: Record<string, MockSignature> }>([
+ {
+ failing: 'user',
+ get: { '/api/users/@me/': () => [500, { detail: 'Server error' }] },
+ },
+ {
+ failing: 'project',
+ get: {
+ '/api/users/@me/': { ...MOCK_DEFAULT_USER, organizations: [{ id: 'new-org', name: 'New org' }] },
+ '/api/organizations/new-org/projects/': () => [500, { detail: 'Server error' }],
+ },
+ },
+ ])('offers a reload instead of a retry when the $failing refresh fails after creation', async ({ get }) => {
+ const toastError = jest.spyOn(lemonToast, 'error')
+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, organization: null, organizations: [], team: null })
+ useMocks({ get, post: { '/api/organizations/': { id: 'new-org', name: 'New org' } } })
+
+ await expectLogic(logic, () => logic.actions.createNewOrganization('New org')).toFinishAllListeners()
+
+ expect(toastError).toHaveBeenCalledWith(
+ expect.stringContaining('Reload the page'),
+ expect.objectContaining({ button: expect.objectContaining({ label: 'Reload' }) })
+ )
+ expect(userLogic.values.user).not.toBeNull()
+ expect(logic.values.newOrganizationLoading).toBe(false)
+ toastError.mockRestore()
+ })
+
const HINT_TEAMS = [
{ id: 11, organization: 'org-a', name: 'A project' },
{ id: 22, organization: 'org-b', name: 'B project' },
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
index 270ae8166676..4fc49e551471 100644
--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
@@ -6,6 +6,7 @@ import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import api from 'lib/api'
+import { timeSensitiveAuthenticationLogic } from 'lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import {
IDENTITY_SCOPES,
@@ -26,6 +27,8 @@ import { userLogic } from 'scenes/userLogic'
import type { OAuthApplicationPublicMetadata, OrganizationBasicType, TeamBasicType, UserType } from '~/types'
+import { create as createOrganization } from 'products/platform_features/frontend/generated/api'
+
export type OAuthAuthorizationFormValues = {
scoped_organizations: string[]
scoped_teams: number[]
@@ -152,6 +155,7 @@ export interface oauthAuthorizeLogicValues {
isOauthAuthorizationSubmitting: boolean
isOauthAuthorizationValid: boolean
isRedirecting: boolean
+ newOrganizationLoading: boolean
newProjectLoading: boolean
oauthApplication: OAuthApplicationPublicMetadata | null
oauthApplicationLoading: boolean
@@ -186,6 +190,9 @@ export interface oauthAuthorizeLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface oauthAuthorizeLogicActions {
cancel: () => {}
+ createNewOrganization: (name: string) => {
+ name: string
+ }
createNewProject: (name: string) => {
name: string
}
@@ -237,6 +244,9 @@ export interface oauthAuthorizeLogicActions {
setIsMcpResource: (isMcpResource: boolean) => {
isMcpResource: boolean
}
+ setNewOrganizationLoading: (loading: boolean) => {
+ loading: boolean
+ }
setNewProjectLoading: (loading: boolean) => {
loading: boolean
}
@@ -391,6 +401,8 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
setShowCreateProject: (show: boolean) => ({ show }),
createNewProject: (name: string) => ({ name }),
setNewProjectLoading: (loading: boolean) => ({ loading }),
+ createNewOrganization: (name: string) => ({ name }),
+ setNewOrganizationLoading: (loading: boolean) => ({ loading }),
}),
loaders({
allTeams: [
@@ -399,8 +411,9 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
loadAllTeams: async () => {
const user = userLogic.values.user
if (!user?.organizations?.length) {
- // 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.
- return await api.loadPaginatedResults('api/projects')
+ // Without an organization there are no projects to list, and `api/projects`
+ // would 404 because it resolves the current organization.
+ return []
}
const results = await Promise.all(
user.organizations.map((org) =>
@@ -443,6 +456,47 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
actions.setCanceling(false)
}
},
+ createNewOrganization: async ({ name }) => {
+ actions.setNewOrganizationLoading(true)
+ try {
+ await timeSensitiveAuthenticationLogic.findMounted()?.asyncActions.checkReauthentication()
+ const previousUser = userLogic.values.user
+ // The backend creates a default project with the organization and makes both current.
+ // nosemgrep: prefer-codegen-api -- False positive: this is the generated create() from products/platform_features/frontend/generated/api, which semgrep resolves to api.create because the module is named api.
+ const organization = await createOrganization({ name })
+ // The loaders below report their own failures and resolve anyway. A retry here would
+ // create a second organization, so offer a reload, which keeps the authorize URL.
+ const showReloadToast = (): void => {
+ lemonToast.error(
+ "Your organization was created, but it couldn't be loaded. Reload the page to continue.",
+ {
+ button: { label: 'Reload', action: () => window.location.reload() },
+ }
+ )
+ }
+ await userLogic.asyncActions.loadUser()
+ if (!userLogic.values.user) {
+ // A failed loadUser sets the user to null, which hides this screen.
+ if (previousUser) {
+ userLogic.actions.loadUserSuccess(previousUser)
+ }
+ showReloadToast()
+ return
+ }
+ await oauthAuthorizeLogic.asyncActions.loadAllTeams()
+ if (!values.allTeams?.some((team) => team.organization === organization.id)) {
+ showReloadToast()
+ return
+ }
+ if (values.requiredAccessLevel === 'team') {
+ actions.setSelectedOrganization(organization.id, userLogic.values.user?.team?.id)
+ }
+ } catch (e: any) {
+ lemonToast.error(e.detail || "Couldn't create the organization. Try again.")
+ } finally {
+ actions.setNewOrganizationLoading(false)
+ }
+ },
createNewProject: async ({ name }) => {
actions.setNewProjectLoading(true)
try {
@@ -570,6 +624,12 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
setNewProjectLoading: (_, { loading }) => loading,
},
],
+ newOrganizationLoading: [
+ false,
+ {
+ setNewOrganizationLoading: (_, { loading }) => loading,
+ },
+ ],
}),
listeners(({ actions, values }) => ({
setRequiredAccessLevel: ({ requiredAccessLevel }) => {
diff --git a/frontend/src/scenes/sceneLogic.test.tsx b/frontend/src/scenes/sceneLogic.test.tsx
index c6be286a7d3b..d260008672d4 100644
--- a/frontend/src/scenes/sceneLogic.test.tsx
+++ b/frontend/src/scenes/sceneLogic.test.tsx
@@ -73,6 +73,7 @@ const testScenes: Record<string, () => any> = {
[Scene.AIObservabilityOfflineExperiments]: sceneImport,
[Scene.Billing]: sceneImport,
[Scene.DataManagement]: sceneImport,
+ [Scene.OAuthAuthorize]: sceneImport,
[Scene.OrganizationCreateFirst]: sceneImport,
[Scene.OrganizationDeactivated]: sceneImport,
[Scene.OrganizationPendingDeletion]: sceneImport,
@@ -495,33 +496,56 @@ describe('sceneLogic', () => {
expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(resetLink)
})
+ const setUpUserWithoutOrganization = (): void => organizationLogic.actions.loadCurrentOrganizationSuccess(null)
+ const setUpUserWithoutProjects = (): void => {
+ userLogic.actions.loadUserSuccess({
+ ...MOCK_DEFAULT_USER,
+ organization: { ...MOCK_DEFAULT_ORGANIZATION, teams: [] },
+ })
+ teamLogic.actions.loadCurrentTeamSuccess(null)
+ }
+
it.each([
- ['without an organization', (): void => organizationLogic.actions.loadCurrentOrganizationSuccess(null)],
+ [
+ 'without an organization',
+ 'agentic',
+ setUpUserWithoutOrganization,
+ urls.agenticAuthorize(),
+ Scene.AgenticAuthorize,
+ ],
[
'whose organization has no projects',
- (): void => {
- userLogic.actions.loadUserSuccess({
- ...MOCK_DEFAULT_USER,
- organization: { ...MOCK_DEFAULT_ORGANIZATION, teams: [] },
- })
- teamLogic.actions.loadCurrentTeamSuccess(null)
- },
+ 'agentic',
+ setUpUserWithoutProjects,
+ urls.agenticAuthorize(),
+ Scene.AgenticAuthorize,
],
- ])('keeps a signed-in user %s on the agentic consent page', async (_label, setUpUser) => {
- setUpUser()
- const originalPath = window.location.pathname
- // openScene reads window.location, which the test router's memory history never moves.
- window.history.replaceState(null, '', urls.agenticAuthorize())
- try {
- router.actions.push(urls.agenticAuthorize())
- await expectLogic(logic).delay(1)
+ ['without an organization', 'OAuth', setUpUserWithoutOrganization, urls.oauthAuthorize(), Scene.OAuthAuthorize],
+ [
+ 'whose organization has no projects',
+ 'OAuth',
+ setUpUserWithoutProjects,
+ urls.oauthAuthorize(),
+ Scene.OAuthAuthorize,
+ ],
+ ])(
+ 'keeps a signed-in user %s on the %s consent page',
+ async (_label, _page, setUpUser, consentPath, consentScene) => {
+ setUpUser()
+ const originalPath = window.location.pathname
+ // openScene reads window.location, which the test router's memory history never moves.
+ window.history.replaceState(null, '', consentPath)
+ try {
+ router.actions.push(consentPath)
+ await expectLogic(logic).delay(1)
- expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(urls.agenticAuthorize())
- expect(logic.values.sceneId).toEqual(Scene.AgenticAuthorize)
- } finally {
- window.history.replaceState(null, '', originalPath)
+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(consentPath)
+ expect(logic.values.sceneId).toEqual(consentScene)
+ } finally {
+ window.history.replaceState(null, '', originalPath)
+ }
}
- })
+ )
it('persists the loaded scenes', async () => {
const expectedAnnotation = partial({
diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsx
index 4cde412d9ee6..b3a2d1eb43fa 100644
--- a/frontend/src/scenes/sceneLogic.tsx
+++ b/frontend/src/scenes/sceneLogic.tsx
@@ -996,14 +996,17 @@ export const sceneLogic = kea<sceneLogicType>([
}
if (sceneId !== Scene.InviteSignup) {
+ // The agentic and OAuth consent pages pick or create the organization and project
+ // they use, so approving there must not require either first.
+ const isConsentPage =
+ location.pathname.startsWith(urls.agenticAuthorize()) ||
+ location.pathname.startsWith(urls.oauthAuthorize())
// Redirect to org/project creation if there's no org/project respectively, unless using invite
if (organizationLogic.values.isCurrentOrganizationUnavailable) {
if (
location.pathname !== urls.organizationCreateFirst() &&
!location.pathname.startsWith(urls.settings('user')) &&
- // The agentic consent page picks or creates the organization and project
- // it uses, so approving there must not require either first.
- !location.pathname.startsWith(urls.agenticAuthorize())
+ !isConsentPage
) {
console.warn('Organization not available, redirecting to organization creation')
router.actions.replace(urls.organizationCreateFirst())
@@ -1019,7 +1022,7 @@ export const sceneLogic = kea<sceneLogicType>([
if (
location.pathname !== urls.projectCreateFirst() &&
!location.pathname.startsWith('/settings') &&
- !location.pathname.startsWith(urls.agenticAuthorize())
+ !isConsentPage
) {
console.warn(
'Project not available and no other projects, redirecting to project creation'