repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
posthog | posthog/api/user_integration.py | .py | """Personal Settings β Personal integrations: manage the user's own GitHub integrations.
A ``UserIntegration`` (kind=github) stores the user's own GitHub App installation
plus user-to-server tokens. This gives the user independent repo access at the
personal level, separate from any team-level ``Integration``.
A user... | 790 | 35,894 |
posthog | posthog/api/integration.py | .py | import os
import re
import json
from collections.abc import Iterable
from typing import Any, NoReturn, Protocol, cast
from urllib.parse import urlencode
from django.conf import settings
from django.core.cache import cache
from django.db import transaction
from django.db.models import Q, QuerySet
from django.http impor... | 1,944 | 88,754 |
posthog | posthog/api/secret_revocation.py | .py | import re
from typing import Literal
from posthog.api.personal_api_key import PersonalAPIKeySerializer
from posthog.api.project_secret_api_key import roll_project_secret_api_key_and_notify
from posthog.dataclasses import frozen
from posthog.models.oauth import find_oauth_access_token, find_oauth_refresh_token, revoke_... | 173 | 7,840 |
posthog | posthog/api/identity_provider_config.py | .py | from typing import Any, cast
import posthoganalytics
from drf_spectacular.utils import extend_schema
from rest_framework import exceptions, request, response, serializers, status
from rest_framework.request import Request
from rest_framework.viewsets import ModelViewSet
from posthog.api.routing import TeamAndOrgViewS... | 247 | 10,662 |
posthog | posthog/api/two_factor_reset.py | .py | import time
from typing import cast
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils.crypto import constant_time_compare
from django.utils.http import base36_to_int
import structlog
from rest_framework import permissions, stat... | 285 | 11,186 |
posthog | posthog/api/query.py | .py | import re
from time import perf_counter
from typing import NoReturn
from django.core.cache import cache
from django.http import JsonResponse
from django.http.response import HttpResponseBase
import orjson
import structlog
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParamete... | 539 | 25,065 |
posthog | posthog/api/two_factor_qrcode.py | .py | """
Cache-aware QR code view for django-two-factor-auth to handle session race conditions.
"""
from two_factor.views import QRGeneratorView
from posthog.helpers.session_cache import SessionCache
class CacheAwareQRGeneratorView(QRGeneratorView):
"""
QR view that retrieves secrets from cache to avoid session ... | 28 | 975 |
posthog | posthog/api/product_enablement.py | .py | """Proactive product enablement for self-driving Signals setup.
Turns PostHog products ON so their signal sources have data to read. The wizard
calls this (via the `products-enable` MCP tool) before it enables sources, so a
freshly-instrumented project isn't left with empty inboxes.
Exposed under a narrow `product_en... | 149 | 6,340 |
posthog | posthog/api/hog.py | .py | import structlog
from rest_framework import status, viewsets
from rest_framework.response import Response
from posthog.schema import HogCompileResponse
from posthog.hogql.compiler.bytecode import Local, create_bytecode
from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.parser import parse_program
... | 47 | 1,964 |
posthog | posthog/api/query_performance_proxy.py | .py | """OAuth-gated ClickHouse passthrough for query-performance autoresearch.
Stub: route + M2M auth only. The execution layer that forwards SQL to the
``autoresearch`` ClickHouse user will be added in a follow-up PR.
"""
from __future__ import annotations
from drf_spectacular.utils import extend_schema
from rest_framew... | 79 | 3,322 |
posthog | posthog/api/uploaded_media.py | .py | from io import BytesIO
from typing import Optional
from urllib.parse import quote
from django.http import HttpResponse
from django.utils.http import content_disposition_header
from django.views.decorators.csrf import csrf_exempt
import structlog
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.util... | 238 | 9,484 |
posthog | posthog/api/streaming.py | .py | import time
import random
import asyncio
import threading
from collections import deque
from collections.abc import AsyncGenerator, AsyncIterable, AsyncIterator, Generator, Iterable, Iterator
from http import HTTPStatus
from django.conf import settings
from django.db import connections
from django.http import HttpResp... | 369 | 15,229 |
posthog | posthog/api/query_coalescer.py | .py | import re
import time
import uuid
import hashlib
import threading
from enum import StrEnum
from typing import TYPE_CHECKING, Optional
from urllib.parse import parse_qs, urlencode
from django.http import HttpRequest, HttpResponse
import orjson
import structlog
import posthoganalytics
from prometheus_client import Coun... | 441 | 16,722 |
posthog | posthog/api/log_entries.py | .py | import dataclasses
from datetime import UTC, datetime, timedelta
from typing import Any, Optional, cast
from drf_spectacular.utils import extend_schema
from rest_framework import serializers, viewsets
from rest_framework.exceptions import ValidationError
from rest_framework.request import Request
from rest_framework.r... | 185 | 7,016 |
posthog | posthog/api/proxy_record_diagnostics.py | .py | """
Reverse proxy diagnostics.
Runs a sequence of synchronous checks against a ProxyRecord and returns a structured
DiagnosticReport. Called from the in-app /diagnose API endpoint when a user clicks
"Diagnose" on a proxy that's stuck or erroring.
Intentionally not called from the daily monitor workflow β that one sta... | 770 | 31,907 |
posthog | posthog/api/github.py | .py | import base64
from hashlib import sha256
from typing import Any
from django.conf import settings
from django.db.models import Q
import requests
import structlog
import posthoganalytics
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes, serialization
from cryptograp... | 366 | 13,811 |
posthog | posthog/api/personal_api_key.py | .py | import uuid
from typing import cast
from django.utils import timezone
import posthoganalytics
from drf_spectacular.utils import extend_schema, extend_schema_field
from rest_framework import response, serializers, status, viewsets
from rest_framework.permissions import BasePermission, IsAuthenticated
from posthog.api... | 300 | 13,173 |
posthog | posthog/api/health_issue.py | .py | from django.db.models import Case, Count, QuerySet, When
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import (
OpenApiParameter,
OpenApiResponse,
extend_schema,
extend_schema_field,
extend_schema_view,
)
from rest_framework import serializers
from rest_framework.decorat... | 375 | 15,890 |
posthog | posthog/api/unsubscribe.py | .py | from django.http import HttpRequest, JsonResponse
import jwt
from products.exports.backend.models.subscription import unsubscribe_using_token
def unsubscribe(request: HttpRequest):
token = request.GET.get("token")
if not token:
return JsonResponse({"success": False})
try:
unsubscribe_us... | 19 | 457 |
posthog | posthog/api/ingestion_warnings.py | .py | import json
from datetime import timedelta
from django.utils.timezone import now
from rest_framework import viewsets
from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.documentation import _FallbackSerializer
from posthog.api.routing import TeamAndOrgViewSetMixin... | 83 | 2,996 |
posthog | posthog/api/object_media_preview.py | .py | from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.models import EventDefinition, ObjectMediaPreview,... | 153 | 5,919 |
posthog | posthog/api/proxy_record.py | .py | import time
import asyncio
import hashlib
from django.conf import settings
from django.core.cache import cache
import posthoganalytics
from drf_spectacular.utils import extend_schema
from rest_framework import serializers, status
from rest_framework.decorators import action
from rest_framework.exceptions import NotFo... | 448 | 19,054 |
posthog | posthog/api/quick_filters.py | .py | from django.db import connection, transaction
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers, viewsets
from rest_framework.exceptions import ValidationError
from posthog.schema import QuickFilterContext as QuickFilterContextEnum
from posthog.api.routing import TeamAndOrg... | 179 | 7,003 |
posthog | posthog/api/organization_integration.py | .py | from typing import Any
import structlog
from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import mixins, serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import APIException
from rest_framework.request import Request
from rest_... | 205 | 8,301 |
posthog | posthog/api/web_vitals.py | .py | from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema
from rest_framework import exceptions, status, viewsets
from rest_framework.exceptions import ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
from pos... | 98 | 3,877 |
posthog | posthog/api/capture.py | .py | """capture_internal β batch-native client for the v1 analytics capture endpoint.
This module provides the PREFERRED method for publishing analytics events from the Django
app on behalf of customer teams/projects. PLEASE DO NOT write events directly to
ingestion Kafka topics β USE THIS! The capture-rs pipeline handle... | 842 | 36,817 |
posthog | posthog/api/routing.py | .py | import sys
from functools import cached_property, lru_cache
from typing import TYPE_CHECKING, Any, Literal, Optional, cast
from uuid import UUID
from django.db.models.query import QuerySet
from opentelemetry import trace
from rest_framework.exceptions import AuthenticationFailed, NotFound, ValidationError
from rest_f... | 648 | 28,674 |
posthog | posthog/api/signup.py | .py | import json
import uuid as uuid_module
from datetime import timedelta
from typing import Any, Optional, TypedDict, Union, cast
from urllib.parse import quote, urlencode
from django import forms
from django.conf import settings
from django.contrib.auth import login, password_validation
from django.contrib.sessions.back... | 1,118 | 50,427 |
posthog | posthog/api/report.py | .py | from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import structlog
from rest_framework import status
from posthog.api.capture import CaptureInternalError, capture_batch_internal, capture_internal
from posthog.api.csp import process... | 112 | 4,357 |
posthog | posthog/api/event_definition_generators/typescript.py | .py | from datetime import datetime
from django.db.models import QuerySet
import orjson
from ...models import EventDefinition, SchemaPropertyGroupProperty
from .base import EventDefinitionGenerator
class TypeScriptGenerator(EventDefinitionGenerator):
def generator_version(self) -> str:
return "1.1.0"
de... | 212 | 7,775 |
posthog | posthog/api/event_definition_generators/golang.py | .py | import re
from datetime import datetime
from django.db.models import QuerySet
import orjson
from ...models import EventDefinition, SchemaPropertyGroupProperty
from .base import EventDefinitionGenerator
class GolangGenerator(EventDefinitionGenerator):
def generator_version(self) -> str:
return "1.1.0"
... | 434 | 15,030 |
posthog | posthog/api/event_definition_generators/python.py | .py | import re
from datetime import datetime
from django.db.models import QuerySet
import orjson
from ...models import EventDefinition, SchemaPropertyGroupProperty
from .base import EventDefinitionGenerator
class PythonGenerator(EventDefinitionGenerator):
def generator_version(self) -> str:
return "1.1.0"
... | 281 | 9,303 |
posthog | posthog/api/event_definition_generators/base.py | .py | import hashlib
from abc import ABC, abstractmethod
from django.db.models import Exists, OuterRef, Q, QuerySet
import orjson
from posthog.event_usage import report_user_action
from posthog.models import EventDefinition, EventSchema, SchemaPropertyGroupProperty
from posthog.taxonomy.taxonomy import CORE_EVENTS
class... | 126 | 4,753 |
posthog | posthog/api/file_system/file_system_shortcut.py | .py | from typing import Any, cast
from django.db import transaction
from django.db.models import Case, Q, QuerySet, When
from django.db.models.functions import Lower
from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import serializers, status, viewsets
from rest_framework.decorators impo... | 150 | 6,706 |
posthog | posthog/api/file_system/file_system.py | .py | import re
import json
import shlex
import logging
import builtins
from functools import cached_property
from typing import Any, Optional, cast
from uuid import UUID
from django.db import transaction
from django.db.models import Case, F, IntegerField, Q, QuerySet, Value, When
from django.db.models.functions import Conc... | 1,162 | 53,291 |
posthog | posthog/api/file_system/access_levels.py | .py | import logging
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from typing import Any, Optional, cast
from django.apps import apps
from django.core.cache import cache
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db.models import BigIntegerFiel... | 474 | 23,472 |
posthog | posthog/api/file_system/deletion.py | .py | from __future__ import annotations
import logging
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Literal
from django.apps import apps
from django.core.exceptions import (
ObjectDoesNotExist,
ValidationError as DjangoValidationError,
)
from posthog.models.file_s... | 470 | 15,796 |
posthog | posthog/api/file_system/user_product_list.py | .py | from typing import Any, cast
from django.db import transaction
from django.db.models import QuerySet
from django.db.models.functions import Lower
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.respons... | 98 | 3,421 |
posthog | posthog/api/file_system/registrations.py | .py | from __future__ import annotations
from typing import Any
from posthog.api.file_system.deletion import (
HOG_FUNCTION_TYPES,
DeletionContext,
RestoreContext,
register_file_system_type,
register_post_delete_hook,
register_post_restore_hook,
register_pre_delete_hook,
register_pre_restore... | 435 | 14,280 |
posthog | posthog/api/file_system/file_system_logging.py | .py | from __future__ import annotations
from datetime import datetime
from typing import Any, Optional, cast
from django.conf import settings
from django.http import HttpRequest
from rest_framework.request import Request
from posthog.models.activity_logging.model_activity import is_impersonated_session
from posthog.mode... | 69 | 1,939 |
posthog | posthog/api/file_system/test/test_file_system_shortcut.py | .py | from datetime import timedelta
from posthog.test.base import APIBaseTest
from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
from posthog.models import User
from posthog.models.file_system.file_system_shortcut import FileSystemShortcut
from products.dashboard... | 225 | 11,089 |
posthog | posthog/api/file_system/test/test_file_system.py | .py | from collections.abc import Callable, Iterable, Mapping
from datetime import UTC
from typing import Any, TypedDict, cast
import pytest
from freezegun import freeze_time
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.core.cache import cache
from django.db import connection
from d... | 2,445 | 110,998 |
posthog | posthog/api/oauth/test_views.py | .py | import os
import json
import base64
import hashlib
import importlib
from datetime import timedelta
from types import SimpleNamespace
from typing import Optional, cast
from urllib.parse import parse_qs, quote, urlencode, urlparse, urlunparse
import pytest
from freezegun import freeze_time
from posthog.test.base import ... | 5,198 | 236,319 |
posthog | posthog/api/oauth/cimd.py | .py | """
OAuth Client ID Metadata Document (CIMD)
draft-ietf-oauth-client-id-metadata-document-00
Allows MCP clients to use an HTTPS URL as their client_id. The authorization
server fetches client metadata (name, redirect URIs, logo) from that URL,
removing the need for pre-registration or Dynamic Client Registration.
"""
... | 1,080 | 47,692 |
posthog | posthog/api/oauth/test_cimd.py | .py | import json
import base64
import hashlib
from ipaddress import ip_address
from typing import cast
from urllib.parse import urlencode
import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from django.core.cache import cache as real_cache
from django.test import SimpleTestCa... | 1,540 | 73,621 |
posthog | posthog/api/oauth/client_assertion.py | .py | """``private_key_jwt`` client authentication (RFC 7521 / RFC 7523 section 2.2).
A client authenticates by signing a short-lived JWT with its private key instead of
presenting a shared secret. We verify the signature against the public keys the client
publishes at its ``jwks_uri``, so no credential ever has to be trans... | 314 | 14,543 |
posthog | posthog/api/oauth/test_client_name.py | .py | from unittest import TestCase
from parameterized import parameterized
from rest_framework import serializers
from posthog.api.oauth.client_name import CLIENT_NAME_MAX_LENGTH, sanitize_client_name, validate_client_name
class TestSanitizeClientName(TestCase):
@parameterized.expand(
[
("plain_n... | 64 | 2,672 |
posthog | posthog/api/oauth/test_dcr.py | .py | import base64
import hashlib
from urllib.parse import parse_qs, urlparse
from posthog.test.base import APIBaseTest
from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIClient
from posthog.api.oauth.client_name import sanitize_client_name
from posthog.models.oau... | 533 | 22,175 |
posthog | posthog/api/oauth/test_hogli_metadata.py | .py | import json
from ipaddress import ip_address
from urllib.parse import urlparse
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase, override_settings
from oauth2_provider.models import AbstractApplication
from parameterized import parameterized
... | 125 | 5,880 |
posthog | posthog/api/oauth/client_auth.py | .py | """Client authentication primitives shared by every OAuth token consumer.
Both the oauthlib-backed ``/oauth/token`` endpoint and the hand-rolled agentic token
endpoint have to answer the same question -- has this client proven it is who it claims to
be -- so the comparison itself lives here rather than being written o... | 81 | 3,269 |
posthog | posthog/api/oauth/application.py | .py | from drf_spectacular.utils import extend_schema, extend_schema_field
from rest_framework import mixins, serializers, viewsets
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.models.oauth import OAuthApplication
class OrganizationOAuthApplicationSerializer(serializers.ModelSerializer):
"""Seri... | 46 | 1,482 |
posthog | posthog/api/oauth/__init__.py | .py | # Re-export for backwards compatibility
from posthog.api.oauth.application import OrganizationOAuthApplicationSerializer, OrganizationOAuthApplicationViewSet
from posthog.api.oauth.cimd import get_application_by_client_id, is_cimd_client_id
from posthog.api.oauth.dcr import (
DCRBurstThrottle,
DCRRequestSeriali... | 51 | 1,485 |
posthog | posthog/api/oauth/mcp_resource_scopes.py | .py | from __future__ import annotations
import os
import json
from functools import lru_cache
from typing import TypedDict
from urllib.parse import urlparse
import structlog
from posthog.cloud_utils import is_dev_mode
from posthog.scopes import get_oauth_scopes_supported
from posthog.settings.base_variables import BASE_D... | 95 | 3,413 |
posthog | posthog/api/oauth/test_application.py | .py | from posthog.test.base import APIBaseTest
from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIClient
from posthog.models.oauth import OAuthApplication
from posthog.models.organization import Organization
class TestOrganizationOAuthApplicationViewSet(APIBaseTe... | 99 | 4,643 |
posthog | posthog/api/oauth/toolbar_service.py | .py | """
Toolbar OAuth backend primitives.
Non-obvious behavior documented here:
- We keep one OAuth app per organization (not global, not per team).
- The redirect URI is derived from settings.SITE_URL (one per deployment).
- OAuth state is both signed and one-time-use (cache-backed) to prevent replay.
"""
import re
impo... | 386 | 14,495 |
posthog | posthog/api/oauth/connected_apps.py | .py | from django.utils import timezone
from drf_spectacular.utils import extend_schema
from rest_framework import serializers, status, viewsets
from rest_framework.request import Request
from rest_framework.response import Response
from posthog.auth import SessionAuthentication
from posthog.models.oauth import OAuthAccess... | 100 | 4,014 |
posthog | posthog/api/oauth/views.py | .py | import json
import uuid
import hashlib
import calendar
from datetime import datetime, timedelta
from typing import TypedDict, cast
from urllib.parse import parse_qs, urlparse
from django.conf import settings
from django.core.exceptions import DisallowedRedirect
from django.db import DatabaseError, OperationalError
fro... | 2,245 | 108,687 |
posthog | posthog/api/oauth/test_mcp_resource_scopes.py | .py | import os
import json
import tempfile
from unittest.mock import patch
from django.test import SimpleTestCase, override_settings
from posthog.api.oauth.mcp_resource_scopes import (
_tool_required_scopes,
build_oauth_mcp_consent_context,
is_trusted_posthog_mcp_resource,
mcp_advertised_scopes,
)
class... | 103 | 4,724 |
posthog | posthog/api/oauth/test_wizard_metadata.py | .py | from django.test import SimpleTestCase, override_settings
@override_settings(SITE_URL="https://us.posthog.com")
class TestWizardClientMetadataView(SimpleTestCase):
def test_returns_valid_cimd_metadata(self):
res = self.client.get("/api/oauth/wizard/client-metadata")
assert res.status_code == 200
... | 40 | 1,746 |
posthog | posthog/api/oauth/client_name.py | .py | """
Shared validation and HTML-safety helpers for OAuth client names.
Client names are untrusted input β they arrive from an unauthenticated DCR request body
(RFC 7591) or a partner-controlled CIMD metadata document β and surface on the OAuth
consent screen. Both ingestion paths (`dcr.py`, `cimd.py`) share these helpe... | 54 | 2,396 |
posthog | posthog/api/oauth/test_connected_apps.py | .py | import uuid
from datetime import timedelta
from freezegun import freeze_time
from posthog.test.base import APIBaseTest
from django.utils import timezone
from rest_framework import status
from rest_framework.test import APIClient
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthGrant, OAuthR... | 186 | 6,871 |
posthog | posthog/api/oauth/test_client_auth.py | .py | from django.contrib.auth.hashers import make_password
from django.test import SimpleTestCase
from parameterized import parameterized
from posthog.api.oauth.client_auth import verify_client_secret
from posthog.api.oauth.views import OAuthValidator
class TestVerifyClientSecret(SimpleTestCase):
@parameterized.expa... | 34 | 1,758 |
posthog | posthog/api/oauth/test_raycast_metadata.py | .py | import json
from ipaddress import ip_address
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase, override_settings
from oauth2_provider.models import AbstractApplication
from parameterized import parameterized
from posthog.api.oauth.cimd impor... | 96 | 4,233 |
posthog | posthog/api/oauth/raycast_metadata.py | .py | from django.conf import settings
from django.http import JsonResponse
from django.views import View
RAYCAST_METADATA_PATH = "api/oauth/raycast/client-metadata"
# Scope ceiling for tokens issued to the Raycast extension. OIDC scopes
# (openid/profile/email) bypass the ceiling via ALWAYS_ALLOWED_SCOPES.
RAYCAST_SCOPES ... | 48 | 1,566 |
posthog | posthog/api/oauth/test_client_assertion.py | .py | import json
import time
from typing import cast
from posthog.test.base import BaseTest
from unittest.mock import patch
from django.core.cache import cache
from django.test import override_settings
import jwt
from cryptography.hazmat.primitives.asymmetric import rsa
from parameterized import parameterized
from rest_f... | 271 | 12,351 |
posthog | posthog/api/oauth/wizard_metadata.py | .py | from django.conf import settings
from django.http import JsonResponse
from django.views import View
WIZARD_METADATA_PATH = "api/oauth/wizard/client-metadata"
class WizardClientMetadataView(View):
"""
Serves a static CIMD (Client ID Metadata Document) for the PostHog Wizard CLI.
The client_id in the resp... | 34 | 1,096 |
posthog | posthog/api/oauth/dcr.py | .py | """
OAuth 2.0 Dynamic Client Registration (RFC 7591)
Allows MCP clients to register themselves without prior authentication.
This is required by the MCP OAuth specification for seamless client onboarding.
Supports both public clients (token_endpoint_auth_method: "none") and
confidential clients (token_endpoint_auth_m... | 246 | 10,251 |
posthog | posthog/api/oauth/hogli_metadata.py | .py | from django.conf import settings
from django.http import JsonResponse
from django.views import View
HOGLI_METADATA_PATH = "api/oauth/hogli/client-metadata"
# Scope ceiling: /authorize clamps to this, so keep it to what a hogli command actually reads.
HOGLI_SCOPES = [
"engineering_analytics:read",
]
# Tracked on ... | 49 | 1,826 |
posthog | posthog/api/services/flags_service.py | .py | """
Shared utilities for proxying flag evaluation requests to the Rust flags service.
All flag evaluation (decide, toolbar, local eval API, etc.) now goes through the Rust
flags service. This module provides a shared HTTP client and proxy function.
"""
import time
from typing import Any
from django.conf import setti... | 214 | 9,351 |
posthog | posthog/api/services/llm_prompt.py | .py | import json
from dataclasses import dataclass
from typing import Any
from django.conf import settings
from django.db import IntegrityError, transaction
from django.db.models import QuerySet
from posthog.api.llm_prompt_serializers import MAX_PROMPT_PAYLOAD_BYTES
from posthog.exceptions_capture import capture_exception... | 447 | 15,436 |
posthog | posthog/api/services/query.py | .py | from dataclasses import dataclass
from typing import Literal, Optional, overload
import structlog
import pydantic_core
from pydantic import BaseModel
from rest_framework.exceptions import APIException, ValidationError
from posthog.schema import (
DashboardFilter,
DatabaseSchemaQuery,
DatabaseSchemaQueryRe... | 384 | 14,985 |
posthog | posthog/api/wizard/utils.py | .py | from __future__ import annotations
from typing import Any
from google.genai.types import Type
def get_type_enum(json_type: str) -> Type:
"""Convert JSON Schema type to Gemini Type enum"""
type_mapping = {
"string": Type.STRING,
"number": Type.NUMBER,
"integer": Type.INTEGER,
... | 75 | 2,207 |
posthog | posthog/api/wizard/http.py | .py | from __future__ import annotations
import json
import time
import hashlib
from typing import NoReturn, cast
from django.conf import settings
from django.core.cache import cache
from django.utils.crypto import get_random_string
import posthoganalytics
from drf_spectacular.utils import extend_schema
from google.genai.... | 539 | 21,337 |
posthog | posthog/api/wizard/test/test_http.py | .py | import json
from datetime import timedelta
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils import timezone
from rest_framework import status
from posth... | 578 | 24,730 |
posthog | posthog/api/wizard/test/test_utils.py | .py | from unittest import TestCase
from google.genai.types import Type
from ..utils import convert_schema, json_schema_to_gemini_schema
class TestSchemaConversion(TestCase):
def test_convert_schema_basic_types(self):
string_schema = {"type": "string"}
result = convert_schema(string_schema)
as... | 160 | 6,139 |
posthog | posthog/api/github_callback/types.py | .py | """Constants and small helpers shared across the GitHub callback modules."""
import re
from enum import StrEnum
from typing import Any, Literal, Self
from urllib.parse import parse_qsl, urlencode, urlparse
from django.conf import settings
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, ValidationErr... | 173 | 6,261 |
posthog | posthog/api/github_callback/state.py | .py | from typing import cast
from urllib.parse import parse_qsl
from django.core.cache import cache
from rest_framework.exceptions import ValidationError
from rest_framework.request import Request
from posthog.api.github_callback.types import (
GITHUB_AUTHORIZE_STATE_CACHE_TTL_SECONDS,
GITHUB_UNIFIED_AUTHORIZE_CA... | 196 | 8,330 |
posthog | posthog/api/github_callback/installation_events.py | .py | """Inbound GitHub App ``installation`` webhook handling.
This is the inbound side of bi-directional uninstall: when an account owner
uninstalls the App on GitHub, GitHub sends an ``installation`` event with
``action == "deleted"``. We then remove every PostHog row that referenced the
installation so we don't keep dead... | 81 | 3,447 |
posthog | posthog/api/github_callback/redirects.py | .py | from urllib.parse import parse_qsl, urlencode, urlparse
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from posthog.api.github_callback.types import (
ACCOUNT_CONNECTED_GITHUB_INTEGRATION_PATH,
MOBILE_GITHUB_CALLBACK_URL,
PERSONAL_INTEGRATIONS_SETTINGS_PATH,
FinishR... | 96 | 3,634 |
posthog | posthog/api/github_callback/views.py | .py | from typing import Literal, cast
from django.core.cache import cache
from django.http import HttpRequest, HttpResponseRedirect
from django.views.decorators.http import require_http_methods
from posthog.api.github_callback import personal_finish, redirects, state, team_services
from posthog.api.github_callback.types i... | 145 | 6,646 |
posthog | posthog/api/github_callback/team_services.py | .py | import os
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any, cast
from urllib.parse import parse_qsl, urlencode, urlparse
from django.core.cache import cache
from django.http import HttpRequest
from django.utils.crypto import get_random_string
import requests
import structlog... | 867 | 36,140 |
posthog | posthog/api/github_callback/personal_state.py | .py | """Read-only helpers for a user's *personal* GitHub App state.
Distinct from ``team_services.py``, which manages team-scoped ``Integration`` rows: this module
answers what a user's own OAuth-linked ``UserIntegration`` can see on GitHub, independent of any
team. Shared by the personal "unlinked installations" check, th... | 104 | 3,844 |
posthog | posthog/api/github_callback/personal_finish.py | .py | from typing import cast
from urllib.parse import parse_qs, urlencode
from django.core.cache import cache
from django.http import HttpRequest
from django.utils.crypto import get_random_string
import requests
import structlog
from posthog.api.github_callback import state
from posthog.api.github_callback.types import (... | 261 | 11,092 |
posthog | posthog/api/test/test_report.py | .py | import json
from freezegun import freeze_time
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.test.client import Client
from parameterized import parameterized
from rest_framework import status
from structlog.testing import capture_logs
from posthog.api.csp import CSP_R... | 602 | 26,474 |
posthog | posthog/api/test/test_streaming.py | .py | import gc
import asyncio
from collections.abc import AsyncGenerator, AsyncIterable, AsyncIterator, Iterator
from http import HTTPStatus
from typing import cast
import pytest
from unittest import mock
from django.http import StreamingHttpResponse
from django.http.response import HttpResponseBase
from django.test impor... | 343 | 16,123 |
posthog | posthog/api/test/test_sharing_access_token_security.py | .py | """
Security tests for sharing access tokens - ensuring they cannot be abused to access unauthorized resources.
"""
import json
from datetime import timedelta
from typing import Any, cast
from freezegun import freeze_time
from posthog.test.base import APIBaseTest
from django.conf import settings
from django.utils im... | 573 | 26,137 |
posthog | posthog/api/test/test_quick_filters.py | .py | from posthog.test.base import APIBaseTest
from django.test import override_settings
from rest_framework import status
from posthog.models.quick_filter import QuickFilter
from products.dashboards.backend.models.dashboard import Dashboard
@override_settings(IN_UNIT_TESTING=True)
class TestQuickFilters(APIBaseTest):... | 136 | 5,441 |
posthog | posthog/api/test/test_comment_slack_sync.py | .py | from datetime import timedelta
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from django.utils import timezone
from celery.exceptions import Retry
from parameterized import parameterized
from rest_framework import status
from slack_sdk.errors import SlackApiError
from posthog.... | 635 | 29,523 |
posthog | posthog/api/test/test_event.py | .py | import json
from datetime import datetime
from urllib.parse import unquote, urlencode
from zoneinfo import ZoneInfo
from freezegun import freeze_time
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
_create_event,
_create_person,
also_test_with_materialized_columns,
flush_perso... | 1,710 | 71,437 |
posthog | posthog/api/test/test_role_external_reference.py | .py | from parameterized import parameterized
from rest_framework import status
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.role_external_reference import RoleExternalReference
from ee.api.test.base import APILicensedTest
from ee.models.rbac.role import Role
class Test... | 167 | 6,948 |
posthog | posthog/api/test/test_github_installation_webhook.py | .py | import hmac
import json
import hashlib
from unittest.mock import MagicMock, patch
from django.test import TestCase, override_settings
from parameterized import parameterized
from rest_framework.test import APIClient
from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integra... | 198 | 9,166 |
posthog | posthog/api/test/test_schema_property_group.py | .py | from posthog.test.base import APIBaseTest
from rest_framework import status
from posthog.models import EventDefinition, EventSchema, Project, SchemaPropertyGroup, SchemaPropertyGroupProperty
class TestSchemaPropertyGroupAPI(APIBaseTest):
def test_create_property_group_with_properties(self):
response = s... | 325 | 14,361 |
posthog | posthog/api/test/test_documentation_lint_hook.py | .py | """Tests for posthog.api.documentation.lint_spec_consistency_hook."""
import pytest
from unittest.mock import patch
from posthog.api.documentation import lint_spec_consistency_hook
@pytest.mark.parametrize(
"operation_id,should_warn",
[
("llm_analytics_personal_spend_list", False),
("clean_s... | 57 | 2,126 |
posthog | posthog/api/test/test_properties_timeline.py | .py | import json
import uuid
import random
from typing import Optional
from freezegun.api import freeze_time
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
_create_event,
_create_person,
also_test_with_materialized_columns,
flush_persons_and_events,
snapshot_clickhouse_queries... | 781 | 28,524 |
posthog | posthog/api/test/test_circular_dependency_detection.py | .py | """
Tests for circular dependency detection in feature flags.
"""
from posthog.test.base import APIBaseTest
from parameterized import parameterized
from rest_framework import status
from products.feature_flags.backend.models.feature_flag import FeatureFlag
class TestCircularDependencyDetection(APIBaseTest):
""... | 245 | 9,413 |
posthog | posthog/api/test/test_preflight.py | .py | import os
from datetime import datetime
from typing import cast
import pytest
from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_queries
from unittest.mock import patch
from django.conf import settings
from django.test import override_settings
from django.utils import timezone
from param... | 359 | 15,117 |
posthog | posthog/api/test/test_organization_integration.py | .py | from posthog.test.base import APIBaseTest
from unittest.mock import patch
from rest_framework import status
from posthog.models.integration import Integration
from posthog.models.organization import OrganizationMembership
from posthog.models.organization_integration import OrganizationIntegration
class TestOrganiza... | 213 | 9,811 |
posthog | posthog/api/test/test_team_default_release_conditions.py | .py | from posthog.test.base import APIBaseTest
from parameterized import parameterized
from rest_framework import status
from posthog.models import OrganizationMembership
from posthog.models.team.extensions import get_or_create_team_extension
from products.feature_flags.backend.models import TeamFeatureFlagDefaultsConfig... | 181 | 6,881 |
posthog | posthog/api/test/test_signup.py | .py | import uuid
from datetime import datetime, timedelta
from typing import Optional, cast
from zoneinfo import ZoneInfo
import pytest
import unittest
from posthog.test.base import APIBaseTest
from unittest import mock
from unittest.mock import ANY, patch
from django.contrib.sessions.backends.base import UpdateError
from... | 3,425 | 148,563 |
posthog | posthog/api/test/test_materialized_column_slot.py | .py | """Tests for MaterializedColumnSlot REST API endpoints."""
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
from rest_framework import status
from posthog.models import MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition
... | 575 | 22,667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.