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: review public resources during offboarding (#123674)

Alex Lider35ebaa42fcd9
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 981a1512fae8..86563e03ebc3 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -15650,6 +15650,14 @@ snapshots:
hash: v1.k794b7964.125683bfe67f38e8705abf402d5dc17fa355dcde157e710e6daad85fcb20c02e.tbzNEa9x9B-PU_UNEPOo_dbiVJhxDnFAwzBgH3ka36g
scenes-app-settings-organization--settings-organization-startup-program--light:
hash: v1.k794b7964.a7050dc508b37c55eba7ba4cb783a4567e0fff3cab6924ce3ca79ebb07664e79.moDmbGJ1e6J9sEvpXxnMKAsIi8rTMxsH9b_IWAaWCWE
+ scenes-app-settings-organization-member-offboarding--no-resources--dark:
+ hash: v1.k794b7964.d2feb6e0abcdf2a80e53fc9ef2c654ae59371898447d11098a34a28cc828396b.LTgmr0g4aUgaG8KmbEmRDxt8SDyIzAgIejRrTMQdfKk
+ scenes-app-settings-organization-member-offboarding--no-resources--light:
+ hash: v1.k794b7964.5858a7f6b0058141bee9134870d3438e8564148e3ac5c2ae2879c551a60ea6cf.xFY9ivLhVV1pKN5UWMjkzXHzhaYFapC3vvRtwtsqro4
+ scenes-app-settings-organization-member-offboarding--review-resources--dark:
+ hash: v1.k794b7964.6fb1e231bc80b3e7acfbed6c74ec8389130af9860c74f8ef0a28c79fc4ee3c1d.5-3-pH2WXIujOvfIFAuUm0OypDZjpijwHj5t-kD6-pI
+ scenes-app-settings-organization-member-offboarding--review-resources--light:
+ hash: v1.k794b7964.cad1e4793a60815a10dd8f59d2d9badea8e1803cfce936c074172125f2bc1966.4Te9lMFGEdCWGqE87pLrBPKYyH7Ehe9KnWrQxdP9v1M
scenes-app-settings-project--settings-project-access-control--dark:
hash: v1.k794b7964.7554b77bd6b1d3fdc411385eff866e2fb0e442e33459268f37d116561aaa50c0.tNvJl7_UinwSpilEuRCVIkSFxqIAQY4x5_6QfXAm0hM
scenes-app-settings-project--settings-project-access-control--light:
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 7f89b48235a7..55ec8f09dd68 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -3760,22 +3760,24 @@ const api = {
insightId,
recordingId,
notebookShortId,
+ teamId,
}: {
dashboardId?: DashboardType['id']
insightId?: InsightModel['id']
recordingId?: SessionRecordingType['id']
notebookShortId?: NotebookType['short_id']
+ teamId?: TeamType['id']
},
data: Partial<SharingConfigurationType>
): Promise<SharingConfigurationType | null> {
return dashboardId
- ? new ApiRequest().dashboardSharing(dashboardId).update({ data })
+ ? new ApiRequest().dashboardSharing(dashboardId, teamId).update({ data })
: insightId
- ? new ApiRequest().insightSharing(insightId).update({ data })
+ ? new ApiRequest().insightSharing(insightId, teamId).update({ data })
: recordingId
- ? new ApiRequest().recordingSharing(recordingId).update({ data })
+ ? new ApiRequest().recordingSharing(recordingId, teamId).update({ data })
: notebookShortId
- ? new ApiRequest().notebookSharing(notebookShortId).update({ data })
+ ? new ApiRequest().notebookSharing(notebookShortId, teamId).update({ data })
: null
},
diff --git a/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx
index e58d984eb90d..922af4693cf3 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx
@@ -19,11 +19,8 @@ export function BulkSelectionBar<T extends Record<string, any>, K extends BulkSe
const isOpen = context.selectedCount > 0
const [singular, plural] = noun
const word = context.selectedCount === 1 ? singular : plural
- const summary = (
- <span className="text-secondary text-sm">
- {context.selectedCount} {word} selected
- </span>
- )
+ const selectionLabel = config.getSelectionLabel?.(context) ?? `${context.selectedCount} ${word} selected`
+ const summary = <span className="text-secondary text-sm">{selectionLabel}</span>
const clearButton = (
<LemonButton type="secondary" size="small" onClick={context.clearSelection}>
Clear
diff --git a/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts
index aa15a8f7676b..fe0e170a343b 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts
+++ b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts
@@ -34,6 +34,7 @@ export interface BulkSelectionConfig<T extends Record<string, any>, K extends Bu
headerAriaLabel?: string
/** Singular/plural noun used in "N items selected". Defaults to ['item', 'items']. */
noun?: [string, string]
+ getSelectionLabel?: (ctx: BulkSelectionContext<T, K>) => string
/** Initial selection (uncontrolled). Read once on mount; later changes are ignored.
* Useful for stories and test scaffolds that want to render the bar pre-populated. */
initialSelectedKeys?: ReadonlyArray<K>
diff --git a/frontend/src/models/membersLogic.tsx b/frontend/src/models/membersLogic.tsx
index 70569583c990..b960fa136aef 100644
--- a/frontend/src/models/membersLogic.tsx
+++ b/frontend/src/models/membersLogic.tsx
@@ -173,21 +173,6 @@ export interface membersLogicActions {
postRemoveMember: (userUuid: string) => {
userUuid: string
}
- removeMember: (member: OrganizationMemberType) => OrganizationMemberType
- removeMemberFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- removeMemberSuccess: (
- members: OrganizationMemberType[] | null,
- payload?: OrganizationMemberType
- ) => {
- members: OrganizationMemberType[] | null
- payload?: OrganizationMemberType
- }
setSearch: (search: any) => {
search: any
}
@@ -242,7 +227,7 @@ export const membersLogic = kea<membersLogicType>([
}),
postRemoveMember: (userUuid: string) => ({ userUuid }),
}),
- loaders(({ values, actions }) => ({
+ loaders(({ values }) => ({
members: {
__default: null as OrganizationMemberType[] | null,
loadAllMembers: async () => {
@@ -275,16 +260,6 @@ export const membersLogic = kea<membersLogicType>([
return members
},
- removeMember: async (member: OrganizationMemberType) => {
- await api.organizationMembers.delete(member.user.uuid)
- lemonToast.success(
- <>
- Removed <b>{member.user.first_name}</b> from organization
- </>
- )
- actions.postRemoveMember(member.user.uuid)
- return values.members?.filter((thisMember) => thisMember.user.id !== member.user.id) ?? null
- },
changeMemberAccessLevel: async ({ member, level }) => {
const updatedMember = await api.organizationMembers.update(member.user.uuid, { level })
lemonToast.success(
@@ -338,6 +313,13 @@ export const membersLogic = kea<membersLogicType>([
},
})),
reducers({
+ members: [
+ null as OrganizationMemberType[] | null,
+ {
+ postRemoveMember: (state, { userUuid }) =>
+ state?.filter((member) => member.user.uuid !== userUuid) ?? null,
+ },
+ ],
search: ['', { setSearch: (_, { search }) => search }],
}),
selectors({
diff --git a/frontend/src/scenes/settings/organization/MemberOffboardingModal.stories.tsx b/frontend/src/scenes/settings/organization/MemberOffboardingModal.stories.tsx
new file mode 100644
index 000000000000..97c49f8b9223
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/MemberOffboardingModal.stories.tsx
@@ -0,0 +1,117 @@
+import { MOCK_SECOND_ORGANIZATION_MEMBER } from 'lib/api.mock'
+
+import type { Meta, StoryObj } from '@storybook/react'
+import { waitFor } from '@testing-library/react'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import { memberOffboardingLogic } from './memberOffboardingLogic'
+import { MemberOffboardingModal } from './MemberOffboardingModal'
+
+const resources = [
+ {
+ id: 'public_link:dashboard:1:4',
+ resource_id: '4',
+ kind: 'dashboard',
+ name: 'Product adoption',
+ url: '/project/1/dashboard/4',
+ password_protected: true,
+ team_id: 1,
+ project_name: 'Website',
+ },
+ {
+ id: 'public_link:dashboard:2:5',
+ resource_id: '5',
+ kind: 'dashboard',
+ name: 'Growth overview',
+ url: '/project/2/dashboard/5',
+ password_protected: false,
+ team_id: 2,
+ project_name: 'App',
+ },
+ {
+ id: 'public_link:dashboard:1:1',
+ resource_id: '1',
+ kind: 'dashboard',
+ name: 'Product overview',
+ url: '/project/1/dashboard/1',
+ password_protected: false,
+ team_id: 1,
+ project_name: 'Website',
+ },
+ {
+ id: 'public_link:insight:1:2',
+ resource_id: '2',
+ kind: 'insight',
+ name: 'Weekly acquisition',
+ url: '/project/1/insights/trends01',
+ password_protected: true,
+ team_id: 1,
+ project_name: 'Website',
+ },
+ {
+ id: 'public_link:notebook:2:3',
+ resource_id: 'analysis',
+ kind: 'notebook',
+ name: 'Acquisition analysis',
+ url: '/project/2/notebooks/analysis',
+ password_protected: true,
+ team_id: 2,
+ project_name: 'App',
+ },
+]
+
+async function openMemberOffboarding(): Promise<void> {
+ await waitFor(() => {
+ if (!memberOffboardingLogic.isMounted()) {
+ throw new Error('Waiting for member offboarding to mount')
+ }
+ })
+ memberOffboardingLogic.actions.open(MOCK_SECOND_ORGANIZATION_MEMBER)
+}
+
+const meta: Meta<typeof MemberOffboardingModal> = {
+ title: 'Scenes-App/Settings/Organization/Member offboarding',
+ component: MemberOffboardingModal,
+ parameters: {
+ testOptions: { snapshotTargetSelector: '.LemonModal' },
+ },
+ decorators: [
+ mswDecorator({
+ patch: {
+ '/api/projects/:project/:kind/:resource/sharing/': () => [204, null],
+ },
+ get: {
+ '/api/organizations/:organizationId/members/:userUuid/offboarding_preview/': resources,
+ '/api/organizations/:organizationId/members/:userUuid/scoped_api_keys/': { has_keys: false, keys: [] },
+ },
+ }),
+ ],
+ play: async () => {
+ await openMemberOffboarding()
+ const logic = memberOffboardingLogic
+ await waitFor(() => {
+ if (!logic.values.resources?.length) {
+ throw new Error(logic.values.loadError || 'Waiting for resource review')
+ }
+ })
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof meta>
+export const ReviewResources: Story = {}
+export const NoResources: Story = {
+ decorators: [
+ mswDecorator({ get: { '/api/organizations/:organizationId/members/:userUuid/offboarding_preview/': [] } }),
+ ],
+ play: async () => {
+ await openMemberOffboarding()
+ const logic = memberOffboardingLogic
+ await waitFor(() => {
+ if (logic.values.resourcesLoading || logic.values.resources === null) {
+ throw new Error(logic.values.loadError || 'Waiting for resource review')
+ }
+ })
+ },
+}
diff --git a/frontend/src/scenes/settings/organization/MemberOffboardingModal.tsx b/frontend/src/scenes/settings/organization/MemberOffboardingModal.tsx
new file mode 100644
index 000000000000..ae4324410a6a
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/MemberOffboardingModal.tsx
@@ -0,0 +1,226 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { IconDashboard, IconGraph, IconLock, IconNotebook, IconRewindPlay } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonSkeleton, LemonSwitch, LemonTable } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { Link } from 'lib/lemon-ui/Link'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { fullNameOrEmail } from 'lib/utils/strings'
+import { userLogic } from 'scenes/userLogic'
+
+import { membersLogic } from '~/models/membersLogic'
+
+import { memberOffboardingLogic } from './memberOffboardingLogic'
+
+const RESOURCE_ICONS = {
+ dashboard: <IconDashboard />,
+ insight: <IconGraph />,
+ notebook: <IconNotebook />,
+ recording: <IconRewindPlay />,
+}
+
+export function MemberOffboardingModal(): JSX.Element {
+ const [bulkBarTarget, setBulkBarTarget] = useState<HTMLDivElement | null>(null)
+ const {
+ member,
+ resources,
+ resourcesLoading,
+ loadError,
+ keep,
+ removedLoading,
+ savingResourcesLoading,
+ savingResourceIds,
+ getSelectionLabel,
+ } = useValues(memberOffboardingLogic)
+ const { close, loadResources, setKeep, disableResources, remove } = useActions(memberOffboardingLogic)
+ const { scopedApiKeys, scopedApiKeysLoading } = useValues(membersLogic)
+ const { user } = useValues(userLogic)
+ const isSelf = member?.user.uuid === user?.uuid
+ const disabledReason = removedLoading ? 'Removing member…' : savingResourcesLoading ? 'Saving changes…' : undefined
+ const hasResources = !resourcesLoading && !loadError && !!resources?.length
+
+ return (
+ <LemonModal
+ isOpen={!!member}
+ onClose={disabledReason ? undefined : close}
+ title={
+ isSelf
+ ? 'Leave organization?'
+ : `Remove ${member ? fullNameOrEmail(member.user) : 'member'} from organization?`
+ }
+ width={hasResources ? 720 : 576}
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={close} disabledReason={disabledReason}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ status="danger"
+ loading={removedLoading}
+ disabledReason={disabledReason || (resourcesLoading ? 'Checking public resources…' : undefined)}
+ onClick={remove}
+ data-attr="confirm-org-member-offboarding"
+ >
+ {isSelf ? 'Leave' : 'Remove'}
+ </LemonButton>
+ </>
+ }
+ >
+ <p>
+ {isSelf
+ ? 'Are you sure you want to leave this organization? This cannot be undone. If you leave, you will no longer have access to this organization.'
+ : 'The user will no longer have access to this organization.'}
+ </p>
+ {resourcesLoading ? (
+ <LemonSkeleton className="h-12" />
+ ) : loadError ? (
+ <LemonBanner type="warning" action={{ children: 'Retry', onClick: loadResources }}>
+ Couldn't load public resources. You can still remove the member. Their public links will stay
+ unchanged.
+ </LemonBanner>
+ ) : hasResources ? (
+ <section className="space-y-3">
+ <h3>Publicly shared resources</h3>
+ <p>
+ These resources were shared by this member and are accessible to anyone with the link. You can
+ disable public sharing. This won't delete them.
+ </p>
+ {!isSelf && (
+ <div className="relative h-9">
+ <div ref={setBulkBarTarget} className="absolute inset-0 [&:not(:empty)+span]:hidden" />
+ <span className="flex h-full items-center text-secondary text-sm">
+ {getSelectionLabel(resources!.map((resource) => resource.id))}
+ </span>
+ </div>
+ )}
+ <LemonTable
+ dataSource={resources ?? []}
+ rowKey="id"
+ bulkSelection={
+ isSelf
+ ? undefined
+ : {
+ getKey: (resource) => resource.id,
+ noun: ['resource', 'resources'],
+ rowAriaLabel: (resource) => `Select ${resource.name}`,
+ headerAriaLabel: 'Select all resources on this page',
+ clearSelectionKey: member?.user.uuid,
+ isRowSelectable: () => (disabledReason ? { disabledReason } : true),
+ barPortalTarget: bulkBarTarget,
+ actionsPlacement: 'start',
+ barClassName: 'justify-start! px-0! [&>span]:min-w-0 [&>span]:truncate',
+ getSelectionLabel: ({ selectedKeys }) => getSelectionLabel(selectedKeys),
+ renderActions: (ctx) => (
+ <LemonButton
+ type="secondary"
+ status="danger"
+ size="small"
+ loading={savingResourceIds.length > 0}
+ disabledReason={disabledReason}
+ onClick={() => {
+ disableResources([...ctx.selectedKeys])
+ ctx.clearSelection()
+ }}
+ >
+ Disable selected
+ </LemonButton>
+ ),
+ }
+ }
+ pagination={resources!.length > 5 ? { pageSize: 5 } : undefined}
+ columns={[
+ {
+ title: 'Resource name',
+ key: 'name',
+ render: (_, resource) => (
+ <div className="flex items-center gap-2 min-w-0">
+ <span
+ className="text-lg text-secondary shrink-0"
+ role="img"
+ aria-label={resource.kind}
+ title={resource.kind}
+ >
+ {RESOURCE_ICONS[resource.kind]}
+ </span>
+ <Link
+ to={resource.url ?? undefined}
+ target="_blank"
+ targetBlankIcon={false}
+ className="break-words min-w-0"
+ data-attr="offboarding-resource-link"
+ >
+ {resource.name}
+ </Link>
+ </div>
+ ),
+ },
+ {
+ title: 'Project',
+ dataIndex: 'project_name',
+ key: 'project',
+ width: 124,
+ render: (name) => <span className="break-words">{name}</span>,
+ },
+ ...(!isSelf
+ ? [
+ {
+ title: 'Publicly shared',
+ key: 'disable',
+ width: 112,
+ render: (_: unknown, resource: NonNullable<typeof resources>[number]) => (
+ <div className="flex items-center gap-2">
+ <LemonSwitch
+ loading={savingResourceIds.includes(resource.id)}
+ checked={keep.includes(resource.id)}
+ onChange={(enabled) => setKeep(resource.id, enabled)}
+ disabledReason={disabledReason}
+ aria-label={`Public sharing for ${resource.name}`}
+ data-attr="offboarding-disable-dashboard"
+ />
+ {resource.password_protected && (
+ <Tooltip title="Password protected">
+ <span
+ className="flex text-secondary"
+ role="img"
+ aria-label="Password protected"
+ >
+ <IconLock />
+ </span>
+ </Tooltip>
+ )}
+ </div>
+ ),
+ },
+ ]
+ : []),
+ ]}
+ />
+ </section>
+ ) : null}
+ {!scopedApiKeysLoading && !!scopedApiKeys?.keys.length && (
+ <div className="mt-4">
+ <LemonBanner type="warning" className="mb-2">
+ The following personal API keys will lose access to this organization and will stop working
+ immediately. Check any services that depend on them before continuing.
+ </LemonBanner>
+ <LemonTable
+ dataSource={scopedApiKeys.keys}
+ columns={[
+ { title: 'Name', dataIndex: 'name', key: 'name' },
+ {
+ title: 'Last used',
+ dataIndex: 'last_used_at',
+ key: 'last_used_at',
+ render: (lastUsed) => (lastUsed ? <TZLabel time={lastUsed} /> : 'Never'),
+ },
+ ]}
+ />
+ </div>
+ )}
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/settings/organization/Members.tsx b/frontend/src/scenes/settings/organization/Members.tsx
index 518f6f78c193..19f8aee9cb02 100644
--- a/frontend/src/scenes/settings/organization/Members.tsx
+++ b/frontend/src/scenes/settings/organization/Members.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
import { IconInfo } from '@posthog/icons'
-import { LemonBanner, LemonInput, LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'
+import { LemonInput, LemonSkeleton, LemonSwitch } from '@posthog/lemon-ui'
import { projectDataFreshnessLogic } from 'lib/components/Account/projectDataFreshnessLogic'
import { PayGateMini } from 'lib/components/PayGateMini/PayGateMini'
@@ -33,55 +33,17 @@ import { userLogic } from 'scenes/userLogic'
import { membersLogic } from '~/models/membersLogic'
import { AvailableFeature, OrganizationMemberType } from '~/types'
+import { memberOffboardingLogic } from './memberOffboardingLogic'
+import { MemberOffboardingModal } from './MemberOffboardingModal'
import { accessibleProjects, orderByActivity } from './memberProjectAccess'
import { memberProjectAccessLogic } from './memberProjectAccessLogic'
import { MemberProjectAccessModal } from './MemberProjectAccessModal'
-function RemoveMemberModal({ member }: { member: OrganizationMemberType }): JSX.Element {
- const { user } = useValues(userLogic)
- const { scopedApiKeys } = useValues(membersLogic)
-
- return (
- <div className="max-w-xl">
- <p>
- {member.user.uuid === user?.uuid
- ? 'Are you sure you want to leave this organization? This cannot be undone. If you leave, you will no longer have access to this organization.'
- : 'Are you sure you want to remove this member? This cannot be undone. They will no longer have access to this organization.'}
- </p>
- {scopedApiKeys?.keys && scopedApiKeys.keys.length > 0 && (
- <div className="mt-4">
- <LemonBanner type="warning" className="mb-2">
- The following personal API keys which belong to{' '}
- {member.user.uuid == user?.uuid ? 'you' : 'this member'} will lose access to this organization
- and will stop working immediately. Please confirm they will not affect any services that depend
- on them before removing {member.user.uuid == user?.uuid ? 'yourself' : 'this member'}.
- </LemonBanner>
- <LemonTable
- dataSource={scopedApiKeys.keys}
- columns={[
- {
- title: 'Name',
- dataIndex: 'name',
- key: 'name',
- },
- {
- title: 'Last used',
- dataIndex: 'last_used_at',
- key: 'last_used_at',
- render: (last_used_at) => (last_used_at ? <TZLabel time={last_used_at} /> : 'Never'),
- },
- ]}
- />
- </div>
- )}
- </div>
- )
-}
-
function ActionsComponent(_: any, member: OrganizationMemberType): JSX.Element | null {
const { user } = useValues(userLogic)
const { currentOrganization } = useValues(organizationLogic)
- const { removeMember, changeMemberAccessLevel, loadMemberScopedApiKeys } = useActions(membersLogic)
+ const { changeMemberAccessLevel } = useActions(membersLogic)
+ const { open: openOffboarding } = useActions(memberOffboardingLogic)
const { openProjectAccessModal } = useActions(memberProjectAccessLogic)
if (!user) {
@@ -160,28 +122,7 @@ function ActionsComponent(_: any, member: OrganizationMemberType): JSX.Element |
<LemonButton
status="danger"
data-attr="delete-org-membership"
- onClick={() => {
- if (!user) {
- throw Error
- }
- loadMemberScopedApiKeys(member)
- LemonDialog.open({
- title: `${
- member.user.uuid == user.uuid
- ? 'Leave'
- : `Remove ${fullName(member.user)} from`
- } organization ${user.organization?.name}?`,
- primaryButton: {
- children: member.user.uuid == user.uuid ? 'Leave' : 'Remove',
- status: 'danger',
- onClick: () => removeMember(member),
- },
- secondaryButton: {
- children: 'Cancel',
- },
- content: <RemoveMemberModal member={member} />,
- })
- }}
+ onClick={() => openOffboarding(member)}
fullWidth
>
{member.user.uuid !== user.uuid ? 'Remove from organization' : 'Leave organization'}
@@ -408,6 +349,7 @@ export function Members(): JSX.Element | null {
</div>
<MemberProjectAccessModal />
+ <MemberOffboardingModal />
<LemonTable
dataSource={filteredMembers ?? []}
columns={columns}
diff --git a/frontend/src/scenes/settings/organization/memberOffboardingLogic.test.ts b/frontend/src/scenes/settings/organization/memberOffboardingLogic.test.ts
new file mode 100644
index 000000000000..d1833d4028b0
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/memberOffboardingLogic.test.ts
@@ -0,0 +1,245 @@
+jest.unmock('lib/utils/concurrencyController')
+
+import { MOCK_DEFAULT_ORGANIZATION_MEMBER, MOCK_SECOND_ORGANIZATION_MEMBER } from 'lib/api.mock'
+
+import { waitFor } from '@testing-library/react'
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import { useMocks } from '~/mocks/jest'
+import { membersLogic } from '~/models/membersLogic'
+import { initKeaTests } from '~/test/init'
+
+import { memberOffboardingLogic } from './memberOffboardingLogic'
+
+const resources = [
+ {
+ id: 'public_link:dashboard:1:1',
+ resource_id: '1',
+ kind: 'dashboard',
+ name: 'Product overview',
+ team_id: 1,
+ project_name: 'Website',
+ },
+ {
+ id: 'public_link:insight:1:2',
+ resource_id: '2',
+ kind: 'insight',
+ name: 'Weekly acquisition',
+ team_id: 1,
+ project_name: 'Website',
+ },
+]
+
+describe('memberOffboardingLogic', () => {
+ let logic: ReturnType<typeof memberOffboardingLogic.build>
+ let submitted: unknown[]
+ let updates: unknown[]
+
+ beforeEach(() => {
+ submitted = []
+ updates = []
+ useMocks({
+ get: {
+ '/api/organizations/:organization/members/:user/offboarding_preview/': resources,
+ '/api/organizations/:organization/members/:user/scoped_api_keys/': { has_keys: false, keys: [] },
+ },
+ patch: {
+ '/api/projects/:project/:kind/:resource/sharing/': async ({ request }) => {
+ updates.push({ path: new URL(request.url).pathname, body: await request.json() })
+ return [204, null]
+ },
+ },
+ delete: {
+ '/api/organizations/:organization/members/:user/': () => {
+ submitted.push('remove')
+ return [204, null]
+ },
+ },
+ })
+ initKeaTests()
+ logic = memberOffboardingLogic()
+ logic.mount()
+ })
+
+ it('saves toggles immediately and removes the member without changing resources again', async () => {
+ await expectLogic(logic, () => logic.actions.open(MOCK_SECOND_ORGANIZATION_MEMBER)).toFinishAllListeners()
+ expect(logic.values.resources).toEqual(resources)
+ expect(logic.values.keep).toEqual(resources.map((resource) => resource.id))
+ membersLogic.actions.loadAllMembersSuccess([MOCK_DEFAULT_ORGANIZATION_MEMBER, MOCK_SECOND_ORGANIZATION_MEMBER])
+ await expectLogic(logic, () => {
+ logic.actions.setKeep(resources[0].id, false)
+ expect(logic.values.savingResourceIds).toEqual([resources[0].id])
+ }).toFinishAllListeners()
+ expect(logic.values.savingResourceIds).toEqual([])
+ expect(updates).toEqual([{ path: '/api/projects/1/dashboards/1/sharing/', body: { enabled: false } }])
+ expect(submitted).toEqual([])
+ await expectLogic(logic, () => logic.actions.remove()).toDispatchActions(['removeSuccess'])
+ expect(submitted).toEqual(['remove'])
+ expect(logic.values.member).toBeNull()
+ expect(membersLogic.values.members).toEqual([MOCK_DEFAULT_ORGANIZATION_MEMBER])
+ expect(membersLogic.values.membersLoading).toBe(false)
+ })
+
+ it('disables selected resources immediately and cancellation does not undo the change', async () => {
+ await expectLogic(logic, () => logic.actions.open(MOCK_SECOND_ORGANIZATION_MEMBER)).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.disableResources([resources[0].id])).toFinishAllListeners()
+ expect(updates).toEqual([{ path: '/api/projects/1/dashboards/1/sharing/', body: { enabled: false } }])
+ expect(logic.values.keep).toEqual([resources[1].id])
+ logic.actions.close()
+ expect(submitted).toEqual([])
+ expect(updates).toHaveLength(1)
+ })
+
+ it('keeps the previous toggle state when saving fails and allows retry', async () => {
+ await expectLogic(logic, () => logic.actions.open(MOCK_SECOND_ORGANIZATION_MEMBER)).toFinishAllListeners()
+ useMocks({
+ patch: {
+ '/api/projects/:project/:kind/:resource/sharing/': () => [500, { detail: 'Save failed' }],
+ },
+ })
+ await expectLogic(logic, () => logic.actions.setKeep(resources[0].id, false)).toDispatchActions([
+ 'saveResourcesSuccess',
+ ])
+ expect(logic.values.keep).toEqual(resources.map((resource) => resource.id))
+ expect(logic.values.savingResourcesLoading).toBe(false)
+ expect(logic.values.savingResourceIds).toEqual([])
+ useMocks({
+ patch: { '/api/projects/:project/:kind/:resource/sharing/': () => [204, null] },
+ })
+ await expectLogic(logic, () => logic.actions.setKeep(resources[0].id, false)).toDispatchActions([
+ 'saveResourcesSuccess',
+ ])
+ expect(logic.values.keep).toEqual([resources[1].id])
+ await expectLogic(logic, () => logic.actions.setKeep(resources[0].id, true)).toDispatchActions([
+ 'saveResourcesSuccess',
+ ])
+ expect(logic.values.keep).toContain(resources[0].id)
+ })
+
+ it('explains why the organization policy prevents re-enabling a public link', async () => {
+ const toast = jest.spyOn(lemonToast, 'error')
+ await expectLogic(logic, () => logic.actions.open(MOCK_SECOND_ORGANIZATION_MEMBER)).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.setKeep(resources[0].id, false)).toFinishAllListeners()
+ useMocks({
+ patch: {
+ '/api/projects/1/dashboards/1/sharing/': () => [
+ 403,
+ { detail: 'Public sharing is disabled for this organization.' },
+ ],
+ },
+ })
+ await expectLogic(logic, () => logic.actions.setKeep(resources[0].id, true)).toFinishAllListeners()
+ expect(logic.values.keep).toEqual([resources[1].id])
+ expect(logic.values.savingResourceIds).toEqual([])
+ expect(toast).toHaveBeenLastCalledWith(
+ "Couldn't update Product overview. Public sharing is disabled for this organization."
+ )
+ toast.mockRestore()
+ })
+
+ it('keeps successful bulk changes when another resource fails', async () => {
+ await expectLogic(logic, () => logic.actions.open(MOCK_SECOND_ORGANIZATION_MEMBER)).toFinishAllListeners()
+ useMocks({ patch: { '/api/projects/1/insights/2/sharing/': () => [403, { detail: 'Cannot edit' }] } })
+ await expectLogic(logic, () =>
+ logic.actions.disableResources(resources.map((resource) => resource.id))
+ ).toFinishAllListeners()
+ expect(logic.values.keep).toEqual([resources[1].id])
+ expect(logic.values.savingResourcesLoading).toBe(false)
+ })
+
+ it('limits bulk updates to five requests in flight', async () => {
+ const manyResources = Array.from({ length: 12 }, (_, index) => ({
+ ...resources[0],
+ id: `public_link:dashboard:1:${index + 1}`,
+ resource_id: String(index + 1),
+ }))
+ useMocks({ get: { '/api/organizations/:organization/members/:user/offboarding_preview/': manyResources } })
+ await expectLogic(logic, () => logic.actions.open(MOCK_SECOND_ORGANIZATION_MEMBER)).toFinishAllListeners()
+ let release = (): void => {}
+ const gate = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ let active = 0
+ let peak = 0
+ const update = jest.spyOn(api, 'update').mockImplementation(async () => {
+ active++
+ peak = Math.max(peak, active)
+ await gate
+ active--
+ return {}
+ })
+ const saving = expectLogic(logic, () =>
+ logic.actions.disableResources(manyResources.map((resource) => resource.id))
+ ).toFinishAllListeners()
+ try {
+ await waitFor(() => expect(update).toHaveBeenCalledTimes(5))
+ } finally {
+ release()
+ await saving
+ update.mockRestore()
+ }
+ expect(peak).toBe(5)
+ expect(logic.values.keep).toEqual([])
+ })
+
+ it('summarizes the selected resource types, including selections beyond one page', async () => {
+ const mixedResources = [
+ ...resources,
+ { ...resources[0], id: 'dashboard:2' },
+ { ...resources[0], id: 'dashboard:3' },
+ { ...resources[0], id: 'notebook:1', kind: 'notebook' },
+ { ...resources[0], id: 'recording:1', kind: 'recording' },
+ ]
+ useMocks({ get: { '/api/organizations/:organization/members/:user/offboarding_preview/': mixedResources } })
+ await expectLogic(logic, () => logic.actions.open(MOCK_SECOND_ORGANIZATION_MEMBER)).toFinishAllListeners()
+ expect(logic.values.getSelectionLabel([mixedResources[4].id]).replaceAll('\u00a0', ' ')).toBe('1 notebook')
+ expect(
+ logic.values.getSelectionLabel(mixedResources.map((resource) => resource.id)).replaceAll('\u00a0', ' ')
+ ).toBe('3 dashboards, 1 insight, 1 notebook, 1 recording')
+ })
+
+ it('skips the resource review when leaving the organization yourself', async () => {
+ useMocks({ get: { '/api/organizations/:organization/members/:user/offboarding_preview/': [] } })
+ await expectLogic(logic, () => logic.actions.open(MOCK_DEFAULT_ORGANIZATION_MEMBER)).toFinishAllListeners()
+ expect(logic.values.resources).toEqual([])
+ expect(logic.values.keep).toEqual([])
+ await expectLogic(logic, () => logic.actions.remove()).toDispatchActions(['removeSuccess'])
+ expect(submitted).toEqual(['remove'])
+ })
+
+ it('allows retry after the resource review fails', async () => {
+ useMocks({
+ get: {
+ '/api/organizations/:organization/members/:user/offboarding_preview/': () => [
+ 500,
+ { detail: 'Review unavailable' },
+ ],
+ },
+ })
+ await expectLogic(logic, () => logic.actions.open(MOCK_SECOND_ORGANIZATION_MEMBER)).toDispatchActions([
+ 'loadResourcesFailure',
+ ])
+ expect(logic.values.loadError).toBeTruthy()
+ useMocks({ get: { '/api/organizations/:organization/members/:user/offboarding_preview/': resources } })
+ await expectLogic(logic, () => logic.actions.loadResources()).toDispatchActions(['loadResourcesSuccess'])
+ expect(logic.values.loadError).toBeNull()
+ })
+ it('allows removal when the resource review fails', async () => {
+ useMocks({
+ get: {
+ '/api/organizations/:organization/members/:user/offboarding_preview/': () => [
+ 500,
+ { detail: 'Review unavailable' },
+ ],
+ },
+ })
+ await expectLogic(logic, () => logic.actions.open(MOCK_SECOND_ORGANIZATION_MEMBER)).toDispatchActions([
+ 'loadResourcesFailure',
+ ])
+ await expectLogic(logic, () => logic.actions.remove()).toDispatchActions(['removeSuccess'])
+ expect(submitted).toEqual(['remove'])
+ })
+})
diff --git a/frontend/src/scenes/settings/organization/memberOffboardingLogic.ts b/frontend/src/scenes/settings/organization/memberOffboardingLogic.ts
new file mode 100644
index 000000000000..b5ba2b8f4f45
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/memberOffboardingLogic.ts
@@ -0,0 +1,316 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api, { ApiError } from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { ConcurrencyController } from 'lib/utils/concurrencyController'
+import { fullNameOrEmail, pluralize } from 'lib/utils/strings'
+import { organizationLogic } from 'scenes/organizationLogic'
+import { userLogic } from 'scenes/userLogic'
+
+import { membersLogic } from '~/models/membersLogic'
+import { OrganizationMemberType } from '~/types'
+
+import { membersDestroy, membersOffboardingPreviewRetrieve } from 'products/platform_features/frontend/generated/api'
+import type { MemberOffboardingResourceApi } from 'products/platform_features/frontend/generated/api.schemas'
+
+import type { OrganizationType, UserType } from '../../../types'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface memberOffboardingLogicValues {
+ currentOrganization: OrganizationType | null // organizationLogic
+ user: UserType | null // userLogic
+ getSelectionLabel: (selectedKeys: readonly string[]) => string
+ keep: string[]
+ loadError: string | null
+ member: OrganizationMemberType | null
+ removed: boolean
+ removedLoading: boolean
+ resources: MemberOffboardingResourceApi[] | null
+ resourcesLoading: boolean
+ savingResourceIds: string[]
+ savingResources: boolean
+ savingResourcesLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface memberOffboardingLogicActions {
+ loadMemberScopedApiKeys: (member: OrganizationMemberType) => {
+ member: OrganizationMemberType
+ } // membersLogic
+ postRemoveMember: (userUuid: string) => {
+ userUuid: string
+ } // membersLogic
+ close: () => {
+ value: true
+ }
+ disableResources: (ids: string[]) => {
+ ids: string[]
+ }
+ loadResources: () => {
+ value: true
+ }
+ loadResourcesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadResourcesSuccess: (
+ resources: MemberOffboardingResourceApi[] | null,
+ payload?: {
+ value: true
+ }
+ ) => {
+ resources: MemberOffboardingResourceApi[] | null
+ payload?: {
+ value: true
+ }
+ }
+ open: (member: OrganizationMemberType) => {
+ member: OrganizationMemberType
+ }
+ remove: () => {
+ value: true
+ }
+ removeFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ removeSuccess: (
+ removed: boolean,
+ payload?: {
+ value: true
+ }
+ ) => {
+ removed: boolean
+ payload?: {
+ value: true
+ }
+ }
+ saveResources: ({ ids, enabled }: { enabled: boolean; ids: string[] }) => {
+ ids: string[]
+ enabled: boolean
+ }
+ saveResourcesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ saveResourcesSuccess: (
+ savingResources: boolean,
+ payload?: {
+ ids: string[]
+ enabled: boolean
+ }
+ ) => {
+ savingResources: boolean
+ payload?: {
+ ids: string[]
+ enabled: boolean
+ }
+ }
+ setKeep: (
+ id: string,
+ keep: boolean
+ ) => {
+ id: string
+ keep: boolean
+ }
+ setKeptResources: (ids: string[]) => {
+ ids: string[]
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface memberOffboardingLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ getSelectionLabel: (
+ resources: MemberOffboardingResourceApi[] | null
+ ) => (selectedKeys: readonly string[]) => string
+ }
+}
+
+export type memberOffboardingLogicType = MakeLogicType<
+ memberOffboardingLogicValues,
+ memberOffboardingLogicActions,
+ Record<string, any>,
+ memberOffboardingLogicMeta
+>
+
+export const memberOffboardingLogic = kea<memberOffboardingLogicType>([
+ path(['scenes', 'settings', 'organization', 'memberOffboardingLogic']),
+ connect({
+ values: [organizationLogic, ['currentOrganization'], userLogic, ['user']],
+ actions: [membersLogic, ['loadMemberScopedApiKeys', 'postRemoveMember']],
+ }),
+ actions({
+ open: (member: OrganizationMemberType) => ({ member }),
+ close: true,
+ setKeep: (id: string, keep: boolean) => ({ id, keep }),
+ disableResources: (ids: string[]) => ({ ids }),
+ setKeptResources: (ids: string[]) => ({ ids }),
+ loadResources: true,
+ remove: true,
+ }),
+ reducers({
+ member: [null as OrganizationMemberType | null, { open: (_, { member }) => member, close: () => null }],
+ keep: [
+ [] as string[],
+ {
+ open: () => [],
+ setKeptResources: (_, { ids }) => ids,
+ },
+ ],
+ savingResourceIds: [
+ [] as string[],
+ {
+ open: () => [],
+ saveResources: (_, { ids }) => ids,
+ saveResourcesSuccess: () => [],
+ saveResourcesFailure: () => [],
+ },
+ ],
+ loadError: [
+ null as string | null,
+ { open: () => null, loadResources: () => null, loadResourcesFailure: (_, { error }) => error },
+ ],
+ }),
+ loaders(({ values, actions }) => ({
+ resources: {
+ __default: null as MemberOffboardingResourceApi[] | null,
+ loadResources: async (_, breakpoint) => {
+ const member = values.member
+ if (!member) {
+ return null
+ }
+ const resources = await membersOffboardingPreviewRetrieve(
+ values.currentOrganization?.id ?? '@current',
+ member.user.uuid
+ )
+ breakpoint()
+ return resources
+ },
+ },
+ savingResources: {
+ __default: false,
+ saveResources: async ({ ids, enabled }: { ids: string[]; enabled: boolean }) => {
+ if (!values.member) {
+ return false
+ }
+ const selected = (values.resources ?? []).filter((resource) => ids.includes(resource.id))
+ const concurrency = new ConcurrencyController(5)
+ const results = await Promise.allSettled(
+ selected.map((resource) =>
+ concurrency.run({
+ fn: async () => {
+ const resourceId = resource.resource_id
+ await api.sharing.update(
+ {
+ teamId: resource.team_id,
+ ...(resource.kind === 'dashboard'
+ ? { dashboardId: Number(resourceId) }
+ : resource.kind === 'insight'
+ ? { insightId: Number(resourceId) }
+ : resource.kind === 'notebook'
+ ? { notebookShortId: resourceId }
+ : { recordingId: resourceId }),
+ },
+ { enabled }
+ )
+ return resource.id
+ },
+ })
+ )
+ )
+ const savedIds = results.flatMap((result) => (result.status === 'fulfilled' ? [result.value] : []))
+ actions.setKeptResources(
+ enabled
+ ? [...new Set([...values.keep, ...savedIds])]
+ : values.keep.filter((id) => !savedIds.includes(id))
+ )
+ const failed = selected.filter((_, index) => results[index].status === 'rejected')
+ if (failed.length) {
+ const reasons = [
+ ...new Set(
+ results.flatMap((result) =>
+ result.status === 'rejected' &&
+ result.reason instanceof ApiError &&
+ result.reason.detail
+ ? [result.reason.detail]
+ : []
+ )
+ ),
+ ]
+ lemonToast.error(
+ `Couldn't update ${failed.map((resource) => resource.name).join(', ')}. ${reasons.join(' ') || 'Please try again.'}`
+ )
+ }
+ return true
+ },
+ },
+ removed: {
+ __default: false,
+ remove: async () => {
+ if (!values.member || values.resourcesLoading || values.savingResourcesLoading) {
+ return false
+ }
+ const member = values.member
+ await membersDestroy(values.currentOrganization?.id ?? '@current', member.user.uuid)
+ lemonToast.success(`Removed ${fullNameOrEmail(member.user)} from organization`)
+ actions.close()
+ actions.postRemoveMember(member.user.uuid)
+ return true
+ },
+ },
+ })),
+ selectors({
+ getSelectionLabel: [
+ (s) => [s.resources],
+ (resources: MemberOffboardingResourceApi[] | null) =>
+ (selectedKeys: ReadonlyArray<string>): string => {
+ const selected = new Set(selectedKeys)
+ const counts = new Map<string, number>()
+ for (const resource of resources ?? []) {
+ if (selected.has(resource.id)) {
+ counts.set(resource.kind, (counts.get(resource.kind) ?? 0) + 1)
+ }
+ }
+ const labels = ['dashboard', 'insight', 'notebook', 'recording']
+ .filter((kind) => counts.has(kind))
+ .map((kind) => pluralize(counts.get(kind)!, kind))
+ return labels.join(', ')
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ setKeep: ({ id, keep }) => {
+ if (!values.savingResourcesLoading && !values.removedLoading) {
+ actions.saveResources({ ids: [id], enabled: keep })
+ }
+ },
+ disableResources: ({ ids }) => {
+ if (!values.savingResourcesLoading && !values.removedLoading && ids.length > 0) {
+ actions.saveResources({ ids, enabled: false })
+ }
+ },
+ saveResourcesFailure: () => {
+ lemonToast.error("Couldn't save changes. Please try again.")
+ },
+ loadResourcesSuccess: ({ resources }) => {
+ actions.setKeptResources(
+ values.member?.user.uuid === values.user?.uuid ? [] : (resources ?? []).map((resource) => resource.id)
+ )
+ },
+ open: ({ member }) => {
+ actions.loadMemberScopedApiKeys(member)
+ actions.loadResources()
+ },
+ })),
+])
diff --git a/posthog/api/organization_member.py b/posthog/api/organization_member.py
index 96780e5d3a6e..385b4ba58c76 100644
--- a/posthog/api/organization_member.py
+++ b/posthog/api/organization_member.py
@@ -1,6 +1,6 @@
from typing import Any, cast
-from django.db.models import F, Model, Prefetch, QuerySet
+from django.db.models import F, Model, Prefetch, QuerySet, TextChoices
from django.shortcuts import get_object_or_404
from django_otp.plugins.otp_totp.models import TOTPDevice
@@ -38,6 +38,7 @@ from posthog.helpers.verified_domain_enforcement import verified_domain_email_q
from posthog.models import OrganizationMembership
from posthog.models.user import User
from posthog.models.webauthn_credential import WebauthnCredential
+from posthog.organization_offboarding import OrganizationOffboarding
from posthog.permissions import TimeSensitiveActionPermission, extract_organization
from posthog.utils import posthoganalytics
@@ -152,6 +153,27 @@ class OrganizationMemberGithubLoginSerializer(serializers.Serializer):
)
+class MemberOffboardingResourceKind(TextChoices):
+ DASHBOARD = "dashboard", "Dashboard"
+ INSIGHT = "insight", "Insight"
+ NOTEBOOK = "notebook", "Notebook"
+ RECORDING = "recording", "Session recording"
+
+
+class MemberOffboardingResourceSerializer(serializers.Serializer):
+ id = serializers.CharField(help_text="Opaque identifier used to update this resource during offboarding.")
+ resource_id = serializers.CharField(help_text="Identifier accepted by the resource’s own API.")
+ kind = serializers.ChoiceField(
+ choices=MemberOffboardingResourceKind.choices,
+ help_text="The kind of public object or automated delivery.",
+ )
+ name = serializers.CharField(help_text="The resource's display name.")
+ team_id = serializers.IntegerField(help_text="Project containing the resource.")
+ project_name = serializers.CharField(help_text="Name of the project containing the resource.")
+ password_protected = serializers.BooleanField(help_text="Whether all active public links require a password.")
+ url = serializers.CharField(allow_null=True, help_text="Project-scoped path to open the resource in PostHog.")
+
+
@extend_schema(extensions={"x-product": "platform_features"})
@extend_schema_view(
list=extend_schema(
@@ -329,6 +351,22 @@ class OrganizationMemberViewSet(
instance.user.leave(organization=instance.organization)
+ @extend_schema(
+ operation_id="members_offboarding_preview_retrieve", responses=MemberOffboardingResourceSerializer(many=True)
+ )
+ @action(detail=True, methods=["get"], required_scopes=["organization_member:write"], pagination_class=None)
+ def offboarding_preview(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ instance = cast(OrganizationMembership, self.get_object())
+ requesting_membership = OrganizationMembership.objects.get(
+ user_id=cast(User, request.user).id,
+ organization=instance.organization,
+ )
+ requesting_membership.validate_update(instance)
+ if instance.user_id == request.user.id:
+ return Response([])
+ resources = OrganizationOffboarding(instance).resources()
+ return Response(MemberOffboardingResourceSerializer(resources, many=True).data)
+
@extend_schema(responses=OrganizationMemberGithubLoginSerializer)
@action(detail=True, methods=["get"], url_path="github_login", required_scopes=["organization_member:read"])
def github_login(self, request: Request, *args: Any, **kwargs: Any) -> Response:
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index 5f87e774cfa9..d3e277874173 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -5,6 +5,7 @@ from urllib.parse import urlparse, urlunparse
from django.core.exceptions import ImproperlyConfigured
from django.core.serializers.json import DjangoJSONEncoder
+from django.db import transaction
from django.db.models import Model, Q
from django.http import HttpResponseRedirect
from django.shortcuts import render
@@ -535,42 +536,51 @@ class SharingConfigurationViewSet(
check_can_access_sharing_configuration(self, request, instance)
- # Now that the caller is authorized to edit, collapse any duplicate active rows.
- instance = self._get_sharing_configuration(context, dedupe=True)
-
if request.data.get("password_required", False):
if not self.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL):
return response.Response(
{"error": "Sharing with password requires the Access Control feature"}, status=403
)
- if context.get("recording"):
- recording = cast(SessionRecording, context.get("recording"))
- # Special case where we need to save the instance for recordings so that the actual record gets created
- recording.save()
-
# Publishing is the access decision for shared links (queries on the public page execute
# without warehouse access control), so gate the enable transition: the publisher must have
# access to everything the artifact queries, or sharing becomes an escalation channel.
+ denied_resources: list[str] = []
if (
request.data.get("enabled")
- and not instance.enabled
and self.team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL)
- # org admins have full access, so skip the gate for a faster enable
and not self.user_access_control.is_organization_admin
):
denied_resources = denied_resources_in_share(cast(User, request.user), self.team, instance)
- if denied_resources:
+ serializer = self.get_serializer(instance, data=request.data, partial=True)
+ serializer.is_valid(raise_exception=True)
+
+ with transaction.atomic():
+ if context.get("recording"):
+ recording = cast(SessionRecording, context.get("recording"))
+ # Recordings may not have a persisted row until they are shared.
+ recording.save()
+
+ instance.lock_resource()
+ instance = self._get_sharing_configuration(context, dedupe=True)
+ if denied_resources and not instance.enabled:
denied_names = ", ".join(f"`{name}`" for name in denied_resources)
raise ValidationError(
f"Can't enable sharing: you don't have access to {denied_names}, "
"which the shared queries use. Ask an admin for access, or remove those queries first."
)
-
- serializer = self.get_serializer(instance, data=request.data, partial=True)
- serializer.is_valid(raise_exception=True)
- was_enabled = instance.enabled
- serializer.save(**({"shared_by": request.user} if serializer.validated_data.get("enabled") else {}))
+ serializer.instance = instance
+ was_enabled = instance.enabled
+ serializer.save(**({"shared_by": request.user} if serializer.validated_data.get("enabled") else {}))
+
+ if serializer.validated_data.get("enabled") is False:
+ SharingConfiguration.objects.filter(
+ team_id=self.team_id,
+ dashboard_id=instance.dashboard_id,
+ insight_id=instance.insight_id,
+ notebook_id=instance.notebook_id,
+ recording_id=instance.recording_id,
+ ).update(enabled=False)
if context.get("insight") and "enabled" in serializer.validated_data:
name = instance.insight.name or instance.insight.derived_name
diff --git a/posthog/api/test/test_organization_offboarding.py b/posthog/api/test/test_organization_offboarding.py
new file mode 100644
index 000000000000..3d226a813b61
--- /dev/null
+++ b/posthog/api/test/test_organization_offboarding.py
@@ -0,0 +1,298 @@
+from datetime import timedelta
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import Mock, patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.models import Organization, OrganizationMembership, SessionRecording, SharingConfiguration, Team, User
+from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.organization_offboarding import OrganizationOffboarding
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.dashboards.backend.models.dashboard import Dashboard
+from products.notebooks.backend.models import Notebook
+from products.product_analytics.backend.facade.models import Insight
+
+
+class TestOrganizationOffboarding(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ self.departing = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self.url = f"/api/organizations/@current/members/{self.departing.uuid}/"
+
+ def test_review_uses_publisher_with_creator_fallback_only_when_unknown(self) -> None:
+ second_team = Team.objects.create(organization=self.organization, name="Second project")
+ owned = Dashboard.objects.create(team=second_team, created_by=self.departing, name="Product overview")
+ shared = Dashboard.objects.create(team=self.team, created_by=self.user, name="Weekly acquisition")
+ for dashboard in (owned, shared):
+ SharingConfiguration.objects.create(
+ team=dashboard.team,
+ dashboard=dashboard,
+ enabled=True,
+ password_required=dashboard == owned,
+ shared_by=self.departing if dashboard == shared else None,
+ )
+ reshared = Dashboard.objects.create(team=self.team, created_by=self.departing)
+ SharingConfiguration.objects.create(team=self.team, dashboard=reshared, enabled=True, shared_by=self.user)
+ history_only = Dashboard.objects.create(team=self.team, created_by=self.user)
+ SharingConfiguration.objects.create(team=self.team, dashboard=history_only, enabled=True)
+ ActivityLog.objects.create(
+ team_id=self.team.pk,
+ user=self.departing,
+ scope="Dashboard",
+ activity="sharing enabled",
+ item_id=str(history_only.pk),
+ )
+ inactive = Dashboard.objects.create(team=self.team, created_by=self.departing)
+ SharingConfiguration.objects.create(team=self.team, dashboard=inactive, enabled=False)
+ expired = Dashboard.objects.create(team=self.team, created_by=self.departing)
+ SharingConfiguration.objects.create(
+ team=self.team, dashboard=expired, enabled=True, expires_at=timezone.now() - timedelta(seconds=1)
+ )
+ response = self.client.get(self.url + "offboarding_preview/")
+ assert response.status_code == 200
+ assert {(item["name"], item["team_id"]) for item in response.json()} == {
+ ("Product overview", second_team.pk),
+ ("Weekly acquisition", self.team.pk),
+ }
+ assert all("token" not in str(item) for item in response.json())
+ assert {item["name"]: item["password_protected"] for item in response.json()} == {
+ "Product overview": True,
+ "Weekly acquisition": False,
+ }
+ assert {item["url"] for item in response.json()} == {
+ f"/project/{second_team.pk}/dashboard/{owned.pk}",
+ f"/project/{self.team.pk}/dashboard/{shared.pk}",
+ }
+
+ def test_preview_does_not_load_deferred_insight_queries(self) -> None:
+ for index in range(3):
+ insight = Insight.objects.create(team=self.team, created_by=self.departing, name=f"Insight {index}")
+ SharingConfiguration.objects.create(team=self.team, insight=insight, enabled=True)
+ membership = OrganizationMembership.objects.get(user=self.departing, organization=self.organization)
+ with self.assertNumQueries(4):
+ resources = OrganizationOffboarding(membership).resources()
+ assert len(resources) == 3
+
+ def test_removal_preserves_all_dashboard_tokens_and_other_members_links(self) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.departing, is_shared=True)
+ shares = [SharingConfiguration.objects.create(team=self.team, dashboard=dashboard, enabled=True)]
+ shares.append(
+ SharingConfiguration.objects.create(
+ team=self.team, dashboard=dashboard, enabled=True, expires_at=timezone.now() + timedelta(minutes=5)
+ )
+ )
+ other = Dashboard.objects.create(team=self.team, created_by=self.user)
+ other_share = SharingConfiguration.objects.create(team=self.team, dashboard=other, enabled=True)
+ response = self.client.delete(self.url)
+ assert response.status_code == 204
+ assert not OrganizationMembership.objects.filter(user=self.departing, organization=self.organization).exists()
+ for share in shares:
+ share.refresh_from_db()
+ assert share.enabled
+ dashboard.refresh_from_db()
+ other_share.refresh_from_db()
+ assert dashboard.is_shared
+ assert other_share.enabled
+
+ def test_admin_can_disable_selected_dashboards(self) -> None:
+ kept = Dashboard.objects.create(team=self.team, created_by=self.departing)
+ disabled = Dashboard.objects.create(team=self.team, created_by=self.departing)
+ kept_share = SharingConfiguration.objects.create(team=self.team, dashboard=kept, enabled=True)
+ disabled_share = SharingConfiguration.objects.create(team=self.team, dashboard=disabled, enabled=True)
+ response = self.client.patch(
+ f"/api/projects/{self.team.pk}/dashboards/{disabled.pk}/sharing",
+ {"enabled": False},
+ format="json",
+ )
+ assert response.status_code == 200
+ assert OrganizationMembership.objects.filter(user=self.departing, organization=self.organization).exists()
+ disabled_share.refresh_from_db()
+ assert not disabled_share.enabled
+ response = self.client.delete(self.url)
+ assert response.status_code == 204
+ kept_share.refresh_from_db()
+ disabled_share.refresh_from_db()
+ assert kept_share.enabled
+ assert not disabled_share.enabled
+
+ def test_review_and_cleanup_are_scoped_to_organization(self) -> None:
+ other_team = Team.objects.create(organization=Organization.objects.create(name="Other organization"))
+ dashboard = Dashboard.objects.create(team=other_team, created_by=self.departing)
+ share = SharingConfiguration.objects.create(team=other_team, dashboard=dashboard, enabled=True)
+ assert self.client.get(self.url + "offboarding_preview/").json() == []
+ assert self.client.delete(self.url).status_code == 204
+ share.refresh_from_db()
+ assert share.enabled
+
+ def test_member_cannot_review_or_remove_another_member(self) -> None:
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ assert self.client.get(self.url + "offboarding_preview/").status_code == 403
+ assert self.client.delete(self.url).status_code == 403
+
+ def test_self_removal_preserves_public_links(self) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.user, is_shared=True)
+ share = SharingConfiguration.objects.create(team=self.team, dashboard=dashboard, enabled=True)
+ url = f"/api/organizations/@current/members/{self.user.uuid}/"
+ response = self.client.delete(url)
+ assert response.status_code == 204
+ share.refresh_from_db()
+ dashboard.refresh_from_db()
+ assert share.enabled
+ assert dashboard.is_shared
+ assert not OrganizationMembership.objects.filter(user=self.user, organization=self.organization).exists()
+
+ @parameterized.expand([("dashboard",), ("insight",), ("notebook",)])
+ @patch("posthog.api.sharing.export_asset_for_opengraph")
+ def test_publishers_survive_rotation_without_activity_history(self, kind: str, _export: object) -> None:
+ models: dict[str, type[Dashboard] | type[Insight] | type[Notebook]] = {
+ "dashboard": Dashboard,
+ "insight": Insight,
+ "notebook": Notebook,
+ }
+ resource = models[kind].objects.create(team=self.team, created_by=self.user)
+ lookup_id = resource.short_id if isinstance(resource, Notebook) else resource.pk
+ route = "notebooks" if kind == "notebook" else f"{kind}s"
+ self.client.force_login(self.departing)
+ response = self.client.patch(
+ f"/api/projects/{self.team.pk}/{route}/{lookup_id}/sharing/", {"enabled": True}, format="json"
+ )
+ assert response.status_code == 200
+ share = SharingConfiguration.objects.get(team=self.team, **{kind: resource})
+ assert share.shared_by_id == self.departing.pk
+ rotated = share.rotate_access_token()
+ assert rotated.shared_by_id == self.departing.pk
+ ActivityLog.objects.filter(team_id=self.team.pk, user=self.departing).delete()
+ self.client.force_login(self.user)
+ response = self.client.get(self.url + "offboarding_preview/")
+ assert response.status_code == 200
+ assert [item["id"] for item in response.json()] == [f"public_link:{kind}:{self.team.pk}:{resource.pk}"]
+
+ def test_review_and_disable_all_public_resource_kinds(self) -> None:
+ insight = Insight.objects.create(team=self.team, created_by=self.departing, name="Weekly trends")
+ notebook = Notebook.objects.create(team=self.team, created_by=self.user, title="Analysis")
+ recording = SessionRecording.objects.create(team=self.team, session_id="offboarding-test-recording")
+ insight_share = SharingConfiguration.objects.create(
+ team=self.team, insight=insight, enabled=True, password_required=True
+ )
+ notebook_share = SharingConfiguration.objects.create(
+ team=self.team, notebook=notebook, enabled=True, password_required=True, shared_by=self.departing
+ )
+ recording_share = SharingConfiguration.objects.create(
+ team=self.team, recording=recording, enabled=True, shared_by=self.departing
+ )
+ grace_share = SharingConfiguration.objects.create(
+ team=self.team,
+ notebook=notebook,
+ enabled=True,
+ password_required=True,
+ expires_at=timezone.now() + timedelta(minutes=5),
+ )
+ deleted = Insight.objects.create(team=self.team, created_by=self.departing, deleted=True)
+ SharingConfiguration.objects.create(team=self.team, insight=deleted, enabled=True)
+ other = Notebook.objects.create(team=self.team, created_by=self.user)
+ unrelated_share = SharingConfiguration.objects.create(team=self.team, notebook=other, enabled=True)
+ response = self.client.get(self.url + "offboarding_preview/")
+ assert response.status_code == 200
+ review = {item["kind"]: item for item in response.json()}
+ assert set(review) == {"insight", "notebook", "recording"}
+ assert review["insight"]["password_protected"]
+ assert review["notebook"]["password_protected"]
+ assert not review["recording"]["password_protected"]
+ assert review["insight"]["url"] == f"/project/{self.team.pk}/insights/{insight.short_id}"
+ assert review["notebook"]["url"] == f"/project/{self.team.pk}/notebooks/{notebook.short_id}"
+ assert review["recording"]["url"] == f"/project/{self.team.pk}/replay/{recording.session_id}"
+ grace_share.password_required = False
+ grace_share.save(update_fields=["password_required"])
+ review = {item["kind"]: item for item in self.client.get(self.url + "offboarding_preview/").json()}
+ assert not review["notebook"]["password_protected"]
+ for kind, path in (("notebook", "notebooks"), ("recording", "session_recordings")):
+ response = self.client.patch(
+ f"/api/projects/{self.team.pk}/{path}/{review[kind]['resource_id']}/sharing",
+ {"enabled": False},
+ format="json",
+ )
+ assert response.status_code == 200
+ response = self.client.delete(self.url)
+ assert response.status_code == 204
+ insight_share.refresh_from_db()
+ assert insight_share.enabled
+ for share in (notebook_share, grace_share, recording_share):
+ share.refresh_from_db()
+ assert not share.enabled
+ unrelated_share.refresh_from_db()
+ assert unrelated_share.enabled
+
+ def test_self_leave_skips_resource_review_and_preserves_links_in_all_projects(self) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ hidden_team = Team.objects.create(organization=self.organization, name="Private project")
+ AccessControl.objects.create(
+ team=hidden_team, resource="project", resource_id=str(hidden_team.pk), access_level="none"
+ )
+ visible = Dashboard.objects.create(team=self.team, created_by=self.departing)
+ hidden = Dashboard.objects.create(team=hidden_team, created_by=self.departing)
+ for dashboard in (visible, hidden):
+ SharingConfiguration.objects.create(team=dashboard.team, dashboard=dashboard, enabled=True)
+ assert len(self.client.get(self.url + "offboarding_preview/").json()) == 2
+ self.client.force_login(self.departing)
+ response = self.client.get(self.url + "offboarding_preview/")
+ assert response.status_code == 200
+ assert response.json() == []
+ assert self.client.delete(self.url).status_code == 204
+ assert SharingConfiguration.objects.filter(dashboard__in=[visible, hidden], enabled=True).count() == 2
+
+ def test_confirming_removal_preserves_current_sharing(self) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.departing, is_shared=True)
+ share = SharingConfiguration.objects.create(team=self.team, dashboard=dashboard, enabled=True)
+ assert self.client.delete(self.url).status_code == 204
+ share.refresh_from_db()
+ assert share.enabled
+
+ @patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
+ def test_immediate_sharing_changes_can_be_reversed_without_reviving_old_tokens(self, _export: Mock) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.departing, is_shared=True)
+ current = SharingConfiguration.objects.create(team=self.team, dashboard=dashboard, enabled=True)
+ grace = SharingConfiguration.objects.create(
+ team=self.team, dashboard=dashboard, enabled=True, expires_at=timezone.now() + timedelta(minutes=5)
+ )
+ expired = SharingConfiguration.objects.create(
+ team=self.team, dashboard=dashboard, enabled=False, expires_at=timezone.now() - timedelta(minutes=5)
+ )
+ payload = {"enabled": False}
+ assert (
+ self.client.patch(
+ f"/api/projects/{self.team.pk}/dashboards/{dashboard.pk}/sharing", payload, format="json"
+ ).status_code
+ == 200
+ )
+ assert not SharingConfiguration.objects.filter(team=self.team, dashboard=dashboard, enabled=True).exists()
+ payload["enabled"] = True
+ assert (
+ self.client.patch(
+ f"/api/projects/{self.team.pk}/dashboards/{dashboard.pk}/sharing", payload, format="json"
+ ).status_code
+ == 200
+ )
+ current.refresh_from_db()
+ dashboard.refresh_from_db()
+ grace.refresh_from_db()
+ expired.refresh_from_db()
+ assert current.enabled
+ assert current.shared_by_id == self.user.pk
+ assert dashboard.is_shared
+ assert not grace.enabled
+ assert not expired.enabled
+ assert OrganizationMembership.objects.filter(user=self.departing, organization=self.organization).exists()
+ assert ActivityLog.objects.filter(
+ team_id=self.team.pk, scope="Dashboard", item_id=str(dashboard.pk), activity="sharing enabled"
+ ).exists()
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index 7dcd6ffcd510..d585f9fe0359 100644
--- a/posthog/api/test/test_sharing.py
+++ b/posthog/api/test/test_sharing.py
@@ -2343,6 +2343,36 @@ class TestSharingPublishGate(APIBaseTest):
assert "governed_view" in str(response.json())
assert not SharingConfiguration.objects.filter(team=self.team, enabled=True).exists()
+ @patch("posthog.api.sharing.export_asset_for_opengraph")
+ @patch("posthog.models.sharing_configuration.SharingConfiguration.lock_resource")
+ @patch("posthog.api.sharing.denied_resources_in_share")
+ def test_publish_validation_runs_before_resource_lock(self, check: Mock, lock: Mock, _export: Mock) -> None:
+ def validate(*args: Any) -> list[str]:
+ lock.assert_not_called()
+ return []
+
+ check.side_effect = validate
+ response = self._enable_sharing("dashboard")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ check.assert_called_once()
+ lock.assert_called_once()
+
+ @patch("posthog.api.sharing.denied_resources_in_share")
+ def test_enable_checks_current_state_after_concurrent_disable(self, check: Mock) -> None:
+ configuration = SharingConfiguration.objects.create(team=self.team, insight=self.insight, enabled=True)
+
+ def validate(*args: Any) -> list[str]:
+ SharingConfiguration.objects.filter(team=self.team, pk=configuration.pk).update(enabled=False)
+ return ["governed_view"]
+
+ check.side_effect = validate
+ response = self._enable_sharing("insight")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ configuration.refresh_from_db()
+ assert not configuration.enabled
+
def test_publisher_with_access_can_enable_sharing(self):
response = self._enable_sharing("dashboard")
diff --git a/posthog/models/sharing_configuration.py b/posthog/models/sharing_configuration.py
index bf3a59742c0c..a4e7fd26cb20 100644
--- a/posthog/models/sharing_configuration.py
+++ b/posthog/models/sharing_configuration.py
@@ -176,7 +176,7 @@ class SharingConfiguration(models.Model):
return keep
- def _lock_resource_for_rotation(self) -> None:
+ def lock_resource(self) -> None:
# Resolve each parent model from its own FK instead of importing it. This keeps the module
# free of product imports.
for field_name in ("dashboard", "insight", "notebook", "recording", "interviewee_context"):
@@ -207,7 +207,7 @@ class SharingConfiguration(models.Model):
resource_lookup = self._resource_lookup_for_instance()
with transaction.atomic():
- self._lock_resource_for_rotation()
+ self.lock_resource()
active_configs = list(
SharingConfiguration.objects.select_for_update()
diff --git a/posthog/organization_offboarding.py b/posthog/organization_offboarding.py
new file mode 100644
index 000000000000..adafeab210fd
--- /dev/null
+++ b/posthog/organization_offboarding.py
@@ -0,0 +1,96 @@
+from urllib.parse import quote
+
+from django.db.models import Exists, OuterRef, Q
+
+from posthog.dataclasses import frozen
+from posthog.models.organization import OrganizationMembership
+from posthog.models.sharing_configuration import SharingConfiguration
+from posthog.organization_offboarding_types import OffboardingResource
+
+
+@frozen
+class PublicResourceKind:
+ kind: str
+ identifier_field: str
+ name_field: str
+ url_path: str
+
+
+PUBLIC_RESOURCE_KINDS = (
+ PublicResourceKind(kind="dashboard", identifier_field="id", name_field="name", url_path="dashboard"),
+ PublicResourceKind(kind="insight", identifier_field="id", name_field="name", url_path="insights"),
+ PublicResourceKind(kind="notebook", identifier_field="short_id", name_field="title", url_path="notebooks"),
+ PublicResourceKind(kind="recording", identifier_field="session_id", name_field="session_id", url_path="replay"),
+)
+
+
+class OrganizationOffboarding:
+ def __init__(self, membership: OrganizationMembership) -> None:
+ self.organization_id = str(membership.organization_id)
+ self.user_id = membership.user_id
+
+ def _public_resources(self, resource_kind: PublicResourceKind) -> list[OffboardingResource]:
+ kind = resource_kind.kind
+ related_to_member = Q(shared_by_id=self.user_id)
+ if kind != "recording":
+ related_to_member |= Q(shared_by__isnull=True, **{f"{kind}__created_by_id": self.user_id})
+ configurations = (
+ SharingConfiguration.objects.filter(
+ SharingConfiguration.tokens_active_q(),
+ team__organization_id=self.organization_id,
+ **{f"{kind}__isnull": False},
+ )
+ .filter(related_to_member)
+ .annotate(
+ has_unprotected_link=Exists(
+ SharingConfiguration.objects.filter(
+ SharingConfiguration.tokens_active_q(),
+ team_id=OuterRef("team_id"),
+ password_required=False,
+ **{f"{kind}_id": OuterRef(f"{kind}_id")},
+ )
+ ),
+ )
+ .values(
+ "has_unprotected_link",
+ "team_id",
+ "team__name",
+ f"{kind}_id",
+ f"{kind}__{resource_kind.name_field}",
+ f"{kind}__{resource_kind.identifier_field}",
+ *([f"{kind}__short_id"] if kind in ("insight", "notebook") else []),
+ *(["insight__derived_name"] if kind == "insight" else []),
+ )
+ .order_by("-created_at")
+ )
+ # nosemgrep: orm-field-injection -- kind comes from the fixed PUBLIC_RESOURCE_KINDS registry
+ configurations = configurations.exclude(**{f"{kind}__deleted": True})
+ resources: dict[str, OffboardingResource] = {}
+ for configuration in configurations.iterator(chunk_size=200):
+ team_id = configuration["team_id"]
+ object_id = configuration[f"{kind}_id"]
+ resource_id = f"public_link:{kind}:{team_id}:{object_id}"
+ name = configuration[f"{kind}__{resource_kind.name_field}"]
+ if kind == "insight" and not name:
+ name = configuration["insight__derived_name"]
+ identifier = configuration[
+ f"{kind}__short_id" if kind in ("insight", "notebook") else f"{kind}__{resource_kind.identifier_field}"
+ ]
+ resources.setdefault(
+ resource_id,
+ OffboardingResource(
+ id=resource_id,
+ resource_id=str(configuration["notebook__short_id"] if kind == "notebook" else object_id),
+ kind=kind,
+ name=name or f"Untitled {kind}",
+ team_id=team_id,
+ project_name=configuration["team__name"],
+ password_protected=not configuration["has_unprotected_link"],
+ url=f"/project/{team_id}/{resource_kind.url_path}/{quote(str(identifier), safe='')}",
+ ),
+ )
+ return list(resources.values())
+
+ def resources(self) -> list[OffboardingResource]:
+ resources = [resource for kind in PUBLIC_RESOURCE_KINDS for resource in self._public_resources(kind)]
+ return sorted(resources, key=lambda resource: (resource.name, resource.id))
diff --git a/posthog/organization_offboarding_types.py b/posthog/organization_offboarding_types.py
new file mode 100644
index 000000000000..b7db35b33009
--- /dev/null
+++ b/posthog/organization_offboarding_types.py
@@ -0,0 +1,13 @@
+from posthog.dataclasses import frozen
+
+
+@frozen
+class OffboardingResource:
+ id: str
+ resource_id: str
+ kind: str
+ name: str
+ team_id: int
+ project_name: str
+ password_protected: bool = False
+ url: str | None = None
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 81333cc5abcc..1314c3705a3f 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -476,6 +476,49 @@ export interface OrganizationMemberGithubLoginApi {
github_login: string | null
}
+/**
+ * * `dashboard` - Dashboard
+ * * `insight` - Insight
+ * * `notebook` - Notebook
+ * * `recording` - Session recording
+ */
+export type MemberOffboardingResourceKindEnumApi =
+ (typeof MemberOffboardingResourceKindEnumApi)[keyof typeof MemberOffboardingResourceKindEnumApi]
+
+export const MemberOffboardingResourceKindEnumApi = {
+ Dashboard: 'dashboard',
+ Insight: 'insight',
+ Notebook: 'notebook',
+ Recording: 'recording',
+} as const
+
+export interface MemberOffboardingResourceApi {
+ /** Opaque identifier used to update this resource during offboarding. */
+ id: string
+ /** Identifier accepted by the resource’s own API. */
+ resource_id: string
+ /** The kind of public object or automated delivery.
+ *
+ * * `dashboard` - Dashboard
+ * * `insight` - Insight
+ * * `notebook` - Notebook
+ * * `recording` - Session recording */
+ kind: MemberOffboardingResourceKindEnumApi
+ /** The resource's display name. */
+ name: string
+ /** Project containing the resource. */
+ team_id: number
+ /** Name of the project containing the resource. */
+ project_name: string
+ /** Whether all active public links require a password. */
+ password_protected: boolean
+ /**
+ * Project-scoped path to open the resource in PostHog.
+ * @nullable
+ */
+ url: string | null
+}
+
export interface OrganizationPersonalAPIKeyOwnerApi {
/** First name of the key's owner. */
readonly first_name: string
diff --git a/products/platform_features/frontend/generated/api.ts b/products/platform_features/frontend/generated/api.ts
index 6f76ea99f1b4..ea739d5c3b1f 100644
--- a/products/platform_features/frontend/generated/api.ts
+++ b/products/platform_features/frontend/generated/api.ts
@@ -27,6 +27,7 @@ import type {
InternalFeedbackCreateBody,
InternalFeedbackResponseApi,
ListParams,
+ MemberOffboardingResourceApi,
MembersListParams,
OrganizationAIAccessRequestResponseApi,
OrganizationApi,
@@ -360,6 +361,24 @@ export const membersGithubLoginRetrieve = async (
})
}
+export const getMembersOffboardingPreviewRetrieveUrl = (organizationId: string, userUuid: string) => {
+ return `/api/organizations/${organizationId}/members/${userUuid}/offboarding_preview/`
+}
+
+export const membersOffboardingPreviewRetrieve = async (
+ organizationId: string,
+ userUuid: string,
+ options?: RequestInit
+): Promise<MemberOffboardingResourceApi[]> => {
+ return apiMutator<MemberOffboardingResourceApi[]>(
+ getMembersOffboardingPreviewRetrieveUrl(organizationId, userUuid),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
export const getMembersScopedApiKeysRetrieveUrl = (organizationId: string, userUuid: string) => {
return `/api/organizations/${organizationId}/members/${userUuid}/scoped_api_keys/`
}
diff --git a/products/platform_features/mcp/tools.yaml b/products/platform_features/mcp/tools.yaml
index 413de12a369b..65071f4ae176 100644
--- a/products/platform_features/mcp/tools.yaml
+++ b/products/platform_features/mcp/tools.yaml
@@ -324,6 +324,12 @@ tools:
description: |
The PostHog user UUID of the organization member, as returned by org-members-list. Pass "@me"
for the current user.
+ org-member-offboarding-review:
+ operation: members_offboarding_preview_retrieve
+ enabled: false
+ disabled_reason:
+ Offboarding is an organization settings workflow. Its organization-wide resource review and member
+ removal are kept together in that UI; this change does not expose an MCP offboarding workflow.
org-members-list:
operation: members_list
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index adf4919b8f79..9eb31f6407cf 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -64701,6 +64701,49 @@ export namespace Schemas {
enabled: boolean;
}
+ /**
+ * * `dashboard` - Dashboard
+ * * `insight` - Insight
+ * * `notebook` - Notebook
+ * * `recording` - Session recording
+ */
+ export type MemberOffboardingResourceKindEnum = typeof MemberOffboardingResourceKindEnum[keyof typeof MemberOffboardingResourceKindEnum];
+
+
+ export const MemberOffboardingResourceKindEnum = {
+ Dashboard: 'dashboard',
+ Insight: 'insight',
+ Notebook: 'notebook',
+ Recording: 'recording',
+ } as const;
+
+ export interface MemberOffboardingResource {
+ /** Opaque identifier used to update this resource during offboarding. */
+ id: string;
+ /** Identifier accepted by the resource’s own API. */
+ resource_id: string;
+ /** The kind of public object or automated delivery.
+ *
+ * * `dashboard` - Dashboard
+ * * `insight` - Insight
+ * * `notebook` - Notebook
+ * * `recording` - Session recording */
+ kind: MemberOffboardingResourceKindEnum;
+ /** The resource's display name. */
+ name: string;
+ /** Project containing the resource. */
+ team_id: number;
+ /** Name of the project containing the resource. */
+ project_name: string;
+ /** Whether all active public links require a password. */
+ password_protected: boolean;
+ /**
+ * Project-scoped path to open the resource in PostHog.
+ * @nullable
+ */
+ url: string | null;
+ }
+
/**
* A resolved access level with the rule that supplied it — the wire form of `ResolvedAccess`.
*/