@jsb188/auth-web 1.1.10 → 1.1.11

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