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.

9.8 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router } from 'kea-router'
import posthog from 'posthog-js'

import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { getRelativeNextPath } from 'lib/utils/url'
import { connectedAppsLogic } from 'scenes/settings/user/connectedAppsLogic'
import { passkeySettingsLogic } from 'scenes/settings/user/passkeySettingsLogic'
import { personalAPIKeysLogic } from 'scenes/settings/user/personalAPIKeysLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { usersCredentialsReviewCompleteCreate } from '~/generated/core/api'
import type { ConnectedAppApi } from '~/generated/core/api.schemas'

// pinned: analytics event name and properties, renaming breaks dashboards
const PARTNER_ACCESS_CHOSEN_EVENT = 'credential review partner access chosen'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface credentialReviewLogicValues {
    connectedApps: ConnectedAppApi[] // connectedAppsLogic
    connectedAppsLoading: boolean // connectedAppsLogic
    passkeysLoading: boolean // passkeySettingsLogic
    keysLoading: boolean // personalAPIKeysLogic
    connectedAppsLoadFailed: boolean
    continueDisabledReason: string | null
    isCompleting: boolean
    keptPartnerIds: string[]
    otherConnectedApps: ConnectedAppApi[]
    partnersAwaitingChoice: ConnectedAppApi[]
    partnersRequiringChoice: ConnectedAppApi[]
    revokingAppId: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface credentialReviewLogicActions {
    loadConnectedAppsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // connectedAppsLogic
    loadConnectedAppsSuccess: (
        connectedApps: ConnectedAppApi[],
        payload?: any
    ) => {
        connectedApps: ConnectedAppApi[]
        payload?: any
    } // connectedAppsLogic
    revokeApp: (id: string) => {
        id: string
    } // connectedAppsLogic
    revokeAppFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // connectedAppsLogic
    revokeAppSuccess: (
        connectedApps: ConnectedAppApi[],
        payload?:
            | {
                  id: string
              }
            | undefined
    ) => {
        connectedApps: ConnectedAppApi[]
        payload?: {
            id: string
        }
    } // connectedAppsLogic
    loadPasskeys: () => any // passkeySettingsLogic
    loadKeys: () => {
        value: true
    } // personalAPIKeysLogic
    disconnectPartner: (appId: string) => {
        appId: string
    }
    keepPartnerConnected: (appId: string) => {
        appId: string
    }
    markComplete: () => {
        value: true
    }
    setCompleting: (completing: boolean) => {
        completing: boolean
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface credentialReviewLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        partnersRequiringChoice: (connectedApps: ConnectedAppApi[]) => ConnectedAppApi[]
        otherConnectedApps: (connectedApps: ConnectedAppApi[]) => ConnectedAppApi[]
        partnersAwaitingChoice: (
            partnersRequiringChoice: ConnectedAppApi[],
            keptPartnerIds: string[]
        ) => ConnectedAppApi[]
        continueDisabledReason: (
            revokingAppId: string | null,
            keysLoading: boolean,
            passkeysLoading: boolean,
            connectedAppsLoading: boolean,
            connectedAppsLoadFailed: boolean,
            partnersAwaitingChoice: ConnectedAppApi[]
        ) => string | null
    }
}

export type credentialReviewLogicType = MakeLogicType<
    credentialReviewLogicValues,
    credentialReviewLogicActions,
    Record<string, any>,
    credentialReviewLogicMeta
>

export const credentialReviewLogic = kea<credentialReviewLogicType>([
    path(['scenes', 'authentication', 'account', 'credential-review', 'credentialReviewLogic']),
    // connect (not bare import calls) so the list logics are mounted as dependencies
    // of this scene logic. afterMount runs before the review component renders, so without
    // this the load calls below hit an unmounted logic and throw, which sceneLogic
    // catches and turns into a 404 for the whole credential review screen.
    connect(() => ({
        values: [
            connectedAppsLogic,
            ['connectedApps', 'connectedAppsLoading'],
            passkeySettingsLogic,
            ['passkeysLoading'],
            personalAPIKeysLogic,
            ['keysLoading'],
        ],
        actions: [
            connectedAppsLogic,
            [
                'loadConnectedAppsFailure',
                'loadConnectedAppsSuccess',
                'revokeApp',
                'revokeAppFailure',
                'revokeAppSuccess',
            ],
            passkeySettingsLogic,
            ['loadPasskeys'],
            personalAPIKeysLogic,
            ['loadKeys'],
        ],
    })),
    actions({
        keepPartnerConnected: (appId: string) => ({ appId }),
        disconnectPartner: (appId: string) => ({ appId }),
        markComplete: true,
        setCompleting: (completing: boolean) => ({ completing }),
    }),
    reducers({
        keptPartnerIds: [
            [] as string[],
            {
                keepPartnerConnected: (state, { appId }) => (state.includes(appId) ? state : [...state, appId]),
            },
        ],
        revokingAppId: [
            null as string | null,
            {
                revokeApp: (_, { id }) => id,
                revokeAppSuccess: () => null,
                revokeAppFailure: () => null,
            },
        ],
        isCompleting: [
            false,
            {
                setCompleting: (_, { completing }) => completing,
            },
        ],
        connectedAppsLoadFailed: [
            false,
            {
                loadConnectedAppsFailure: () => true,
                loadConnectedAppsSuccess: () => false,
            },
        ],
    }),
    selectors({
        partnersRequiringChoice: [
            (s) => [s.connectedApps],
            (connectedApps: ConnectedAppApi[]): ConnectedAppApi[] =>
                connectedApps.filter((app) => app.requires_access_confirmation),
        ],
        otherConnectedApps: [
            (s) => [s.connectedApps],
            (connectedApps: ConnectedAppApi[]): ConnectedAppApi[] =>
                connectedApps.filter((app) => !app.requires_access_confirmation),
        ],
        partnersAwaitingChoice: [
            (s) => [s.partnersRequiringChoice, s.keptPartnerIds],
            (partnersRequiringChoice: ConnectedAppApi[], keptPartnerIds: string[]): ConnectedAppApi[] =>
                partnersRequiringChoice.filter((app) => !keptPartnerIds.includes(app.id)),
        ],
        continueDisabledReason: [
            (s) => [
                s.revokingAppId,
                s.keysLoading,
                s.passkeysLoading,
                s.connectedAppsLoading,
                s.connectedAppsLoadFailed,
                s.partnersAwaitingChoice,
            ],
            (
                revokingAppId: string | null,
                keysLoading: boolean,
                passkeysLoading: boolean,
                connectedAppsLoading: boolean,
                connectedAppsLoadFailed: boolean,
                partnersAwaitingChoice: ConnectedAppApi[]
            ): string | null => {
                if (revokingAppId) {
                    return 'Disconnecting app…'
                }
                if (keysLoading || passkeysLoading || connectedAppsLoading) {
                    return 'Loading your credentials…'
                }
                if (connectedAppsLoadFailed) {
                    return 'Could not load your connected apps. Reload the page to try again.'
                }
                if (partnersAwaitingChoice.length > 0) {
                    return 'Choose to keep or disconnect each app above'
                }
                return null
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        keepPartnerConnected: ({ appId }) => {
            posthog.capture(PARTNER_ACCESS_CHOSEN_EVENT, { choice: 'keep', application_id: appId })
        },
        disconnectPartner: ({ appId }) => {
            if (values.revokingAppId || values.isCompleting) {
                return
            }
            posthog.capture(PARTNER_ACCESS_CHOSEN_EVENT, { choice: 'disconnect', application_id: appId })
            actions.revokeApp(appId)
        },
        markComplete: async () => {
            if (values.isCompleting || values.continueDisabledReason) {
                return
            }
            actions.setCompleting(true)
            try {
                await usersCredentialsReviewCompleteCreate('@me')
            } catch {
                lemonToast.error('Could not save your review. Try again.')
                actions.setCompleting(false)
                return
            }
            // Flip the local user state's requires_credential_review via reducer before
            // navigating: a stale in-flight loadUser response would otherwise re-trigger
            // the post-login redirect from userLogic.loadUserSuccess.
            userLogic.actions.credentialReviewDismissed()
            userLogic.actions.loadUser()
            const nextPath = getRelativeNextPath(router.values.searchParams['next'], location)
            router.actions.push(nextPath ?? urls.projectHomepage())
        },
    })),
    afterMount(({ actions }) => {
        // Neither logic auto-loads its list on mount, so trigger both here. Otherwise
        // the review screen would render empty until the user hit the settings page.
        actions.loadKeys()
        actions.loadPasskeys()
    }),
])