: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
feat(auth): grant django staff on dev from google workspace (#129611)
Raúl Negrón-Otero141fe2c7aa9c
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex a53708d872dc..f7f957713780 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -56,7 +56,7 @@ from webauthn.helpers.structs import AuthenticatorTransport, PublicKeyCredentialfrom posthog.api.email_verification import email_verification_code_verifier, is_email_verification_disabledfrom posthog.auth import ACCOUNT_BLOCKED_DETAILfrom posthog.caching.login_device_cache import check_and_cache_login_device-from posthog.constants import AUTH_BACKEND_DISPLAY_NAMES+from posthog.constants import AUTH_BACKEND_DISPLAY_NAMES, POSTHOG_INTERNAL_EMAIL_SUFFIXfrom posthog.email import is_email_availablefrom posthog.event_usage import report_user_logged_in, report_user_password_resetfrom posthog.exceptions_capture import capture_exception@@ -1597,6 +1597,25 @@ def social_reauth_complete(strategy: DjangoStrategy, backend, user: User | Nonecapture_exception(e)+def social_grant_staff_to_google_workspace_members(+ backend: BaseAuth, response: dict[str, Any], user: User | None = None, **kwargs: Any+) -> None:+ """+ Employees on dev ask for Django staff. This step grants it when they log in to dev with Google,+ so they do not have to ask. The `hd` claim confirms that our Google Workspace manages the account.+ """+ if (+ settings.CLOUD_DEPLOYMENT == "DEV"+ and backend.name == "google-oauth2"+ and user is not None+ and not user.is_staff+ and user.email.endswith(POSTHOG_INTERNAL_EMAIL_SUFFIX)+ and response.get("hd") in settings.ADMIN_AUTH_GOOGLE_ALLOWED_DOMAINS+ ):+ user.is_staff = True+ user.save(update_fields=["is_staff"])++def social_login_notification(strategy: DjangoStrategy, backend, user: User | None = None, is_new: bool = False, **kwargs):diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.pyindex 2096b0950322..cd6ccb4fcfe9 100644--- a/posthog/api/test/test_authentication.py+++ b/posthog/api/test/test_authentication.py@@ -17,7 +17,7 @@ from django.core.asgi import get_asgi_applicationfrom django.core.cache import cachefrom django.db import connectionfrom django.http import HttpRequest, HttpResponse-from django.test import RequestFactory, SimpleTestCase, override_settings+from django.test import RequestFactory, SimpleTestCase, TestCase, override_settingsfrom django.test.utils import CaptureQueriesContextfrom django.utils import timezonefrom django.utils.module_loading import import_string@@ -38,7 +38,11 @@ from social_django.models import UserSocialAuthfrom two_factor.utils import totp_digitsfrom two_factor.views.core import REMEMBER_COOKIE_PREFIX-from posthog.api.authentication import password_reset_token_generator, social_login_notification+from posthog.api.authentication import (+ password_reset_token_generator,+ social_grant_staff_to_google_workspace_members,+ social_login_notification,+)from posthog.api.email_verification import is_email_verification_disabledfrom posthog.api.oauth.cimd import CIMDFetchErrorfrom posthog.auth import (@@ -3396,6 +3400,29 @@ class TestOAuthLoginNotification(APIBaseTest):assert len(mail.outbox) == 0+class TestSocialGrantStaffToGoogleWorkspaceMembers(TestCase):+ @parameterized.expand(+ [+ ("prod_us", "US", "google-oauth2", "[email protected]", "posthog.com", False, False),+ ("workspace_member", "DEV", "google-oauth2", "[email protected]", "posthog.com", False, True),+ ("no_workspace", "DEV", "google-oauth2", "[email protected]", None, False, False),+ ("other_workspace", "DEV", "google-oauth2", "[email protected]", "example.com", False, False),+ ("non_posthog_email", "DEV", "google-oauth2", "[email protected]", "posthog.com", False, False),+ ("other_backend", "DEV", "github", "[email protected]", "posthog.com", False, False),+ ("existing_staff_kept", "DEV", "google-oauth2", "[email protected]", None, True, True),+ ]+ )+ def test_grant(self, _name, cloud_deployment, backend_name, email, hosted_domain, was_staff, expected_is_staff):+ user = User.objects.create(email=email, distinct_id=str(uuid.uuid4()), is_staff=was_staff)+ backend = type("Backend", (), {"name": backend_name})()++ with self.settings(CLOUD_DEPLOYMENT=cloud_deployment, ADMIN_AUTH_GOOGLE_ALLOWED_DOMAINS=["posthog.com"]):+ social_grant_staff_to_google_workspace_members(backend, {"hd": hosted_domain}, user)++ user.refresh_from_db()+ assert user.is_staff is expected_is_staff++class TestKnownLoginDeviceCookieMiddleware(APIBaseTest):CONFIG_AUTO_LOGIN = Falsediff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 64e4a9f26e1a..2ceb763f232e 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -345,6 +345,7 @@ SOCIAL_AUTH_PIPELINE = ("social_core.pipeline.social_auth.associate_user","social_core.pipeline.social_auth.load_extra_data","social_core.pipeline.user.user_details",+ "posthog.api.authentication.social_grant_staff_to_google_workspace_members","posthog.api.authentication.social_login_notification",# Must stay last: it grants the step-up window, so every step that can still refuse the re-auth# has to have run first