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.

10.0 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'

import api, { CountedPaginatedResponse } from 'lib/api'
import { OrganizationMembershipLevel } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { organizationLogic } from 'scenes/organizationLogic'

import { membersLogic } from '~/models/membersLogic'
import { OrganizationDomainType, OrganizationMemberType, OrganizationType } from '~/types'

import { verifiedDomainsLogic } from './verifiedDomainsLogic'

/** How many impacted members to fetch for the modal; the total count still comes from the response. */
const IMPACTED_MEMBERS_FETCH_LIMIT = 100

interface EnforcementRemovalResult {
    success: boolean
    removed_members: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface verifiedDomainImpactLogicValues {
    currentOrganization: OrganizationType | null // organizationLogic
    domainImpact: CountedPaginatedResponse<OrganizationMemberType> | null
    domainImpactLoading: boolean
    enforcementImpact: CountedPaginatedResponse<OrganizationMemberType> | null
    enforcementImpactLoading: boolean
    enforcementPromptOpen: boolean
    enforcementRemoval: EnforcementRemovalResult | null
    enforcementRemovalLoading: boolean
    removeDomainPrompt: OrganizationDomainType | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface verifiedDomainImpactLogicActions {
    loadCurrentOrganization: () => any // organizationLogic
    updateOrganization: (
        payload: Partial<
            Pick<
                OrganizationType,
                | 'allow_publicly_shared_resources'
                | 'default_anonymize_ips'
                | 'default_role_id'
                | 'enforce_2fa'
                | 'enforce_verified_domains'
                | 'is_ai_data_processing_approved'
                | 'is_ai_training_opted_in'
                | 'logo_media_id'
                | 'member_notice'
                | 'members_can_create_projects'
                | 'members_can_invite'
                | 'members_can_see_org_members'
                | 'members_can_use_personal_api_keys'
                | 'name'
                | 'read_only_mcp_access'
            >
        >
    ) => Partial<
        Pick<
            OrganizationType,
            | 'allow_publicly_shared_resources'
            | 'default_anonymize_ips'
            | 'default_role_id'
            | 'enforce_2fa'
            | 'enforce_verified_domains'
            | 'is_ai_data_processing_approved'
            | 'is_ai_training_opted_in'
            | 'logo_media_id'
            | 'member_notice'
            | 'members_can_create_projects'
            | 'members_can_invite'
            | 'members_can_see_org_members'
            | 'members_can_use_personal_api_keys'
            | 'name'
            | 'read_only_mcp_access'
        >
    > // organizationLogic
    closeEnforcementPrompt: () => {
        value: true
    }
    closeRemoveDomainPrompt: () => {
        value: true
    }
    confirmEnforceVerifiedDomains: () => {
        value: true
    }
    confirmEnforceVerifiedDomainsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    confirmEnforceVerifiedDomainsSuccess: (
        enforcementRemoval: EnforcementRemovalResult,
        payload?: {
            value: true
        }
    ) => {
        enforcementRemoval: EnforcementRemovalResult
        payload?: {
            value: true
        }
    }
    confirmRemoveDomain: () => {
        value: true
    }
    loadDomainImpact: (domain: OrganizationDomainType) => {
        domain: OrganizationDomainType
    }
    loadDomainImpactFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadDomainImpactSuccess: (
        domainImpact: CountedPaginatedResponse<OrganizationMemberType>,
        payload?: {
            domain: OrganizationDomainType
        }
    ) => {
        domainImpact: CountedPaginatedResponse<OrganizationMemberType>
        payload?: {
            domain: OrganizationDomainType
        }
    }
    loadEnforcementImpact: () => {
        value: true
    }
    loadEnforcementImpactFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadEnforcementImpactSuccess: (
        enforcementImpact: CountedPaginatedResponse<OrganizationMemberType>,
        payload?: {
            value: true
        }
    ) => {
        enforcementImpact: CountedPaginatedResponse<OrganizationMemberType>
        payload?: {
            value: true
        }
    }
    promptEnforceVerifiedDomains: () => {
        value: true
    }
    promptRemoveDomain: (domain: OrganizationDomainType) => {
        domain: OrganizationDomainType
    }
}

export type verifiedDomainImpactLogicType = MakeLogicType<
    verifiedDomainImpactLogicValues,
    verifiedDomainImpactLogicActions
>

/**
 * Impact previews for the two destructive verified-domain actions: removing a verified domain while
 * membership is restricted to verified email domains, and turning that restriction on. Both fetch
 * the members who would lose access so the confirmation modal can list them.
 */
export const verifiedDomainImpactLogic = kea<verifiedDomainImpactLogicType>([
    path(['scenes', 'organization', 'verifiedDomainImpactLogic']),
    connect(() => ({
        values: [organizationLogic, ['currentOrganization']],
        actions: [organizationLogic, ['updateOrganization', 'loadCurrentOrganization']],
    })),
    actions({
        promptRemoveDomain: (domain: OrganizationDomainType) => ({ domain }),
        closeRemoveDomainPrompt: true,
        confirmRemoveDomain: true,
        promptEnforceVerifiedDomains: true,
        closeEnforcementPrompt: true,
        loadDomainImpact: (domain: OrganizationDomainType) => ({ domain }),
        loadEnforcementImpact: true,
        confirmEnforceVerifiedDomains: true,
    }),
    loaders(({ values }) => ({
        domainImpact: [
            null as CountedPaginatedResponse<OrganizationMemberType> | null,
            {
                loadDomainImpact: async ({ domain }: { domain: OrganizationDomainType }) => {
                    return await api.organizationMembers.list({
                        email_domain: domain.domain,
                        limit: IMPACTED_MEMBERS_FETCH_LIMIT,
                    })
                },
            },
        ],
        enforcementImpact: [
            null as CountedPaginatedResponse<OrganizationMemberType> | null,
            {
                loadEnforcementImpact: async () => {
                    return await api.organizationMembers.list({
                        outside_verified_domains: true,
                        // Owners are never removed, so listing them would overstate the count.
                        levels: [OrganizationMembershipLevel.Member, OrganizationMembershipLevel.Admin].join(','),
                        limit: IMPACTED_MEMBERS_FETCH_LIMIT,
                    })
                },
            },
        ],
        enforcementRemoval: [
            null as EnforcementRemovalResult | null,
            {
                confirmEnforceVerifiedDomains: async () => {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use removeBlockedMembersAndEnforceVerifiedDomainsCreate() from 'products/platform_features/frontend/generated/api' instead.
                    return await api.create<EnforcementRemovalResult>(
                        `api/organizations/${values.currentOrganization?.id}/remove_blocked_members_and_enforce_verified_domains`
                    )
                },
            },
        ],
    })),
    reducers({
        removeDomainPrompt: [
            null as OrganizationDomainType | null,
            {
                promptRemoveDomain: (_, { domain }) => domain,
                closeRemoveDomainPrompt: () => null,
            },
        ],
        domainImpact: {
            promptRemoveDomain: () => null,
        },
        enforcementPromptOpen: [
            false,
            {
                loadEnforcementImpactSuccess: (_, { enforcementImpact }) => (enforcementImpact?.count ?? 0) > 0,
                closeEnforcementPrompt: () => false,
                confirmEnforceVerifiedDomainsSuccess: () => false,
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        promptRemoveDomain: ({ domain }) => {
            // The list is only meaningful when the restriction is on and the domain counts as verified.
            if (values.currentOrganization?.enforce_verified_domains && domain.is_verified) {
                actions.loadDomainImpact(domain)
            }
        },
        confirmRemoveDomain: () => {
            const domain = values.removeDomainPrompt
            if (domain) {
                verifiedDomainsLogic.actions.deleteVerifiedDomain(domain.id)
            }
            actions.closeRemoveDomainPrompt()
        },
        promptEnforceVerifiedDomains: () => {
            actions.loadEnforcementImpact()
        },
        loadEnforcementImpactSuccess: () => {
            if ((values.enforcementImpact?.count ?? 0) === 0) {
                // Nobody is impacted, no confirmation needed.
                actions.updateOrganization({ enforce_verified_domains: true })
            }
        },
        confirmEnforceVerifiedDomainsSuccess: ({ enforcementRemoval }) => {
            const removed = enforcementRemoval?.removed_members ?? 0
            lemonToast.success(
                removed === 1
                    ? 'Logins restricted to verified email domains. 1 member was removed.'
                    : `Logins restricted to verified email domains. ${removed} members were removed.`
            )
            actions.loadCurrentOrganization()
            membersLogic.findMounted()?.actions.loadAllMembers()
        },
    })),
])