@jsb188/auth-web 1.1.10 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@ import type { OnErrorGQLFn } from '@jsb188/graphql/types.d';
3
3
  import { AppContext, onAccountLogin, useOpenModalPopUp } from '@jsb188/react/states';
4
4
  import { useCallback, useContext, useEffect, useRef, useState } from 'react';
5
5
  import { authenticateOAuthSignInSession } from '../modules/_helpers';
6
+ import { loadGoogleIdentityServices } from '../utils/googleIdentity';
6
7
 
7
8
  /**
8
9
  * Types
@@ -10,12 +11,12 @@ import { authenticateOAuthSignInSession } from '../modules/_helpers';
10
11
 
11
12
  // SSO sign-in option resolved by the getSsoLoginOptions mutation
12
13
  export interface SsoLoginOptionData {
13
- id: string;
14
- provider: 'GOOGLE' | 'MICROSOFT';
15
- organizationId: string;
16
- organizationName: string;
17
- microsoftTenantId?: string | null;
18
- googleHostedDomain?: string | null;
14
+ id: string;
15
+ provider: 'GOOGLE' | 'MICROSOFT';
16
+ organizationId: string;
17
+ organizationName: string;
18
+ microsoftTenantId?: string | null;
19
+ googleHostedDomain?: string | null;
19
20
  }
20
21
 
21
22
  // Called when an "authenticateOnly" sign-in verified an email with no account
@@ -23,53 +24,53 @@ export interface SsoLoginOptionData {
23
24
  type OnRespondentTokenFn = (token: string, email: string | null) => void;
24
25
 
25
26
  export type OnFinishSignInFn = (
26
- token: string,
27
- sessionBootstrapToken?: string | null,
28
- sessionPersisted?: boolean,
27
+ token: string,
28
+ sessionBootstrapToken?: string | null,
29
+ sessionPersisted?: boolean,
29
30
  ) => boolean | Promise<boolean>;
30
31
 
31
32
  interface ContinueWithGoogleParams {
32
- doNotAlertErrors?: boolean;
33
- onFinishSignIn: OnFinishSignInFn;
34
- onRespondentToken?: OnRespondentTokenFn;
33
+ doNotAlertErrors?: boolean;
34
+ onFinishSignIn: OnFinishSignInFn;
35
+ onRespondentToken?: OnRespondentTokenFn;
35
36
  }
36
37
 
37
38
  interface ContinueWithMicrosoftParams {
38
- doNotAlertErrors?: boolean;
39
- onFinishSignIn: OnFinishSignInFn;
40
- onRespondentToken?: OnRespondentTokenFn;
41
- onError?: OnErrorGQLFn;
39
+ doNotAlertErrors?: boolean;
40
+ onFinishSignIn: OnFinishSignInFn;
41
+ onRespondentToken?: OnRespondentTokenFn;
42
+ onError?: OnErrorGQLFn;
42
43
  }
43
44
 
44
45
  interface GoogleLoginHookParams extends ContinueWithGoogleParams {
45
- scriptLoaded: boolean;
46
- scope?: string;
47
- onError?: OnErrorGQLFn;
48
- onNonOAuthError?: (err: any) => void;
49
- overrideScope?: boolean;
50
- state?: string;
46
+ scriptLoaded: boolean;
47
+ scope?: string;
48
+ onError?: OnErrorGQLFn;
49
+ onNonOAuthError?: (err: any) => void;
50
+ overrideScope?: boolean;
51
+ state?: string;
51
52
  }
52
53
 
53
54
  /*
54
55
  * Apply a BFF-authenticated provider result to the caller and shared app state.
55
56
  */
56
57
  async function applyOAuthAuthenticationResult(
57
- auth: any,
58
- onFinishSignIn: OnFinishSignInFn,
59
- onRespondentToken: OnRespondentTokenFn | undefined,
60
- dispatchApp: any,
58
+ auth: any,
59
+ onFinishSignIn: OnFinishSignInFn,
60
+ onRespondentToken: OnRespondentTokenFn | undefined,
61
+ dispatchApp: any,
61
62
  ): Promise<boolean> {
62
- if (auth?.token && auth.account?.id) {
63
- const persisted = await onFinishSignIn(auth.token, null, true);
64
- if (persisted) {
65
- onAccountLogin({ ...auth, sessionBootstrapToken: null }, dispatchApp);
66
- return true;
67
- }
68
- } else if (auth?.respondentToken) {
69
- onRespondentToken?.(auth.respondentToken, auth.respondentEmail || null);
70
- }
71
-
72
- return false;
63
+ if (auth?.token && auth.account?.id) {
64
+ const persisted = await onFinishSignIn(auth.token, null, true);
65
+ if (persisted) {
66
+ onAccountLogin({ ...auth, sessionBootstrapToken: null }, dispatchApp);
67
+ return true;
68
+ }
69
+ } else if (auth?.respondentToken) {
70
+ onRespondentToken?.(auth.respondentToken, auth.respondentEmail || null);
71
+ }
72
+
73
+ return false;
73
74
  }
74
75
 
75
76
  /**
@@ -77,136 +78,139 @@ async function applyOAuthAuthenticationResult(
77
78
  */
78
79
 
79
80
  function useGoogleLogin(p: GoogleLoginHookParams) {
80
- const {
81
- scriptLoaded,
82
- scope = '',
83
- onError,
84
- onNonOAuthError,
85
- onFinishSignIn,
86
- onRespondentToken,
87
- overrideScope,
88
- state,
89
- doNotAlertErrors,
90
- ...props
91
- } = p;
92
-
93
- const { dispatchApp } = useContext(AppContext);
94
- const openModalPopUp = useOpenModalPopUp();
95
- const [waitingForProvider, setWaitingForProvider] = useState(false);
96
- const [waitingForOAuth, setWaitingForOAuth] = useState(false);
97
-
98
- const clientRef = useRef<any>(null);
99
- const onErrorRef = useRef(onError);
100
-
101
- onErrorRef.current = onError;
102
-
103
- const onNonOAuthErrorRef = useRef(onNonOAuthError);
104
- onNonOAuthErrorRef.current = onNonOAuthError;
105
-
106
- const onRespondentTokenRef = useRef(onRespondentToken);
107
- onRespondentTokenRef.current = onRespondentToken;
108
-
109
- const onFinishSignInRef = useRef(onFinishSignIn);
110
- onFinishSignInRef.current = onFinishSignIn;
111
-
112
- const openModalPopUpRef = useRef(openModalPopUp);
113
- openModalPopUpRef.current = openModalPopUp;
114
-
115
- const doNotAlertErrorsRef = useRef(doNotAlertErrors);
116
- doNotAlertErrorsRef.current = doNotAlertErrors;
117
-
118
- const dispatchAppRef = useRef(dispatchApp);
119
- dispatchAppRef.current = dispatchApp;
120
-
121
- // Org SSO connection to sign in through; read by the token callback below
122
- const ssoConnectionIdRef = useRef<string | null>(null);
123
- // Public web form context; allows contact-gated account creation (CHILD_ORGS forms)
124
- const formPublicIdRef = useRef<string | null>(null);
125
- // When true, a verified email with no account returns a temporary respondent
126
- // token instead of erroring (ANYONE web forms)
127
- const authenticateOnlyRef = useRef<boolean>(false);
128
-
129
- useEffect(() => {
130
- if (scriptLoaded) {
131
- // If using this package, it is expected that you install your own Google OAuth script
132
- const client = (globalThis as any).google?.accounts?.oauth2.initTokenClient({
133
- client_id: getENVVariable('GOOGLE_OAUTH'),
134
- scope: overrideScope ? scope : `openid profile email ${scope}`,
135
- callback: async (response: any) => {
136
- if (response.error) {
137
- setWaitingForProvider(false);
138
- setWaitingForOAuth(false);
139
- return onErrorRef.current?.(response, null);
140
- }
141
-
142
- const { access_token: oauthToken } = response;
143
- setWaitingForProvider(false);
144
- setWaitingForOAuth(true);
145
- const variables = {
146
- provider: 'GOOGLE' as const,
147
- oauthToken,
148
- ssoConnectionId: ssoConnectionIdRef.current,
149
- formPublicId: formPublicIdRef.current,
150
- authenticateOnly: authenticateOnlyRef.current,
151
- };
152
- const { auth, error } = await authenticateOAuthSignInSession(variables);
153
- if (error) {
154
- setWaitingForOAuth(false);
155
- if (!doNotAlertErrorsRef.current) {
156
- openModalPopUpRef.current(null, error);
157
- }
158
- onErrorRef.current?.(error, variables);
159
- return;
160
- }
161
-
162
- try {
163
- const authenticated = await applyOAuthAuthenticationResult(
164
- auth,
165
- onFinishSignInRef.current,
166
- onRespondentTokenRef.current,
167
- dispatchAppRef.current,
168
- );
169
- if (!authenticated) {
170
- setWaitingForOAuth(false);
171
- }
172
- } catch (error) {
173
- setWaitingForOAuth(false);
174
- throw error;
175
- }
176
- },
177
- error_callback: (nonOAuthError: any) => {
178
- setWaitingForProvider(false);
179
- setWaitingForOAuth(false);
180
- onNonOAuthErrorRef.current?.(nonOAuthError);
181
- },
182
- state,
183
- ...props,
184
- });
185
-
186
- clientRef.current = client;
187
- }
188
- }, [scriptLoaded, scope, state]);
189
-
190
- const onInitiateGoogleSignIn = useCallback((overrideConfig?: object, ssoConnectionId?: string | null, formPublicId?: string | null, authenticateOnly?: boolean) => {
191
- ssoConnectionIdRef.current = ssoConnectionId || null;
192
- formPublicIdRef.current = formPublicId || null;
193
- authenticateOnlyRef.current = !!authenticateOnly;
194
- if (clientRef.current) {
195
- setWaitingForProvider(true);
196
- try {
197
- clientRef.current.requestAccessToken(overrideConfig);
198
- } catch (error) {
199
- setWaitingForProvider(false);
200
- throw error;
201
- }
202
- }
203
- }, []);
204
-
205
- return {
206
- onInitiateGoogleSignIn,
207
- oauthButtonDisabled: waitingForProvider,
208
- waitingForOAuth,
209
- };
81
+ const {
82
+ scriptLoaded,
83
+ scope = '',
84
+ onError,
85
+ onNonOAuthError,
86
+ onFinishSignIn,
87
+ onRespondentToken,
88
+ overrideScope,
89
+ state,
90
+ doNotAlertErrors,
91
+ ...props
92
+ } = p;
93
+
94
+ const { dispatchApp } = useContext(AppContext);
95
+ const openModalPopUp = useOpenModalPopUp();
96
+ const [waitingForProvider, setWaitingForProvider] = useState(false);
97
+ const [waitingForOAuth, setWaitingForOAuth] = useState(false);
98
+
99
+ const clientRef = useRef<any>(null);
100
+ const onErrorRef = useRef(onError);
101
+
102
+ onErrorRef.current = onError;
103
+
104
+ const onNonOAuthErrorRef = useRef(onNonOAuthError);
105
+ onNonOAuthErrorRef.current = onNonOAuthError;
106
+
107
+ const onRespondentTokenRef = useRef(onRespondentToken);
108
+ onRespondentTokenRef.current = onRespondentToken;
109
+
110
+ const onFinishSignInRef = useRef(onFinishSignIn);
111
+ onFinishSignInRef.current = onFinishSignIn;
112
+
113
+ const openModalPopUpRef = useRef(openModalPopUp);
114
+ openModalPopUpRef.current = openModalPopUp;
115
+
116
+ const doNotAlertErrorsRef = useRef(doNotAlertErrors);
117
+ doNotAlertErrorsRef.current = doNotAlertErrors;
118
+
119
+ const dispatchAppRef = useRef(dispatchApp);
120
+ dispatchAppRef.current = dispatchApp;
121
+
122
+ // Org SSO connection to sign in through; read by the token callback below
123
+ const ssoConnectionIdRef = useRef<string | null>(null);
124
+ // Public web form context; allows contact-gated account creation (CHILD_ORGS forms)
125
+ const formPublicIdRef = useRef<string | null>(null);
126
+ // When true, a verified email with no account returns a temporary respondent
127
+ // token instead of erroring (ANYONE web forms)
128
+ const authenticateOnlyRef = useRef<boolean>(false);
129
+
130
+ useEffect(() => {
131
+ if (scriptLoaded) {
132
+ // If using this package, it is expected that you install your own Google OAuth script
133
+ const client = (globalThis as any).google?.accounts?.oauth2.initTokenClient({
134
+ client_id: getENVVariable('GOOGLE_OAUTH'),
135
+ scope: overrideScope ? scope : `openid profile email ${scope}`,
136
+ callback: async (response: any) => {
137
+ if (response.error) {
138
+ setWaitingForProvider(false);
139
+ setWaitingForOAuth(false);
140
+ return onErrorRef.current?.(response, null);
141
+ }
142
+
143
+ const { access_token: oauthToken } = response;
144
+ setWaitingForProvider(false);
145
+ setWaitingForOAuth(true);
146
+ const variables = {
147
+ provider: 'GOOGLE' as const,
148
+ oauthToken,
149
+ ssoConnectionId: ssoConnectionIdRef.current,
150
+ formPublicId: formPublicIdRef.current,
151
+ authenticateOnly: authenticateOnlyRef.current,
152
+ };
153
+ const { auth, error } = await authenticateOAuthSignInSession(variables);
154
+ if (error) {
155
+ setWaitingForOAuth(false);
156
+ if (!doNotAlertErrorsRef.current) {
157
+ openModalPopUpRef.current(null, error);
158
+ }
159
+ onErrorRef.current?.(error, variables);
160
+ return;
161
+ }
162
+
163
+ try {
164
+ const authenticated = await applyOAuthAuthenticationResult(
165
+ auth,
166
+ onFinishSignInRef.current,
167
+ onRespondentTokenRef.current,
168
+ dispatchAppRef.current,
169
+ );
170
+ if (!authenticated) {
171
+ setWaitingForOAuth(false);
172
+ }
173
+ } catch (error) {
174
+ setWaitingForOAuth(false);
175
+ throw error;
176
+ }
177
+ },
178
+ error_callback: (nonOAuthError: any) => {
179
+ setWaitingForProvider(false);
180
+ setWaitingForOAuth(false);
181
+ onNonOAuthErrorRef.current?.(nonOAuthError);
182
+ },
183
+ state,
184
+ ...props,
185
+ });
186
+
187
+ clientRef.current = client;
188
+ }
189
+ }, [scriptLoaded, scope, state]);
190
+
191
+ const onInitiateGoogleSignIn = useCallback(
192
+ (overrideConfig?: object, ssoConnectionId?: string | null, formPublicId?: string | null, authenticateOnly?: boolean) => {
193
+ ssoConnectionIdRef.current = ssoConnectionId || null;
194
+ formPublicIdRef.current = formPublicId || null;
195
+ authenticateOnlyRef.current = !!authenticateOnly;
196
+ if (clientRef.current) {
197
+ setWaitingForProvider(true);
198
+ try {
199
+ clientRef.current.requestAccessToken(overrideConfig);
200
+ } catch (error) {
201
+ setWaitingForProvider(false);
202
+ throw error;
203
+ }
204
+ }
205
+ },
206
+ [],
207
+ );
208
+
209
+ return {
210
+ onInitiateGoogleSignIn,
211
+ oauthButtonDisabled: waitingForProvider,
212
+ waitingForOAuth,
213
+ };
210
214
  }
211
215
 
212
216
  /**
@@ -214,42 +218,37 @@ function useGoogleLogin(p: GoogleLoginHookParams) {
214
218
  */
215
219
 
216
220
  export function useContinueWithGoogle(params: ContinueWithGoogleParams) {
217
- const { doNotAlertErrors, onFinishSignIn, onRespondentToken } = params;
218
- const [scriptLoaded, setScriptLoaded] = useState(false);
219
-
220
- useEffect(() => {
221
- const scriptTag = document.createElement('script');
222
- scriptTag.src = 'https://accounts.google.com/gsi/client';
223
- scriptTag.async = true;
224
- scriptTag.defer = true;
225
- // scriptTag.nonce = nonce;
226
-
227
- scriptTag.onload = () => {
228
- setScriptLoaded(true);
229
- };
230
- scriptTag.onerror = () => {
231
- setScriptLoaded(false);
232
- };
233
-
234
- document.body.appendChild(scriptTag);
235
- return () => {
236
- document.body.removeChild(scriptTag);
237
- };
238
- }, []);
239
-
240
- const { onInitiateGoogleSignIn, oauthButtonDisabled, waitingForOAuth } = useGoogleLogin({
241
- doNotAlertErrors,
242
- onFinishSignIn,
243
- onRespondentToken,
244
- scriptLoaded,
245
- });
246
-
247
- return {
248
- oauthButtonDisabled,
249
- waitingForOAuth,
250
- onInitiateGoogleSignIn,
251
- scriptLoaded
252
- };
221
+ const { doNotAlertErrors, onFinishSignIn, onRespondentToken } = params;
222
+ const [scriptLoaded, setScriptLoaded] = useState(false);
223
+
224
+ useEffect(() => {
225
+ let active = true;
226
+ loadGoogleIdentityServices().then(
227
+ () => {
228
+ if (active) setScriptLoaded(true);
229
+ },
230
+ () => {
231
+ if (active) setScriptLoaded(false);
232
+ },
233
+ );
234
+ return () => {
235
+ active = false;
236
+ };
237
+ }, []);
238
+
239
+ const { onInitiateGoogleSignIn, oauthButtonDisabled, waitingForOAuth } = useGoogleLogin({
240
+ doNotAlertErrors,
241
+ onFinishSignIn,
242
+ onRespondentToken,
243
+ scriptLoaded,
244
+ });
245
+
246
+ return {
247
+ oauthButtonDisabled,
248
+ waitingForOAuth,
249
+ onInitiateGoogleSignIn,
250
+ scriptLoaded,
251
+ };
253
252
  }
254
253
 
255
254
  // MSAL client is cached at module level so repeated hook mounts reuse one instance
@@ -260,27 +259,29 @@ let msalClientPromise: Promise<any> | null = null;
260
259
  */
261
260
 
262
261
  function getMSALClient() {
263
- if (!msalClientPromise) {
264
- // Dynamic import keeps MSAL out of the main bundle until Microsoft sign in is used
265
- msalClientPromise = import('@azure/msal-browser').then(async ({ PublicClientApplication }) => {
266
- const pca = new PublicClientApplication({
267
- auth: {
268
- clientId: String(getENVVariable('MICROSOFT_OAUTH') || ''),
269
- authority: 'https://login.microsoftonline.com/common',
270
- redirectUri: getENVVariable('APP_URL') + 'auth/msal',
271
- },
272
- });
273
-
274
- await pca.initialize();
275
- return pca;
276
- }).catch((err) => {
277
- // Do not cache a failed load/initialization; let the next click retry
278
- msalClientPromise = null;
279
- throw err;
280
- });
281
- }
282
-
283
- return msalClientPromise;
262
+ if (!msalClientPromise) {
263
+ // Dynamic import keeps MSAL out of the main bundle until Microsoft sign in is used
264
+ msalClientPromise = import('@azure/msal-browser')
265
+ .then(async ({ PublicClientApplication }) => {
266
+ const pca = new PublicClientApplication({
267
+ auth: {
268
+ clientId: String(getENVVariable('MICROSOFT_OAUTH') || ''),
269
+ authority: 'https://login.microsoftonline.com/common',
270
+ redirectUri: getENVVariable('APP_URL') + 'auth/msal',
271
+ },
272
+ });
273
+
274
+ await pca.initialize();
275
+ return pca;
276
+ })
277
+ .catch((err) => {
278
+ // Do not cache a failed load/initialization; let the next click retry
279
+ msalClientPromise = null;
280
+ throw err;
281
+ });
282
+ }
283
+
284
+ return msalClientPromise;
284
285
  }
285
286
 
286
287
  /**
@@ -288,90 +289,93 @@ function getMSALClient() {
288
289
  */
289
290
 
290
291
  export function useContinueWithMicrosoft(params: ContinueWithMicrosoftParams) {
291
- const { doNotAlertErrors, onFinishSignIn, onRespondentToken, onError } = params;
292
- const { dispatchApp } = useContext(AppContext);
293
- const openModalPopUp = useOpenModalPopUp();
294
- const [waitingForPopUp, setWaitingForPopUp] = useState(false);
295
- const [waitingForOAuth, setWaitingForOAuth] = useState(false);
296
-
297
- const onRespondentTokenRef = useRef(onRespondentToken);
298
- onRespondentTokenRef.current = onRespondentToken;
299
-
300
- const onFinishSignInRef = useRef(onFinishSignIn);
301
- onFinishSignInRef.current = onFinishSignIn;
302
-
303
- const onErrorRef = useRef(onError);
304
- onErrorRef.current = onError;
305
-
306
- const openModalPopUpRef = useRef(openModalPopUp);
307
- openModalPopUpRef.current = openModalPopUp;
308
-
309
- const doNotAlertErrorsRef = useRef(doNotAlertErrors);
310
- doNotAlertErrorsRef.current = doNotAlertErrors;
311
-
312
- const dispatchAppRef = useRef(dispatchApp);
313
- dispatchAppRef.current = dispatchApp;
314
-
315
- const onInitiateMicrosoftSignIn = useCallback(async (ssoOption?: SsoLoginOptionData | any, loginHint?: string, formPublicId?: string | null, authenticateOnly?: boolean) => {
316
- setWaitingForPopUp(true);
317
-
318
- // A plain onClick passes the click event here; only a real SSO option
319
- // (with a tenant id) changes the popup behavior
320
- const ssoTenantId = ssoOption?.microsoftTenantId || null;
321
- const ssoConnectionId = ssoTenantId ? ssoOption?.id : null;
322
-
323
- try {
324
- const pca = await getMSALClient();
325
- const result = await pca.loginPopup({
326
- scopes: ['openid', 'profile', 'email'],
327
- prompt: 'select_account',
328
- // Pin the popup to the org's Entra tenant instead of "common"
329
- ...ssoTenantId ? { authority: `https://login.microsoftonline.com/${ssoTenantId}` } : null,
330
- ...loginHint ? { loginHint } : null,
331
- });
332
-
333
- if (result?.idToken) {
334
- setWaitingForOAuth(true);
335
- const variables = {
336
- provider: 'MICROSOFT' as const,
337
- idToken: result.idToken,
338
- ssoConnectionId,
339
- formPublicId,
340
- authenticateOnly,
341
- };
342
- const authentication = await authenticateOAuthSignInSession(variables);
343
- if (authentication.error) {
344
- setWaitingForOAuth(false);
345
- if (!doNotAlertErrorsRef.current) {
346
- openModalPopUpRef.current(null, authentication.error);
347
- }
348
- onErrorRef.current?.(authentication.error, variables);
349
- } else {
350
- const authenticated = await applyOAuthAuthenticationResult(
351
- authentication.auth,
352
- onFinishSignInRef.current,
353
- onRespondentTokenRef.current,
354
- dispatchAppRef.current,
355
- );
356
- if (!authenticated) {
357
- setWaitingForOAuth(false);
358
- }
359
- }
360
- }
361
- } catch (err: any) {
362
- setWaitingForOAuth(false);
363
- // User closing/cancelling the popup is not an error
364
- if (err?.errorCode !== 'user_cancelled') {
365
- console.warn(err);
366
- }
367
- } finally {
368
- setWaitingForPopUp(false);
369
- }
370
- }, []);
371
-
372
- return {
373
- onInitiateMicrosoftSignIn,
374
- oauthButtonDisabled: waitingForPopUp,
375
- waitingForOAuth,
376
- };
292
+ const { doNotAlertErrors, onFinishSignIn, onRespondentToken, onError } = params;
293
+ const { dispatchApp } = useContext(AppContext);
294
+ const openModalPopUp = useOpenModalPopUp();
295
+ const [waitingForPopUp, setWaitingForPopUp] = useState(false);
296
+ const [waitingForOAuth, setWaitingForOAuth] = useState(false);
297
+
298
+ const onRespondentTokenRef = useRef(onRespondentToken);
299
+ onRespondentTokenRef.current = onRespondentToken;
300
+
301
+ const onFinishSignInRef = useRef(onFinishSignIn);
302
+ onFinishSignInRef.current = onFinishSignIn;
303
+
304
+ const onErrorRef = useRef(onError);
305
+ onErrorRef.current = onError;
306
+
307
+ const openModalPopUpRef = useRef(openModalPopUp);
308
+ openModalPopUpRef.current = openModalPopUp;
309
+
310
+ const doNotAlertErrorsRef = useRef(doNotAlertErrors);
311
+ doNotAlertErrorsRef.current = doNotAlertErrors;
312
+
313
+ const dispatchAppRef = useRef(dispatchApp);
314
+ dispatchAppRef.current = dispatchApp;
315
+
316
+ const onInitiateMicrosoftSignIn = useCallback(
317
+ async (ssoOption?: SsoLoginOptionData | any, loginHint?: string, formPublicId?: string | null, authenticateOnly?: boolean) => {
318
+ setWaitingForPopUp(true);
319
+
320
+ // A plain onClick passes the click event here; only a real SSO option
321
+ // (with a tenant id) changes the popup behavior
322
+ const ssoTenantId = ssoOption?.microsoftTenantId || null;
323
+ const ssoConnectionId = ssoTenantId ? ssoOption?.id : null;
324
+
325
+ try {
326
+ const pca = await getMSALClient();
327
+ const result = await pca.loginPopup({
328
+ scopes: ['openid', 'profile', 'email'],
329
+ prompt: 'select_account',
330
+ // Pin the popup to the org's Entra tenant instead of "common"
331
+ ...(ssoTenantId ? { authority: `https://login.microsoftonline.com/${ssoTenantId}` } : null),
332
+ ...(loginHint ? { loginHint } : null),
333
+ });
334
+
335
+ if (result?.idToken) {
336
+ setWaitingForOAuth(true);
337
+ const variables = {
338
+ provider: 'MICROSOFT' as const,
339
+ idToken: result.idToken,
340
+ ssoConnectionId,
341
+ formPublicId,
342
+ authenticateOnly,
343
+ };
344
+ const authentication = await authenticateOAuthSignInSession(variables);
345
+ if (authentication.error) {
346
+ setWaitingForOAuth(false);
347
+ if (!doNotAlertErrorsRef.current) {
348
+ openModalPopUpRef.current(null, authentication.error);
349
+ }
350
+ onErrorRef.current?.(authentication.error, variables);
351
+ } else {
352
+ const authenticated = await applyOAuthAuthenticationResult(
353
+ authentication.auth,
354
+ onFinishSignInRef.current,
355
+ onRespondentTokenRef.current,
356
+ dispatchAppRef.current,
357
+ );
358
+ if (!authenticated) {
359
+ setWaitingForOAuth(false);
360
+ }
361
+ }
362
+ }
363
+ } catch (err: any) {
364
+ setWaitingForOAuth(false);
365
+ // User closing/cancelling the popup is not an error
366
+ if (err?.errorCode !== 'user_cancelled') {
367
+ console.warn(err);
368
+ }
369
+ } finally {
370
+ setWaitingForPopUp(false);
371
+ }
372
+ },
373
+ [],
374
+ );
375
+
376
+ return {
377
+ onInitiateMicrosoftSignIn,
378
+ oauthButtonDisabled: waitingForPopUp,
379
+ waitingForOAuth,
380
+ };
377
381
  }