Skip to content

: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.

fix(vercel): link verified SSO identities to existing accounts (#112775)

Matt Brooker5f208fa273a4
diff --git a/docs/published/handbook/engineering/vercel-integration.md b/docs/published/handbook/engineering/vercel-integration.md
index 5bfe3090a3d2..90f2b90ee6fa 100644
--- a/docs/published/handbook/engineering/vercel-integration.md
+++ b/docs/published/handbook/engineering/vercel-integration.md
@@ -437,6 +437,11 @@ sequenceDiagram
Vercel users can SSO into PostHog without a separate login.
+An existing active PostHog account can link automatically when the signed Vercel SSO token contains a verified, matching email.
+Accounts with two-factor authentication or enforced domain SSO must complete PostHog login.
+The installation's verified-domain restrictions also apply before automatic linking.
+A stored mapping keeps its original account, and a removed organization member cannot regain access by retrying SSO.
+
```mermaid
sequenceDiagram
actor User
diff --git a/ee/api/vercel/README.md b/ee/api/vercel/README.md
index 1f6a73749ee6..af055e2f7168 100644
--- a/ee/api/vercel/README.md
+++ b/ee/api/vercel/README.md
@@ -198,8 +198,8 @@ Before releasing changes to the Vercel integration, manually verify the followin
- [ ] Installation completes without errors
- [ ] New organization is created
- [ ] Existing user is added as Owner of the new organization
-- [ ] Click "Connect Account" → User is prompted to login (security: must prove ownership)
-- [ ] After login, SSO works
+- [ ] Click "Connect Account" → SSO logs in the existing account when Vercel's signed token has a verified, matching email
+- [ ] Accounts with 2FA or enforced SSO, or without a verified matching email, still require PostHog login
#### Scenario 3: Trusted Vercel User (Second Installation)
@@ -213,7 +213,7 @@ Before releasing changes to the Vercel integration, manually verify the followin
- [ ] Installation completes without errors
- [ ] Second organization is created
- [ ] Same user is added as Owner of the second organization
-- [ ] Click "Connect Account" → SSO works immediately (user is trusted)
+- [ ] Click "Connect Account" → SSO works immediately with a verified, matching email and no additional account login requirements
#### Scenario 4: Inactive User Reactivation
diff --git a/ee/api/vercel/test/test_vercel_sso.py b/ee/api/vercel/test/test_vercel_sso.py
index 898742385422..ffb9e713868e 100644
--- a/ee/api/vercel/test/test_vercel_sso.py
+++ b/ee/api/vercel/test/test_vercel_sso.py
@@ -5,6 +5,9 @@ from urllib.parse import parse_qs, urlparse
import pytest
from unittest.mock import Mock, patch
+from django.contrib.auth import SESSION_KEY
+
+from django_otp.plugins.otp_totp.models import TOTPDevice
from rest_framework import status
from posthog.models import Organization, OrganizationMembership, Team, User
@@ -192,21 +195,16 @@ def mock_sso_success(sso_setup):
class TestSSORedirectSuccess(BaseSSOMockTest):
def test_sso_redirect_basic_success(self, sso_setup):
response = SSOTestHelper.make_sso_request(sso_setup["client"], sso_setup["url"])
- # Existing users should be redirected to login for verification
- SSOTestHelper.assert_login_redirect(response, {"mode": "sso", "code": "test_auth_code", "state": "test_state"})
+ SSOTestHelper.assert_successful_redirect(response)
def test_sso_redirect_with_billing_path(self, sso_setup):
response = SSOTestHelper.make_sso_request(sso_setup["client"], sso_setup["url"], path="billing")
- # Existing users should be redirected to login for verification
- SSOTestHelper.assert_login_redirect(
- response, {"mode": "sso", "code": "test_auth_code", "state": "test_state", "path": "billing"}
- )
+ SSOTestHelper.assert_successful_redirect(response, "/organization/billing/overview")
def test_sso_redirect_with_custom_url(self, sso_setup):
custom_url = "https://eu.posthog.com/dashboard"
response = SSOTestHelper.make_sso_request(sso_setup["client"], sso_setup["url"], url=custom_url)
- # Existing users should be redirected to login for verification
- SSOTestHelper.assert_login_redirect(response, {"mode": "sso", "code": "test_auth_code", "state": "test_state"})
+ SSOTestHelper.assert_successful_redirect(response, custom_url)
def test_sso_redirect_with_resource_switching(self, sso_setup):
team = Team.objects.create(organization=sso_setup["organization"], name="SSO Test Team")
@@ -219,12 +217,10 @@ class TestSSORedirectSuccess(BaseSSOMockTest):
)
response = SSOTestHelper.make_sso_request(sso_setup["client"], sso_setup["url"], resource_id=str(resource.pk))
- # Existing users should be redirected to login for verification
- SSOTestHelper.assert_login_redirect(response, {"mode": "sso", "code": "test_auth_code", "state": "test_state"})
+ SSOTestHelper.assert_successful_redirect(response)
- # Since user is redirected to login, team switching hasn't happened yet
sso_setup["user"].refresh_from_db()
- assert sso_setup["user"].current_team != team # Team switching happens after login verification
+ assert sso_setup["user"].current_team == team
def test_sso_redirect_with_experimentation_item(self, sso_setup):
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -238,10 +234,9 @@ class TestSSORedirectSuccess(BaseSSOMockTest):
)
response = SSOTestHelper.make_sso_request(
- sso_setup["client"], sso_setup["url"], experimentation_item_id=f"flag:{flag.id}"
+ sso_setup["client"], sso_setup["url"], experimentation_item_id=f"flag_{flag.id}"
)
- # Existing users should be redirected to login for verification
- SSOTestHelper.assert_login_redirect(response, {"mode": "sso", "code": "test_auth_code", "state": "test_state"})
+ SSOTestHelper.assert_successful_redirect(response, f"/project/{team.pk}/feature_flags/{flag.pk}")
class TestSSORedirectValidation:
@@ -334,24 +329,34 @@ class TestSSORedirectFailures:
class TestSSOUserMapping:
- def test_sso_redirect_creates_new_user_mapping_for_unknown_user(self, sso_setup):
- """
- When an existing user (with same email) tries to authenticate via SSO, the system should:
- 1. Detect that the user exists
- 2. Redirect them to login for verification
- 3. Not create user mapping until after login verification
- """
+ @pytest.mark.parametrize(
+ ("email_verified", "email"), [(True, "[email protected]"), (False, "[email protected]"), (True, "[email protected]")]
+ )
+ def test_sso_redirect_links_existing_user_only_with_verified_email(
+ self, sso_setup, email_verified: bool, email: str
+ ) -> None:
+ sso_setup["user"].set_unusable_password()
+ sso_setup["user"].save()
+ claims = create_user_claims(sso_setup["installation_id"], "new_sso_user_456", email=email)
+ claims.user_email_verified = email_verified
+
with (
mock_vercel_integration(**MockFactory.successful_sso_flow(sso_setup["installation_id"])),
- mock_jwt_validation(create_user_claims(sso_setup["installation_id"], "new_sso_user_456")),
+ mock_jwt_validation(claims),
):
response = SSOTestHelper.make_sso_request(sso_setup["client"], sso_setup["url"])
- # Existing users should be redirected to login for verification
+
+ if email_verified:
+ SSOTestHelper.assert_successful_redirect(response)
+ assert sso_setup["client"].session[SESSION_KEY] == str(sso_setup["user"].pk)
+ SSOTestHelper.assert_user_mapping_created(
+ sso_setup["installation"], "new_sso_user_456", sso_setup["user"].pk
+ )
+ else:
SSOTestHelper.assert_login_redirect(
response, {"mode": "sso", "code": "test_auth_code", "state": "test_state"}
)
-
- # User mapping should NOT be created until after login verification
+ assert SESSION_KEY not in sso_setup["client"].session
sso_setup["installation"].refresh_from_db()
user_mappings = sso_setup["installation"].config.get("user_mappings", {})
assert "new_sso_user_456" not in user_mappings
@@ -390,14 +395,10 @@ class TestSSOUserMapping:
SSOTestHelper.assert_login_redirect(response, {"mode": "sso", "code": "test_auth_code", "state": "test_state"})
assert "email" not in parse_qs(urlparse(response.url).query)
- def test_sso_redirect_cleans_up_stale_user_mapping(self, sso_setup):
- """
- When a user mapping exists for a deleted user, the SSO flow should:
- 1. Detect the stale mapping
- 2. Clean it up
- 3. Create a new mapping for the current user
- 4. Successfully authenticate the user
- """
+ @pytest.mark.parametrize("requires_login", [False, True])
+ def test_sso_redirect_cleans_up_stale_user_mapping(self, sso_setup, requires_login: bool) -> None:
+ if requires_login:
+ TOTPDevice.objects.create(user=sso_setup["user"], name="default", confirmed=True)
deleted_user_pk = 99999
sso_setup["installation"].config["user_mappings"] = {"stale_user_123": deleted_user_pk}
sso_setup["installation"].save()
@@ -407,10 +408,13 @@ class TestSSOUserMapping:
mock_jwt_validation(create_user_claims(sso_setup["installation_id"], "stale_user_123")),
):
response = SSOTestHelper.make_sso_request(sso_setup["client"], sso_setup["url"])
- # Existing users should be redirected to login for verification
- SSOTestHelper.assert_login_redirect(
- response, {"mode": "sso", "code": "test_auth_code", "state": "test_state"}
- )
+ if requires_login:
+ SSOTestHelper.assert_login_redirect(response, {"code": TestConstants.AUTH_CODE})
+ sso_setup["client"].force_login(sso_setup["user"])
+ response = sso_setup["client"].get("/login/vercel/continue", TestConstants.BASE_SSO_PARAMS)
+
+ SSOTestHelper.assert_successful_redirect(response)
+ SSOTestHelper.assert_user_mapping_created(sso_setup["installation"], "stale_user_123", sso_setup["user"].pk)
class TestSSOOrganizationHandling:
@@ -459,22 +463,14 @@ class TestSSOOrganizationHandling:
mock_jwt_validation(create_user_claims(other_installation.integration_id)),
):
response = SSOTestHelper.make_sso_request(sso_setup["client"], sso_setup["url"])
- # Existing users should be redirected to login for verification
- SSOTestHelper.assert_login_redirect(
- response, {"mode": "sso", "code": "test_auth_code", "state": "test_state"}
- )
+ SSOTestHelper.assert_successful_redirect(response)
assert OrganizationMembership.objects.filter(
user=sso_setup["user"], organization=sso_setup["organization"]
).exists()
+ sso_setup["user"].refresh_from_db()
+ assert sso_setup["user"].current_organization == other_org
def test_sso_redirect_denies_access_for_user_without_organization_membership(self, sso_setup):
- """
- When a user with an existing mapping no longer has organization membership, the system should:
- 1. Detect the missing organization membership
- 2. Remove the stale user mapping
- 3. Deny access with PermissionDenied
- """
-
sso_setup["installation"].config["user_mappings"] = {"mapped_user_123": sso_setup["user"].pk}
sso_setup["installation"].save()
@@ -484,12 +480,16 @@ class TestSSOOrganizationHandling:
mock_vercel_integration(**MockFactory.successful_sso_flow(sso_setup["installation_id"])),
mock_jwt_validation(create_user_claims(sso_setup["installation_id"], "mapped_user_123")),
):
- response = SSOTestHelper.make_sso_request(sso_setup["client"], sso_setup["url"])
- assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ for _ in range(2):
+ response = SSOTestHelper.make_sso_request(sso_setup["client"], sso_setup["url"])
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
sso_setup["installation"].refresh_from_db()
user_mappings = sso_setup["installation"].config.get("user_mappings", {})
- assert "mapped_user_123" not in user_mappings
+ assert user_mappings["mapped_user_123"] == sso_setup["user"].pk
+ assert not OrganizationMembership.objects.filter(
+ user=sso_setup["user"], organization=sso_setup["organization"]
+ ).exists()
def test_sso_redirect_allows_access_for_user_with_valid_membership_levels(self, sso_setup):
from posthog.models.organization import OrganizationMembership
@@ -573,8 +573,8 @@ class TestSSORegionRedirect:
):
response = SSOTestHelper.make_sso_request(sso_setup["client"], sso_setup["url"], resource_id="99999")
- assert response.status_code == status.HTTP_302_FOUND
- assert "eu.posthog.com" not in response.url
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert "Location" not in response
def test_dev_env_processes_normally(self, sso_setup):
with (
@@ -584,8 +584,8 @@ class TestSSORegionRedirect:
):
response = SSOTestHelper.make_sso_request(sso_setup["client"], sso_setup["url"], resource_id="99999")
- assert response.status_code == status.HTTP_302_FOUND
- assert "eu.posthog.com" not in response.url
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert "Location" not in response
def test_no_resource_id_processes_normally(self, sso_setup):
with (
@@ -624,8 +624,8 @@ class TestSSORegionRedirect:
):
response = SSOTestHelper.make_sso_request(sso_setup["client"], sso_setup["url"], resource_id="not-a-number")
- assert response.status_code == status.HTTP_302_FOUND
- assert "eu.posthog.com" not in response.url
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ assert "Location" not in response
@staticmethod
def settings(**kwargs):
diff --git a/ee/vercel/integration.py b/ee/vercel/integration.py
index f3cb626d9751..987bca1147d9 100644
--- a/ee/vercel/integration.py
+++ b/ee/vercel/integration.py
@@ -15,13 +15,17 @@ from django.utils.text import slugify
import structlog
from rest_framework import exceptions
+from two_factor.utils import default_device
from posthog.cloud_utils import get_cached_instance_license
from posthog.dataclasses import frozen
from posthog.event_usage import report_user_signed_up
from posthog.exceptions_capture import capture_exception
+from posthog.helpers.email_utils import EmailLookupHandler
+from posthog.helpers.two_factor_session import has_passkeys
from posthog.models.integration import Integration
from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.organization_domain import OrganizationDomain
from posthog.models.organization_integration import OrganizationIntegration
from posthog.models.product_intent import ProductIntent
from posthog.models.team import Team
@@ -892,6 +896,24 @@ class VercelIntegration:
def _claims_prove_email(claims: VercelUserClaims, email: str) -> bool:
return claims.user_email_verified is True and (claims.user_email or "").lower() == email.lower()
+ @staticmethod
+ def _sso_login_block_reason(
+ user: User, claims: VercelUserClaims, installation: OrganizationIntegration
+ ) -> str | None:
+ if not user.is_active:
+ return "inactive_user"
+ if claims.user_email_verified is not True:
+ return "email_unverified"
+ if not VercelIntegration._claims_prove_email(claims, user.email):
+ return "email_mismatch"
+ if default_device(user) or (user.passkeys_enabled_for_2fa and has_passkeys(user)):
+ return "two_factor_required"
+ if OrganizationDomain.objects.get_sso_enforcement_for_email_address(user.email):
+ return "sso_enforced"
+ if OrganizationDomain.objects.is_email_blocked_by_domain_enforcement(user.email, installation.organization):
+ return "domain_blocked"
+ return None
+
@staticmethod
def _authenticate_and_login_user(request, claims: VercelUserClaims, resource_id: str | None) -> User:
user = VercelIntegration._find_sso_user(claims)
@@ -927,6 +949,8 @@ class VercelIntegration:
integration_id=claims.installation_id,
)
mapped_user_pk = VercelIntegration._get_user_mapping(installation, claims.user_id)
+ if mapped_user_pk is not None and not User.objects.filter(pk=mapped_user_pk).exists():
+ mapped_user_pk = None
if mapped_user_pk is None:
can_link = VercelIntegration._claims_prove_email(claims, request.user.email)
else:
@@ -1134,32 +1158,35 @@ class VercelIntegration:
return user
@staticmethod
+ @transaction.atomic
def _find_sso_user(claims: VercelUserClaims) -> User:
if not claims.user_email:
raise ValueError("Email is required for user creation")
- installation = VercelIntegration._get_installation(claims.installation_id)
+ installation = OrganizationIntegration.objects.select_for_update().get(
+ kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
+ integration_id=claims.installation_id,
+ )
# Try to find already mapped user
user_pk = VercelIntegration._get_user_mapping(installation, claims.user_id)
if user_pk:
- user = User.objects.filter(pk=user_pk, is_active=True).first()
+ user = User.objects.filter(pk=user_pk).first()
if user:
# Validate that the user still has access to the organization associated with the installation
- if not user.organization_memberships.filter(
- organization=installation.organization, level__gte=OrganizationMembership.Level.MEMBER
- ).exists():
- # User no longer has access to this organization, remove stale mapping
- user_mappings = installation.config.get("user_mappings", {})
- if claims.user_id in user_mappings:
- del user_mappings[claims.user_id]
- installation.save(update_fields=["config"])
+ if (
+ user.is_active
+ and not user.organization_memberships.filter(
+ organization=installation.organization, level__gte=OrganizationMembership.Level.MEMBER
+ ).exists()
+ ):
raise exceptions.PermissionDenied("User no longer has access to this organization")
- if VercelIntegration._claims_prove_email(claims, user.email):
+ reason = VercelIntegration._sso_login_block_reason(user, claims, installation)
+ if reason is None:
return user
logger.info(
"Vercel SSO mapping needs a PostHog login",
- reason="email_unverified" if claims.user_email_verified is not True else "email_mismatch",
+ reason=reason,
email_verified=claims.user_email_verified,
installation_id=claims.installation_id,
integration="vercel",
@@ -1178,21 +1205,26 @@ class VercelIntegration:
del user_mappings[claims.user_id]
installation.save(update_fields=["config"])
- existing_user = User.objects.filter(email=claims.user_email).first()
+ existing_user = EmailLookupHandler.get_user_by_email(claims.user_email, is_active=None)
if existing_user:
- raise RequiresExistingUserLogin(
- email=claims.user_email, vercel_user_id=claims.user_id, installation_id=claims.installation_id
+ if VercelIntegration._sso_login_block_reason(existing_user, claims, installation) is not None:
+ raise RequiresExistingUserLogin(
+ email=claims.user_email, vercel_user_id=claims.user_id, installation_id=claims.installation_id
+ )
+ user = existing_user
+ intended_level = VercelIntegration._determine_membership_level(user.email, installation)
+ VercelIntegration._add_user_to_organization(user, installation.organization, intended_level)
+ user.current_organization = installation.organization
+ user.save(update_fields=["current_organization"])
+ else:
+ intended_level = VercelIntegration._determine_membership_level(claims.user_email, installation)
+ user = VercelIntegration._create_user_for_email(
+ email=claims.user_email,
+ name=claims.user_name,
+ organization=installation.organization,
+ level=intended_level,
)
- intended_level = VercelIntegration._determine_membership_level(claims.user_email, installation)
-
- user = VercelIntegration._create_user_for_email(
- email=claims.user_email,
- name=claims.user_name,
- organization=installation.organization,
- level=intended_level,
- )
-
VercelIntegration._set_user_mapping(installation, claims.user_id, user.pk)
return user
diff --git a/ee/vercel/test/test_integration.py b/ee/vercel/test/test_integration.py
index 84871f67b6b3..45d72680cf1b 100644
--- a/ee/vercel/test/test_integration.py
+++ b/ee/vercel/test/test_integration.py
@@ -8,17 +8,21 @@ from django.contrib.auth import SESSION_KEY
from django.contrib.sessions.middleware import SessionMiddleware
from django.db import IntegrityError
from django.http import HttpResponse
-from django.test import RequestFactory, TestCase
+from django.test import RequestFactory, TestCase, override_settings
+from django.utils import timezone
+from django_otp.plugins.otp_totp.models import TOTPDevice
from parameterized import parameterized
from rest_framework import exceptions
from rest_framework.exceptions import NotFound, ValidationError
from posthog.models.integration import Integration
from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.organization_domain import OrganizationDomain
from posthog.models.organization_integration import OrganizationIntegration
from posthog.models.team import Team
from posthog.models.user import User
+from posthog.models.webauthn_credential import WebauthnCredential
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -359,6 +363,7 @@ class TestVercelIntegration(TestCase):
assert "new_vercel_id" not in new_installation.config.get("user_mappings", {})
mock_report.assert_not_called()
+ claims.user_email_verified = False
with self.assertRaises(RequiresExistingUserLogin):
VercelIntegration._find_sso_user(claims)
@@ -410,8 +415,7 @@ class TestVercelIntegration(TestCase):
)
@patch("ee.vercel.integration.report_user_signed_up")
- def test_sso_requires_login_for_external_user(self, mock_report):
- """Security test: External users (no Vercel mapping) must prove ownership via login."""
+ def test_sso_requires_login_for_unverified_existing_email(self, mock_report):
from ee.vercel.integration import RequiresExistingUserLogin
# Create an existing PostHog user (not through Vercel)
@@ -445,10 +449,10 @@ class TestVercelIntegration(TestCase):
membership = OrganizationMembership.objects.get(user=existing_user, organization=installation.organization)
assert membership.level == OrganizationMembership.Level.OWNER
- # SSO should require login for external user (no mapping yet)
sso_claims = self._create_user_claims("vercel_external_user")
sso_claims.installation_id = installation_id
sso_claims.user_email = "[email protected]"
+ sso_claims.user_email_verified = False
with self.assertRaises(RequiresExistingUserLogin):
VercelIntegration._find_sso_user(sso_claims)
@@ -534,6 +538,79 @@ class TestVercelIntegration(TestCase):
assert user.email == "[email protected]"
assert user.is_email_verified is claim_email_verified
+ @parameterized.expand(
+ [
+ (f"{policy}_{mapped}", policy, mapped)
+ for policy in ("totp", "passkey", "sso", "inactive", "domain")
+ for mapped in (False, True)
+ ]
+ )
+ @override_settings(
+ CLOUD_DEPLOYMENT="US",
+ SOCIAL_AUTH_GOOGLE_OAUTH2_KEY="synthetic-client",
+ SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET="synthetic-secret",
+ )
+ def test_sso_preserves_account_login_requirements(self, _name: str, policy: str, mapped: bool) -> None:
+ claims = self._create_user_claims("protected_user")
+ claims.user_email = self.user.email
+ if mapped:
+ self.installation.config["user_mappings"] = {claims.user_id: self.user.pk}
+ self.installation.save()
+ if policy == "totp":
+ TOTPDevice.objects.create(user=self.user, name="default", confirmed=True)
+ elif policy == "passkey":
+ self.user.passkeys_enabled_for_2fa = True
+ self.user.save()
+ WebauthnCredential.objects.create(
+ user=self.user,
+ credential_id=b"synthetic-credential",
+ public_key=b"synthetic-public-key",
+ algorithm=-7,
+ verified=True,
+ )
+ elif policy == "sso":
+ self.organization.available_product_features = [{"key": "sso_enforcement"}]
+ self.organization.save()
+ OrganizationDomain.objects.create(
+ organization=self.organization,
+ domain="example.com",
+ verified_at=timezone.now(),
+ sso_enforcement="google-oauth2",
+ )
+ elif policy == "inactive":
+ self.user.is_active = False
+ self.user.save()
+ elif policy == "domain":
+ self.organization.enforce_verified_domains = True
+ self.organization.save()
+
+ request = RequestFactory().get("/")
+ SessionMiddleware(lambda request: HttpResponse()).process_request(request)
+
+ with self.assertRaises(RequiresExistingUserLogin):
+ VercelIntegration._authenticate_and_login_user(request, claims, None)
+
+ assert SESSION_KEY not in request.session
+ self.installation.refresh_from_db()
+ assert self.installation.config.get("user_mappings", {}).get(claims.user_id) == (
+ self.user.pk if mapped else None
+ )
+
+ def test_sso_does_not_replace_an_inactive_users_mapping(self) -> None:
+ inactive_user = User.objects.create_user(
+ email="[email protected]", password=None, first_name="Inactive", is_active=False
+ )
+ claims = self._create_user_claims("inactive_mapping")
+ claims.user_email = self.user.email
+ self.installation.config["user_mappings"] = {claims.user_id: inactive_user.pk}
+ self.installation.save()
+
+ with self.assertRaises(RequiresExistingUserLogin):
+ VercelIntegration._find_sso_user(claims)
+
+ self.installation.refresh_from_db()
+ assert self.installation.config["user_mappings"][claims.user_id] == inactive_user.pk
+
@parameterized.expand(
[
("mapped_user_with_a_different_email", "self", "[email protected]", True, True, True),
@@ -585,8 +662,6 @@ class TestVercelIntegration(TestCase):
@patch("ee.vercel.integration.report_user_signed_up")
def test_sso_works_for_trusted_vercel_user_second_installation(self, mock_report):
- from ee.vercel.integration import RequiresExistingUserLogin, SSOParams
-
# First installation - creates user with mapping
first_installation_id = self.NEW_INSTALLATION_ID
first_user_claims = self._create_user_claims("vercel_user_abc")
@@ -612,23 +687,17 @@ class TestVercelIntegration(TestCase):
sso_claims = self._create_user_claims("vercel_user_xyz")
sso_claims.installation_id = second_installation_id
- with self.assertRaises(RequiresExistingUserLogin):
- VercelIntegration._find_sso_user(sso_claims)
-
- # After logging in and completing SSO, the mapping is created
- code = "test_sso_code_second_install"
- VercelIntegration.set_cached_claims(code, sso_claims, timeout=300)
-
request = RequestFactory().get("/")
SessionMiddleware(lambda request: HttpResponse()).process_request(request)
- request.user = user
- VercelIntegration.complete_sso_for_logged_in_user(
- request, SSOParams(mode="login", code=code, state="test_state")
- )
+ authenticated_user = VercelIntegration._authenticate_and_login_user(request, sso_claims, None)
second_installation.refresh_from_db()
+ assert authenticated_user.pk == user.pk
+ assert request.session[SESSION_KEY] == str(user.pk)
assert second_installation.config["user_mappings"]["vercel_user_xyz"] == user.pk
+ user.refresh_from_db()
+ assert user.current_organization == second_installation.organization
@patch("ee.vercel.integration.report_user_signed_up")
@patch("ee.billing.billing_manager.BillingManager")