|
| 1 | +import { buildAccountsBaseUrl } from '@clerk/shared/buildAccountsBaseUrl'; |
| 2 | +import { ClerkRuntimeError, isClerkRuntimeError } from '@clerk/shared/error'; |
| 3 | +import { useClerk, useSession } from '@clerk/shared/react'; |
| 4 | +import type { EnterpriseSSOFactor } from '@clerk/shared/types'; |
| 5 | +import React from 'react'; |
| 6 | + |
| 7 | +import { ChooseEnterpriseConnectionCard } from '@/ui/common/ChooseEnterpriseConnectionCard'; |
| 8 | +import { Card } from '@/ui/elements/Card'; |
| 9 | +import { useCardState } from '@/ui/elements/contexts'; |
| 10 | +import { handleError } from '@/ui/utils/errorHandler'; |
| 11 | +import { originPrefersPopup } from '@/ui/utils/originPrefersPopup'; |
| 12 | + |
| 13 | +import { useUserVerification } from '../../contexts'; |
| 14 | +import { Flow, localizationKeys } from '../../customizables'; |
| 15 | +import { useRouter } from '../../router'; |
| 16 | +import { useUserVerificationSession } from './useUserVerificationSession'; |
| 17 | + |
| 18 | +type UVFactorOneEnterpriseSSOCardProps = { |
| 19 | + factors: Array<EnterpriseSSOFactor & { enterpriseConnectionId: string; enterpriseConnectionName: string }>; |
| 20 | + onShowAlternativeMethodsClicked: React.MouseEventHandler | undefined; |
| 21 | +}; |
| 22 | + |
| 23 | +const POPUP_CLOSED_CODE = 'reverification_popup_closed'; |
| 24 | + |
| 25 | +const waitForPopupCallback = (popup: Window, url: URL, accountsOrigin: string) => |
| 26 | + new Promise<void>((resolve, reject) => { |
| 27 | + let settled = false; |
| 28 | + const settle = (fn: () => void) => { |
| 29 | + if (settled) { |
| 30 | + return; |
| 31 | + } |
| 32 | + settled = true; |
| 33 | + window.removeEventListener('message', onMessage); |
| 34 | + clearInterval(interval); |
| 35 | + fn(); |
| 36 | + }; |
| 37 | + const onMessage = (event: MessageEvent) => { |
| 38 | + if (event.origin !== accountsOrigin) { |
| 39 | + return; |
| 40 | + } |
| 41 | + if (event.data?.session || event.data?.return_url) { |
| 42 | + settle(resolve); |
| 43 | + } |
| 44 | + }; |
| 45 | + const interval = setInterval(() => { |
| 46 | + if (popup.closed) { |
| 47 | + clearInterval(interval); |
| 48 | + setTimeout( |
| 49 | + () => |
| 50 | + settle(() => reject(new ClerkRuntimeError('Reverification popup was closed', { code: POPUP_CLOSED_CODE }))), |
| 51 | + 1000, |
| 52 | + ); |
| 53 | + } |
| 54 | + }, 500); |
| 55 | + |
| 56 | + window.addEventListener('message', onMessage); |
| 57 | + popup.location.href = url.href; |
| 58 | + }); |
| 59 | + |
| 60 | +export const UVFactorOneEnterpriseSSOCard = (props: UVFactorOneEnterpriseSSOCardProps) => { |
| 61 | + const { factors, onShowAlternativeMethodsClicked } = props; |
| 62 | + const clerk = useClerk(); |
| 63 | + const { session } = useSession(); |
| 64 | + const { data } = useUserVerificationSession(); |
| 65 | + const { afterVerification, oauthFlow } = useUserVerification(); |
| 66 | + const { navigate } = useRouter(); |
| 67 | + const card = useCardState(); |
| 68 | + |
| 69 | + const completeVerification = async (): Promise<void> => { |
| 70 | + if (data?.level === 'multi_factor') { |
| 71 | + await navigate('./factor-two'); |
| 72 | + return; |
| 73 | + } |
| 74 | + await clerk.setActive({ session: session?.id }); |
| 75 | + afterVerification?.(); |
| 76 | + }; |
| 77 | + |
| 78 | + const emailAddressIdFor = (enterpriseConnectionId: string) => { |
| 79 | + const user = session?.user; |
| 80 | + const enterpriseEmail = user?.enterpriseAccounts.find( |
| 81 | + account => account.enterpriseConnection?.id === enterpriseConnectionId, |
| 82 | + )?.emailAddress; |
| 83 | + return ( |
| 84 | + user?.emailAddresses.find(email => email.emailAddress === enterpriseEmail)?.id ?? |
| 85 | + user?.primaryEmailAddressId ?? |
| 86 | + undefined |
| 87 | + ); |
| 88 | + }; |
| 89 | + |
| 90 | + const verifyWithEnterpriseSSO = async (enterpriseConnectionId: string, popup: Window | null): Promise<void> => { |
| 91 | + if (!session) { |
| 92 | + return; |
| 93 | + } |
| 94 | + |
| 95 | + const accountsOrigin = buildAccountsBaseUrl(clerk.frontendApi); |
| 96 | + const popupCallbackUrl = `${accountsOrigin}/popup-callback`; |
| 97 | + const currentUrl = window.location.href; |
| 98 | + |
| 99 | + const response = await session.prepareFirstFactorVerification({ |
| 100 | + strategy: 'enterprise_sso', |
| 101 | + enterpriseConnectionId, |
| 102 | + emailAddressId: emailAddressIdFor(enterpriseConnectionId), |
| 103 | + redirectUrl: popup |
| 104 | + ? clerk.buildUrlWithAuth(`${popupCallbackUrl}?return_url=${encodeURIComponent(currentUrl)}`) |
| 105 | + : currentUrl, |
| 106 | + actionCompleteRedirectUrl: popup ? clerk.buildUrlWithAuth(popupCallbackUrl) : currentUrl, |
| 107 | + }); |
| 108 | + |
| 109 | + const url = response.firstFactorVerification.externalVerificationRedirectURL; |
| 110 | + if (!url) { |
| 111 | + throw new ClerkRuntimeError('Missing external verification redirect URL', { |
| 112 | + code: 'external_verification_redirect_url_missing', |
| 113 | + }); |
| 114 | + } |
| 115 | + |
| 116 | + if (!popup) { |
| 117 | + await clerk.navigate(url.href); |
| 118 | + return; |
| 119 | + } |
| 120 | + |
| 121 | + await waitForPopupCallback(popup, url, accountsOrigin); |
| 122 | + await completeVerification(); |
| 123 | + }; |
| 124 | + |
| 125 | + const handleSelectEnterpriseConnection = (enterpriseConnectionId: string) => { |
| 126 | + const usePopup = oauthFlow === 'redirect' ? false : oauthFlow === 'auto' ? originPrefersPopup() : true; |
| 127 | + const popup = usePopup ? window.open('about:blank', '', 'width=600,height=800') : null; |
| 128 | + return verifyWithEnterpriseSSO(enterpriseConnectionId, popup).catch(err => { |
| 129 | + popup?.close(); |
| 130 | + if (!isClerkRuntimeError(err) || err.code !== POPUP_CLOSED_CODE) { |
| 131 | + handleError(err, [], card.setError); |
| 132 | + } |
| 133 | + throw err; |
| 134 | + }); |
| 135 | + }; |
| 136 | + |
| 137 | + return ( |
| 138 | + <Flow.Part part='enterpriseConnections'> |
| 139 | + <ChooseEnterpriseConnectionCard |
| 140 | + title={localizationKeys('reverification.enterpriseSSO.title')} |
| 141 | + subtitle={localizationKeys('reverification.enterpriseSSO.subtitle')} |
| 142 | + onClick={handleSelectEnterpriseConnection} |
| 143 | + enterpriseConnections={factors.map(factor => ({ |
| 144 | + id: factor.enterpriseConnectionId, |
| 145 | + name: factor.enterpriseConnectionName, |
| 146 | + logoPublicUrl: factor.enterpriseConnectionLogoPublicUrl, |
| 147 | + provider: factor.enterpriseConnectionProvider, |
| 148 | + }))} |
| 149 | + showLogo={false} |
| 150 | + > |
| 151 | + {onShowAlternativeMethodsClicked && ( |
| 152 | + <Card.Action elementId='alternativeMethods'> |
| 153 | + <Card.ActionLink |
| 154 | + localizationKey={localizationKeys('footerActionLink__useAnotherMethod')} |
| 155 | + onClick={onShowAlternativeMethodsClicked} |
| 156 | + /> |
| 157 | + </Card.Action> |
| 158 | + )} |
| 159 | + </ChooseEnterpriseConnectionCard> |
| 160 | + </Flow.Part> |
| 161 | + ); |
| 162 | +}; |
0 commit comments