: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
chore(admin): split oauth models into their own sidebar section (#57713)
Rafael Audibert8a507721f312
diff --git a/posthog/admin/__init__.py b/posthog/admin/__init__.pyindex ea889792e8b8..71ffafa91ea3 100644--- a/posthog/admin/__init__.py+++ b/posthog/admin/__init__.py@@ -175,3 +175,82 @@ def register_all_admin():admin.site.register(UserProductList, UserProductListAdmin)admin.site.register(MCPServerTemplate, MCPServerTemplateAdmin)+++# :KRUDGE: OAuth models live in the `posthog` app, so by default they appear+# under "PostHog" in the admin sidebar alongside dozens of unrelated models.+# The "real" fix would be to move these to `products/oauth/` so Django groups+# them automatically — but every model here is `swappable` (referenced as+# `OAUTH2_PROVIDER_APPLICATION_MODEL` etc.). Changing the app_label means+# rewriting every existing migration that points at the swappable target,+# both in oauth2_provider and in any FK that's been added on top — a known+# Django landmine. Until there's a separate reason to isolate OAuth as its+# own product, override `get_app_list` instead.+_OAUTH_ADMIN_MODEL_NAMES = frozenset(+ {+ "OAuthApplication",+ "OAuthAccessToken",+ "OAuthGrant",+ "OAuthIDToken",+ "OAuthRefreshToken",+ }+)+++def install_admin_app_list_overrides():+ """Override admin sidebar grouping. Must run before any admin request so the+ first call goes through the patched function — otherwise the lazy admin+ registry would only install this mid-call after `get_app_list` has already+ started executing on the original method."""+ from django.contrib import admin+ from django.urls import NoReverseMatch, reverse++ original_get_app_list = admin.site.get_app_list++ def _build_oauth_app_dict(oauth_models):+ try:+ app_url = reverse("admin:app_list", kwargs={"app_label": "oauth"})+ except NoReverseMatch:+ app_url = ""+ return {+ "name": "OAuth",+ "app_label": "oauth",+ "app_url": app_url,+ "has_module_perms": True,+ "models": oauth_models,+ }++ def _extract_oauth_models(app_list):+ oauth_models = []+ for app in app_list:+ kept = []+ for model in app["models"]:+ if model.get("object_name") in _OAUTH_ADMIN_MODEL_NAMES:+ oauth_models.append(model)+ else:+ kept.append(model)+ app["models"] = kept+ return oauth_models++ def get_app_list(request, app_label=None):+ # The synthetic "oauth" app_label has no real models registered against it,+ # so we have to source its models from the `posthog` app and rebuild the+ # group ourselves — otherwise visiting /admin/oauth/ would 404.+ if app_label == "oauth":+ posthog_app_list = original_get_app_list(request, app_label="posthog")+ oauth_models = _extract_oauth_models(posthog_app_list)+ oauth_models.sort(key=lambda model: model["name"].lower())+ return [_build_oauth_app_dict(oauth_models)] if oauth_models else []++ app_list = original_get_app_list(request, app_label=app_label)+ oauth_models = _extract_oauth_models(app_list)+ if not oauth_models:+ return app_list++ oauth_models.sort(key=lambda model: model["name"].lower())+ app_list = [app for app in app_list if app["models"]]+ app_list.append(_build_oauth_app_dict(oauth_models))+ app_list.sort(key=lambda app: app["name"].lower())+ return app_list++ admin.site.get_app_list = get_app_list # type: ignore[method-assign] # ty: ignore[invalid-assignment]diff --git a/posthog/admin/test_admin.py b/posthog/admin/test_admin.pyindex a790c27016cb..715feb7bfc4c 100644--- a/posthog/admin/test_admin.py+++ b/posthog/admin/test_admin.py@@ -5,7 +5,7 @@ from django.contrib import adminfrom django.contrib.admin import AdminSitefrom django.test import RequestFactory-from posthog.admin import register_all_admin+from posthog.admin import _OAUTH_ADMIN_MODEL_NAMES, install_admin_app_list_overrides, register_all_adminfrom posthog.admin.admins.user_admin import UserAdminfrom posthog.admin.inlines.organization_member_inline import OrganizationMemberForUserInline, OrganizationMemberInlinefrom posthog.admin.inlines.plugin_attachment_inline import PluginAttachmentInline@@ -18,6 +18,55 @@ class TestAdmin(BaseTest):register_all_admin()+class TestOAuthSidebarRegrouping(BaseTest):+ def _patched_get_app_list(self):+ site = AdminSite()+ site.get_app_list = lambda request, app_label=None: [ # type: ignore[method-assign] # ty: ignore[invalid-assignment]+ {+ "name": "PostHog",+ "app_label": "posthog",+ "app_url": "/admin/posthog/",+ "has_module_perms": True,+ "models": [+ {"name": "OAuth applications", "object_name": "OAuthApplication"},+ {"name": "OAuth access tokens", "object_name": "OAuthAccessToken"},+ {"name": "OAuth grants", "object_name": "OAuthGrant"},+ {"name": "OAuth ID tokens", "object_name": "OAuthIDToken"},+ {"name": "OAuth refresh tokens", "object_name": "OAuthRefreshToken"},+ {"name": "Users", "object_name": "User"},+ ]+ if app_label in (None, "posthog")+ else [],+ }+ ]+ with patch.object(admin, "site", site):+ install_admin_app_list_overrides()+ return site.get_app_list++ def test_oauth_models_moved_to_oauth_section(self):+ get_app_list = self._patched_get_app_list()+ result = get_app_list(request=None)++ oauth_apps = [app for app in result if app["app_label"] == "oauth"]+ assert len(oauth_apps) == 1+ oauth_object_names = {model["object_name"] for model in oauth_apps[0]["models"]}+ assert oauth_object_names == _OAUTH_ADMIN_MODEL_NAMES++ posthog_apps = [app for app in result if app["app_label"] == "posthog"]+ assert len(posthog_apps) == 1+ posthog_object_names = {model["object_name"] for model in posthog_apps[0]["models"]}+ assert posthog_object_names == {"User"}++ def test_oauth_app_label_returns_only_oauth_models(self):+ get_app_list = self._patched_get_app_list()+ result = get_app_list(request=None, app_label="oauth")++ assert len(result) == 1+ assert result[0]["app_label"] == "oauth"+ assert result[0]["name"] == "OAuth"+ assert {model["object_name"] for model in result[0]["models"]} == _OAUTH_ADMIN_MODEL_NAMES++class TestUserAdmin(BaseTest):def setUp(self) -> None:super().setUp()diff --git a/posthog/apps.py b/posthog/apps.pyindex 224e90c6de83..fe93607c7f32 100644--- a/posthog/apps.py+++ b/posthog/apps.py@@ -166,3 +166,11 @@ class PostHogConfig(AppConfig):# Don't use lazy loading in tests and migrationsif not settings.TEST and "migrate" not in sys.argv and "test" not in sys.argv:admin.site._registry = LazyAdminRegistry()++ # Install the OAuth sidebar regrouping override eagerly. It must wrap+ # `get_app_list` before the first admin request — if it were installed+ # from inside `register_all_admin()` it would only land mid-call, after+ # the original method had already started executing.+ from posthog.admin import install_admin_app_list_overrides++ install_admin_app_list_overrides()diff --git a/products/mcp_store/backend/apps.py b/products/mcp_store/backend/apps.pyindex e41aad7d4aae..2098c5e793c9 100644--- a/products/mcp_store/backend/apps.py+++ b/products/mcp_store/backend/apps.py@@ -5,3 +5,4 @@ class McpStoreConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "products.mcp_store.backend"label = "mcp_store"+ verbose_name = "MCP STORE"