( args: CreateOrUpdateUserArgs, requestHeaders?: Headers, affiliateTrackingId?: string | null, trackingContext?: CreateOrUpdateUserTrackingContext )
| 17 | import { ensureVerifiedDomainOrganizationMembership } from '@/lib/organizations/verified-domain-membership'; |
| 18 | |
| 19 | const workos = new WorkOS(WORKOS_API_KEY); |
| 20 | |
| 21 | async function processSSOInternal( |
| 22 | args: CreateOrUpdateUserArgs, |
| 23 | requestHeaders?: Headers, |
| 24 | affiliateTrackingId?: string | null, |
| 25 | trackingContext?: CreateOrUpdateUserTrackingContext |
| 26 | ): Promise<string | true> { |
| 27 | if (args.provider !== 'workos') { |
| 28 | throw new Error('Only SSO logins supported'); |
| 29 | } |
| 30 | const userDomain = args.google_user_email.split('@').pop(); |
| 31 | if (!userDomain) { |
| 32 | throw new Error('Invalid email address ' + args.google_user_email); |
| 33 | } |
| 34 | const orgs = await workos.organizations.listOrganizations({ |
| 35 | domains: [userDomain], |
| 36 | }); |
| 37 | if (!orgs.data.length) { |
| 38 | throw new Error(`No organization found for domain: ${userDomain}`); |
| 39 | } |
| 40 | if (orgs.data.length > 1) { |
| 41 | throw new Error(`Multiple organizations found for domain: ${userDomain}`); |
| 42 | } |
| 43 | const workOSOrg = orgs.data[0]; |
| 44 | const orgExternalId = workOSOrg.externalId; |
| 45 | |
| 46 | if (!orgExternalId) { |
| 47 | throw new Error( |
| 48 | `Organization ${workOSOrg.name} (${workOSOrg.id}) is not linked to a local organization (missing external_id)` |
| 49 | ); |
| 50 | } |
| 51 | |
| 52 | const authority = await resolveSsoAuthorityForDomain(userDomain); |
| 53 | if (authority.status !== 'required' || authority.sourceOrganizationId !== orgExternalId) { |
| 54 | throw new Error( |
| 55 | `WorkOS organization does not match the active SSO authority for ${userDomain}` |
| 56 | ); |
| 57 | } |
| 58 | |
| 59 | const kiloOrg = await getOrganizationById(orgExternalId); |
| 60 | if (!kiloOrg) { |
| 61 | throw new Error( |
| 62 | `No local organization found for WorkOS organization ${workOSOrg.name} (${workOSOrg.id} - ${orgExternalId})` |
| 63 | ); |
| 64 | } |
| 65 | |
| 66 | const res = await createOrUpdateUser( |
| 67 | args, |
| 68 | undefined, |
| 69 | true, |
| 70 | requestHeaders, |
| 71 | affiliateTrackingId, |
| 72 | trackingContext |
| 73 | ); |
| 74 | if (!res.success) { |
| 75 | if (res.error === 'SIGNUP-RATE-LIMITED' || res.error === 'EMAIL-ALREADY-USED') { |
| 76 | return `${SSO_SIGNIN_PATH}?error=${res.error}`; |
no test coverage detected