:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import {
MakeLogicType,
actions,
connect,
isBreakpoint,
kea,
key,
listeners,
path,
props,
reducers,
selectors,
sharedListeners,
} from 'kea'
import type { BreakPointFunction } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { APIScopeObject, AccessControlLevel } from '~/types'
import type { ScopeObjectEnumApi } from 'products/access_control/frontend/generated/api.schemas'
import type { ObjectRuleResource } from '../../../../../../types'
import { accessControlsLogic } from './accessControlsLogic'
import { AccessObjectRule, accessDetailLogic, parseObjectRuleUrl } from './accessDetailLogic'
import type { ScopeType } from './types'
export interface ObjectOption {
id: string
name: string
}
export interface AddObjectOverrideModalLogicProps {
projectId: string
scopeType: ScopeType
subjectId: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface addObjectOverrideModalLogicValues {
objectRuleResourceOptions: ObjectRuleResource[] // accessControlsLogic
objects: AccessObjectRule[] // accessDetailLogic
displayObjectOptions: ObjectOption[]
existingRule: AccessObjectRule | null
isOpen: boolean
level: AccessControlLevel
objectId: string | null
objectInputKey: number
objectOptions: ObjectOption[]
objectOptionsLoading: boolean
resource: APIScopeObject
search: string
selectedObject: ObjectOption | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface addObjectOverrideModalLogicActions {
setObjectRule: (
resource: ScopeObjectEnumApi,
resourceId: string,
level: AccessControlLevel | null
) => {
level: AccessControlLevel | null
resource: ScopeObjectEnumApi
resourceId: string
} // accessDetailLogic
closeModal: () => {
value: true
}
loadObjectOptions: (_: any) => any
loadObjectOptionsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadObjectOptionsSuccess: (
objectOptions: ObjectOption[],
payload?: any
) => {
objectOptions: ObjectOption[]
payload?: any
}
objectResolvedFromUrl: (
option: ObjectOption,
resource: APIScopeObject
) => {
option: ObjectOption
resource: ScopeObjectEnumApi
}
openModal: () => {
value: true
}
resolveObjectUrl: (
resource: APIScopeObject,
lookupId: string
) => {
lookupId: string
resource: ScopeObjectEnumApi
}
setLevel: (level: AccessControlLevel) => {
level: AccessControlLevel
}
setObjectId: (objectId: string | null) => {
objectId: string | null
}
setResource: (resource: APIScopeObject) => {
resource: ScopeObjectEnumApi
}
setSearch: (search: string) => {
search: string
}
setSelectedObject: (option: ObjectOption | null) => {
option: ObjectOption | null
}
submitRule: () => {
value: true
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface addObjectOverrideModalLogicMeta {
key: string
sharedListeners: {
resourceChanged: (
payload: any,
breakpoint: BreakPointFunction,
action: {
type: string
payload: any
},
previousState: any
) => void | Promise<void>
}
__keaTypeGenInternalSelectorTypes: {
existingRule: (
objects: AccessObjectRule[],
resource: ScopeObjectEnumApi,
objectId: string | null
) => AccessObjectRule | null
displayObjectOptions: (objectOptions: ObjectOption[], selectedObject: ObjectOption | null) => ObjectOption[]
}
}
export type addObjectOverrideModalLogicType = MakeLogicType<
addObjectOverrideModalLogicValues,
addObjectOverrideModalLogicActions,
AddObjectOverrideModalLogicProps,
addObjectOverrideModalLogicMeta
>
export const addObjectOverrideModalLogic = kea<addObjectOverrideModalLogicType>([
path((key) => ['scenes', 'access_control', 'addObjectOverrideModalLogic', key]),
props({} as AddObjectOverrideModalLogicProps),
key((props) => `${props.projectId}:${props.scopeType}:${props.subjectId}`),
connect((props: AddObjectOverrideModalLogicProps) => ({
actions: [accessDetailLogic(props), ['setObjectRule']],
values: [
accessDetailLogic(props),
['objects'],
accessControlsLogic({ projectId: props.projectId }),
['objectRuleResourceOptions'],
],
})),
actions({
openModal: true,
closeModal: true,
setResource: (resource: APIScopeObject) => ({ resource }),
setSearch: (search: string) => ({ search }),
setObjectId: (objectId: string | null) => ({ objectId }),
setSelectedObject: (option: ObjectOption | null) => ({ option }),
resolveObjectUrl: (resource: APIScopeObject, lookupId: string) => ({ resource, lookupId }),
objectResolvedFromUrl: (option: ObjectOption, resource: APIScopeObject) => ({ option, resource }),
setLevel: (level: AccessControlLevel) => ({ level }),
submitRule: true,
}),
reducers({
isOpen: [false, { openModal: () => true, closeModal: () => false }],
resource: [
'dashboard' as APIScopeObject,
{
setResource: (_, { resource }) => resource,
// Only a resolved URL flips the type, together with the object it selects; flipping
// on the lookup itself would leave resource and objectId mismatched when it fails
objectResolvedFromUrl: (_, { resource }) => resource,
closeModal: () => 'dashboard' as APIScopeObject,
},
],
search: [
'',
{
setSearch: (_, { search }) => search,
objectResolvedFromUrl: () => '',
setResource: () => '',
closeModal: () => '',
},
],
/**
* Remounts the object input, the only way to clear the text it holds internally: after a
* pasted URL resolves, the leftover URL would otherwise hide the selected object's name.
*/
objectInputKey: [0, { objectResolvedFromUrl: (key) => key + 1 }],
objectId: [
null as string | null,
{
setObjectId: (_, { objectId }) => objectId,
objectResolvedFromUrl: (_, { option }) => option.id,
setResource: () => null,
closeModal: () => null,
},
],
/** The picked option, kept so its label survives the option list reloading. */
selectedObject: [
null as ObjectOption | null,
{
setSelectedObject: (_, { option }) => option,
objectResolvedFromUrl: (_, { option }) => option,
setResource: () => null,
closeModal: () => null,
},
],
level: [
AccessControlLevel.None as AccessControlLevel,
{ setLevel: (_, { level }) => level, closeModal: () => AccessControlLevel.None },
],
}),
loaders(({ props, values }) => ({
objectOptions: [
[] as ObjectOption[],
{
loadObjectOptions: async (_, breakpoint) => {
await breakpoint(300)
// One backend endpoint serves every resource type with correct display names
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
const response = await api.get<{ results: ObjectOption[] }>(
`api/projects/${props.projectId}/access_control_object_search?resource=${values.resource}&search=${encodeURIComponent(
values.search
)}`
)
return response.results
},
},
],
})),
selectors({
/** The rule already stored for the picked object, so the modal offers an update, not a silent overwrite. */
existingRule: [
(s) => [s.objects, s.resource, s.objectId],
(objects: AccessObjectRule[], resource: APIScopeObject, objectId: string | null): AccessObjectRule | null =>
objectId ? (objects.find((o) => o.resource === resource && o.resource_id === objectId) ?? null) : null,
],
// Selecting an option resets the search, which reloads the options; keep the picked one in
// the list so LemonInputSelect can render its name instead of the raw id
displayObjectOptions: [
(s) => [s.objectOptions, s.selectedObject],
(objectOptions: ObjectOption[], selectedObject: ObjectOption | null): ObjectOption[] =>
selectedObject && !objectOptions.some((o) => o.id === selectedObject.id)
? [selectedObject, ...objectOptions]
: objectOptions,
],
}),
sharedListeners(({ actions, values }) => ({
resourceChanged: () => {
actions.loadObjectOptions(null)
// Some resources enforce a minimum level (an action rule cannot be "No access"), so a
// level carried over from the previous type could be one the backend rejects
const option = values.objectRuleResourceOptions.find((r) => r.resource === values.resource)
if (!option) {
return
}
const levels = option.available_access_levels
if (levels.indexOf(values.level) < levels.indexOf(option.minimum_access_level)) {
actions.setLevel(option.minimum_access_level)
}
},
})),
listeners(({ props, actions, values, sharedListeners }) => ({
openModal: () => actions.loadObjectOptions(null),
setResource: [sharedListeners.resourceChanged],
// A resolved URL changes the type too, so the options have to follow it. Without this the
// list still holds the previous type's objects, and picking one pairs its id with the new type
objectResolvedFromUrl: [sharedListeners.resourceChanged],
setSearch: ({ search }) => {
// A pasted URL selects the exact object instead of searching by name
const parsed = parseObjectRuleUrl(search)
if (parsed) {
actions.resolveObjectUrl(parsed.resource, parsed.id)
return
}
actions.loadObjectOptions(null)
},
resolveObjectUrl: async ({ resource, lookupId }, breakpoint) => {
// Debounced and cancelled like the options loader: setSearch fires per keystroke, and
// without the breakpoint a slower earlier paste could land after a faster later one
// and silently replace the selection
await breakpoint(300)
try {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
const response = await api.get<{ results: ObjectOption[] }>(
`api/projects/${props.projectId}/access_control_object_search?resource=${resource}&id=${encodeURIComponent(
lookupId
)}`
)
breakpoint()
const option = response.results[0]
if (!option) {
lemonToast.error("Couldn't find that object in this project")
return
}
actions.objectResolvedFromUrl(option, resource)
} catch (e: any) {
if (isBreakpoint(e)) {
throw e
}
lemonToast.error("Couldn't find that object in this project")
}
},
setObjectId: ({ objectId }) => {
actions.setSelectedObject(objectId ? (values.objectOptions.find((o) => o.id === objectId) ?? null) : null)
},
submitRule: () => {
// isOpen guards a double click: the first submit closes the modal synchronously
if (!values.isOpen || !values.objectId) {
return
}
actions.setObjectRule(values.resource, values.objectId, values.level)
actions.closeModal()
},
})),
])