From b6a9cd4dd514b66fbb14af3a54b230645f21662b Mon Sep 17 00:00:00 2001 From: Surbhi Date: Wed, 4 Dec 2024 14:54:45 -0500 Subject: [PATCH] add capture event for org domain --- posthog/api/organization_domain.py | 55 ++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/posthog/api/organization_domain.py b/posthog/api/organization_domain.py index e39b611c1fb32..d563c5dd3edf3 100644 --- a/posthog/api/organization_domain.py +++ b/posthog/api/organization_domain.py @@ -1,5 +1,6 @@ import re from typing import Any, cast +import posthoganalytics from rest_framework import exceptions, request, response, serializers from posthog.api.utils import action @@ -11,10 +12,29 @@ from posthog.models import OrganizationDomain from posthog.models.organization import Organization from posthog.permissions import OrganizationAdminWritePermissions +from posthog.event_usage import groups DOMAIN_REGEX = r"^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$" +def _capture_domain_event(request, domain: OrganizationDomain, event_type: str, properties: dict | None = None) -> None: + if not properties: + properties = {} + + properties.update( + { + "domain": domain.domain, + } + ) + + posthoganalytics.capture( + request.user.distinct_id, + f"organization domain {event_type}", + properties=properties, + groups=groups(domain.organization), + ) + + class OrganizationDomainSerializer(serializers.ModelSerializer): UPDATE_ONLY_WHEN_VERIFIED = ["jit_provisioning_enabled", "sso_enforcement"] @@ -96,3 +116,38 @@ def verify(self, request: request.Request, **kw) -> response.Response: serializer = self.get_serializer(instance=instance) return response.Response(serializer.data) + + def create(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response: + serializer = self.get_serializer(data=request.data) + serializer.is_valid(raise_exception=True) + instance = serializer.save() + + _capture_domain_event( + request, + instance, + "created", + properties={ + "jit_provisioning_enabled": instance.jit_provisioning_enabled, + "sso_enforcement": instance.sso_enforcement or None, + }, + ) + + return response.Response(serializer.data, status=201) + + def destroy(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response: + instance = self.get_object() + + _capture_domain_event( + request, + instance, + "deleted", + properties={ + "is_verified": instance.is_verified, + "had_saml": instance.has_saml, + "had_jit_provisioning": instance.jit_provisioning_enabled, + "had_sso_enforcement": bool(instance.sso_enforcement), + }, + ) + + instance.delete() + return response.Response(status=204)