@jsb188/auth-web 1.1.2

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.
@@ -0,0 +1,914 @@
1
+ import { APP_EMAILS } from '@jsb188/app/constants/app.ts';
2
+ import i18n from '@jsb188/app/i18n/index.ts';
3
+ import {
4
+ useAuthenticateAsAgent,
5
+ useCheckUsernameOrEmail,
6
+ useConfirmPhoneVerificationCode,
7
+ useRequestTokenizedEmail,
8
+ useSendPhoneVerificationCode,
9
+ useSignUpWithEmail,
10
+ } from '@jsb188/graphql/hooks/use-auth-mtn';
11
+ import { useSendPublicFormEmailCode } from '@jsb188/graphql/hooks/use-publicFormEmail-mtn';
12
+ import { SMSCodeInput } from '@jsb188/form/modules/Form';
13
+ import SchemaForm from '@jsb188/form/libs/SchemaForm';
14
+ import { submissionResult } from '@jsb188/form/libs/validation';
15
+ import type { FormActions, SubmitResult } from '@jsb188/form/libs/SchemaForm.types';
16
+ import { FullWidthButton } from '@jsb188/react-web/ui/Button';
17
+ import { FormBreak } from '@jsb188/form/ui/Form';
18
+ import Markdown, { TextWithLinks } from '@jsb188/react-web/ui/Markdown';
19
+ import { ModalErrorMessage, ModalSimpleContent } from '@jsb188/react-web/ui/ModalUI';
20
+ import { useEffect, useMemo, useRef, useState } from 'react';
21
+ import { Link, useNavigate } from 'react-router';
22
+ import { getAuthPopupCompletionPath } from '../utils/authPopup.ts';
23
+ import type { AuthPageName } from './_helpers';
24
+ import { getAuthReturnQuery, getAuthRoute, persistSignInSession } from './_helpers';
25
+ import { SsoSignIn } from './AuthForms-SSO';
26
+ import { ConfirmPublicFormEmailCode } from './ConfirmPublicFormEmailCode';
27
+ import { ContinueWithGoogle, ContinueWithMicrosoft, ContinueWithPhone, ContinueWithSso } from './OtherAuthButtons';
28
+ import {
29
+ type SignInFormValues,
30
+ makeRequestTokenizedEmailSchema,
31
+ makeSendPhoneVerificationSchema,
32
+ makeSignInSchema,
33
+ makeSignUpSchema,
34
+ } from './schemas';
35
+
36
+ /**
37
+ * Page meta tags
38
+ */
39
+
40
+ export const meta = [
41
+ {
42
+ title: i18n.t('app.route_', { text: i18n.t('app.route_auth') }),
43
+ },
44
+ ];
45
+
46
+ /**
47
+ * Sign in form (main screen)
48
+ */
49
+
50
+ interface AuthFormProps {
51
+ appNamespace: string;
52
+ formPublicId?: string | null;
53
+ allowPublicFormEmail?: boolean;
54
+ onPublicFormRespondentVerified?: (token: string, email: string | null) => boolean;
55
+ initialMethod?: 'PHONE';
56
+ initialError?: any;
57
+ initialFormData?: any;
58
+ authRoutesMap?: Record<AuthPageName, string>;
59
+ popupId?: string | null;
60
+ popupMode?: boolean;
61
+ returnTo?: string | null;
62
+ // Development-only: when true, show the password-less "AI agents Enter"
63
+ // button. Provided by the host app's sign-in loader; the server reports it
64
+ // as true only on a local development database.
65
+ agentLoginAvailable?: boolean;
66
+ setAuthIface: (iface: SignInIface | null) => void;
67
+
68
+ // Check if needed still
69
+ onError?: (error: any) => void;
70
+ }
71
+
72
+ /*
73
+ * Preserve public-form and popup context across one authentication navigation.
74
+ */
75
+ function getAuthNavigationQuery(returnTo?: string | null, popupMode?: boolean, popupId?: string | null) {
76
+ const searchParams = new URLSearchParams(getAuthReturnQuery(returnTo));
77
+ if (popupMode && popupId) {
78
+ searchParams.set('popup', '1');
79
+ searchParams.set('popupId', popupId);
80
+ }
81
+
82
+ return searchParams.toString() || undefined;
83
+ }
84
+
85
+ /*
86
+ * Return the popup handoff route or the standard post-authentication route.
87
+ */
88
+ function getSignInSuccessRoute(p: Pick<AuthFormProps, 'authRoutesMap' | 'popupId' | 'popupMode' | 'returnTo'>) {
89
+ const popupCompletionPath = p.popupMode ? getAuthPopupCompletionPath(p.popupId) : null;
90
+ if (popupCompletionPath) {
91
+ return popupCompletionPath;
92
+ }
93
+
94
+ return getAuthRoute('signin_success', p.authRoutesMap, getAuthReturnQuery(p.returnTo));
95
+ }
96
+
97
+ /*
98
+ * Discover existing accounts or send one public-form email code before choosing the verification screen.
99
+ */
100
+ const SignInMain = (p: AuthFormProps) => {
101
+ const { authRoutesMap, formPublicId, initialError, initialFormData, popupId, popupMode, returnTo, setAuthIface } = p;
102
+ const navigate = useNavigate();
103
+ const [waitingForPostRequest, setWaitingForPostRequest] = useState(false);
104
+ const mounted = useRef(true);
105
+ const signInSchema = useMemo(makeSignInSchema, []);
106
+ const allowPublicFormEmail = !!p.allowPublicFormEmail && !!formPublicId && !!p.onPublicFormRespondentVerified;
107
+ const { sendPublicFormEmailCode, saving: sendingEmailCode } = useSendPublicFormEmailCode();
108
+ const { saving, checkUsernameOrEmail, dataForSchema, setDataForSchema, error, setError, resetErrors } = useCheckUsernameOrEmail({
109
+ initialError,
110
+ initialFormData: {
111
+ ...initialFormData,
112
+ usernameOrEmail: initialFormData?.identifier || initialFormData?.usernameOrEmail || '',
113
+ },
114
+ });
115
+
116
+ const hidePassword = dataForSchema.hidePassword;
117
+
118
+ useEffect(() => {
119
+ mounted.current = true;
120
+ return () => {
121
+ mounted.current = false;
122
+ };
123
+ }, []);
124
+
125
+ /* Return to identifier discovery when the previously resolved identifier changes. */
126
+ const onFormValuesChange = (formValues: SignInFormValues, { setValues }: FormActions<SignInFormValues>) => {
127
+ const hasInput = !!formValues.identifier?.trim();
128
+ if (!hidePassword && formValues.identifier !== dataForSchema.lastIdentifier) {
129
+ setDataForSchema({
130
+ ...dataForSchema,
131
+ hasInput,
132
+ lastIdentifier: '',
133
+ hidePassword: true,
134
+ });
135
+
136
+ setValues({
137
+ ...formValues,
138
+ password: '',
139
+ });
140
+ } else if (hasInput !== dataForSchema.hasInput) {
141
+ setDataForSchema({
142
+ ...dataForSchema,
143
+ hasInput,
144
+ });
145
+ }
146
+ };
147
+
148
+ /* Resolve the account before authorizing the native password-manager-compatible form POST. */
149
+ const onSubmit = async (
150
+ formValues: SignInFormValues,
151
+ { getValues, setValues }: FormActions<SignInFormValues>,
152
+ ): Promise<SubmitResult<SignInFormValues>> => {
153
+ const identifier = formValues.identifier.trim();
154
+ if (hidePassword) {
155
+ const response = await checkUsernameOrEmail({
156
+ variables: {
157
+ usernameOrEmail: identifier,
158
+ authCheck: !allowPublicFormEmail,
159
+ },
160
+ });
161
+ if (!mounted.current) {
162
+ return { status: 'continue' };
163
+ }
164
+ if (getValues().identifier.trim() !== identifier) {
165
+ resetErrors();
166
+ return { status: 'continue' };
167
+ }
168
+ const submission = submissionResult(response);
169
+ if (submission.status !== 'success') {
170
+ return submission;
171
+ }
172
+ const result = response?.checkUsernameOrEmail;
173
+
174
+ switch (result?.type) {
175
+ case 'PHONE':
176
+ if (!result.taken) {
177
+ return { status: 'error', error: { message: i18n.t('auth.no_account_with_phone') } };
178
+ }
179
+ if (result.hasPassword === false) {
180
+ setAuthIface('VERIFY_PHONE');
181
+ return { status: 'continue' };
182
+ }
183
+ break;
184
+ case 'EMAIL':
185
+ if (!result.taken) {
186
+ if (allowPublicFormEmail) {
187
+ const email = identifier.toLowerCase();
188
+ const sent = await sendPublicFormEmailCode({ variables: { formPublicId, email } });
189
+ if (!mounted.current) {
190
+ return { status: 'continue' };
191
+ }
192
+ if (getValues().identifier.trim() !== identifier) {
193
+ resetErrors();
194
+ return { status: 'continue' };
195
+ }
196
+ const sendSubmission = submissionResult(sent);
197
+ if (sendSubmission.status !== 'success') {
198
+ return sendSubmission;
199
+ }
200
+ if (!sent?.sendPublicFormEmailCode) {
201
+ return { status: 'error', error: { message: i18n.t('error.30000') } };
202
+ }
203
+ setAuthIface(['VERIFY_PUBLIC_FORM_EMAIL_SENT', email]);
204
+ return { status: 'continue' };
205
+ }
206
+ return { status: 'error', error: { message: i18n.t('auth.no_account_with_email') } };
207
+ }
208
+ break;
209
+ default:
210
+ return { status: 'error', error: { message: i18n.t('auth.not_valid_email_or_phone') } };
211
+ }
212
+
213
+ setDataForSchema({
214
+ ...dataForSchema,
215
+ lastIdentifier: identifier,
216
+ hidePassword: false,
217
+ });
218
+ setValues((currentValues) => ({ ...currentValues, identifier }));
219
+ } else if (formValues.password && identifier) {
220
+ setWaitingForPostRequest(true);
221
+ return { status: 'native' };
222
+ }
223
+
224
+ return { status: 'continue' };
225
+ };
226
+
227
+ const showSignUpLink = hidePassword && !error;
228
+
229
+ const onFinishSignIn = async (token: string, sessionBootstrapToken?: string | null, sessionPersisted?: boolean) => {
230
+ const persisted = sessionPersisted || (await persistSignInSession(token, sessionBootstrapToken));
231
+ if (!persisted) {
232
+ setError({
233
+ message: i18n.t('error.network_error'),
234
+ });
235
+ return false;
236
+ }
237
+ navigate(getSignInSuccessRoute({ authRoutesMap, popupId, popupMode, returnTo }));
238
+ return true;
239
+ };
240
+
241
+ // Development-only password-less agent login. agentLoginAvailable is
242
+ // resolved server-side (true only on a local development database), so the
243
+ // button never shows in production.
244
+ const agentLoginAvailable = p.agentLoginAvailable === true;
245
+ const { authenticateAsAgent, saving: agentLoginSaving } = useAuthenticateAsAgent({
246
+ onCompleted: async (data: any) => {
247
+ const auth = data?.authenticateAsAgent;
248
+ if (!auth?.token && !auth?.sessionBootstrapToken) {
249
+ setError({ message: i18n.t('error.network_error') });
250
+ return;
251
+ }
252
+ await onFinishSignIn(auth.token, auth.sessionBootstrapToken);
253
+ },
254
+ /* Forward GraphQL failures only when the callback carries an error. */
255
+ onError: (error) => {
256
+ if (error) setError(error);
257
+ },
258
+ });
259
+
260
+ const onClickAgentLogin = (e: { preventDefault: () => void }) => {
261
+ e.preventDefault();
262
+ const identifier = dataForSchema.lastIdentifier?.trim();
263
+ if (identifier) {
264
+ authenticateAsAgent({ variables: { identifier } });
265
+ }
266
+ };
267
+
268
+ // Show the agent button above the password submit button, once the account
269
+ // has been resolved and the password field is visible
270
+ const agentLoginFooter =
271
+ agentLoginAvailable && !hidePassword ? (
272
+ <FullWidthButton
273
+ className='mt_sm'
274
+ preset='bg_secondary'
275
+ loading={agentLoginSaving}
276
+ onClick={onClickAgentLogin}
277
+ >
278
+ {i18n.t('auth.agent_login')}
279
+ </FullWidthButton>
280
+ ) : null;
281
+
282
+ return (
283
+ <>
284
+ {popupMode ? null : (
285
+ <>
286
+ <ContinueWithGoogle
287
+ formPublicId={formPublicId}
288
+ onFinishSignIn={onFinishSignIn}
289
+ />
290
+ <ContinueWithMicrosoft
291
+ formPublicId={formPublicId}
292
+ onFinishSignIn={onFinishSignIn}
293
+ />
294
+ <ContinueWithSso onClickButton={() => setAuthIface('SSO')} />
295
+ </>
296
+ )}
297
+ <ContinueWithPhone onClickButton={() => setAuthIface('VERIFY_PHONE')} />
298
+
299
+ <FormBreak
300
+ className='mt_md'
301
+ colorClassName='strong_bf'
302
+ >
303
+ {i18n.t('c.or')}
304
+ </FormBreak>
305
+
306
+ <SchemaForm
307
+ method='post'
308
+ actionUrl={getAuthRoute('signin', authRoutesMap, getAuthNavigationQuery(returnTo, popupMode, popupId))}
309
+ className='py_df'
310
+ initialValues={{ identifier: initialFormData?.identifier || '' }}
311
+ busy={saving || sendingEmailCode || waitingForPostRequest}
312
+ definition={signInSchema}
313
+ context={dataForSchema}
314
+ onSubmit={onSubmit}
315
+ onError={setError}
316
+ onValuesChange={onFormValuesChange}
317
+ FooterComponent={agentLoginFooter}
318
+ >
319
+ <input
320
+ type='hidden'
321
+ name='managedSessionVersion'
322
+ value='1'
323
+ />
324
+ {error && (
325
+ <ModalErrorMessage
326
+ error={error}
327
+ resetErrors={resetErrors}
328
+ // className='mt_sm'
329
+ />
330
+ )}
331
+ </SchemaForm>
332
+
333
+ {!showSignUpLink || !popupMode ? (
334
+ <div className='a_c'>
335
+ {showSignUpLink ? (
336
+ <Link
337
+ className='text ft_sm cl_md link'
338
+ to={getAuthRoute('signup', authRoutesMap, getAuthNavigationQuery(returnTo, popupMode, popupId))}
339
+ replace
340
+ >
341
+ {i18n.t('auth.signup_email')}
342
+ </Link>
343
+ ) : (
344
+ <button
345
+ type='button'
346
+ className='text ft_sm cl_md link'
347
+ onClick={() => setAuthIface('REQUEST_PASSWORD_RESET')}
348
+ >
349
+ {i18n.t('auth.forgot_password_')}
350
+ </button>
351
+ )}
352
+ </div>
353
+ ) : null}
354
+ </>
355
+ );
356
+ };
357
+
358
+ /**
359
+ * Forgot password form
360
+ */
361
+
362
+ interface RequestTokenizedEmailProps extends AuthFormProps {
363
+ requestType: 'PASSWORD_RESET' | 'EMAIL_VERIFICATION';
364
+ }
365
+
366
+ function RequestTokenizedEmail(p: RequestTokenizedEmailProps) {
367
+ const { requestType, initialFormData, setAuthIface } = p;
368
+ const [error, setError] = useState<any>(null);
369
+ const initialEmailAddress = initialFormData?.identifier || '';
370
+ const onSuccess = (_emailAddress: string) => setAuthIface('EMAIL_SENT');
371
+
372
+ const tokenizedEmailSchema = useMemo(() => {
373
+ const schema = makeRequestTokenizedEmailSchema();
374
+ if (!initialEmailAddress) {
375
+ return schema;
376
+ }
377
+
378
+ return {
379
+ ...schema,
380
+ fields: {
381
+ ...schema.fields,
382
+ email: {
383
+ ...schema.fields.email!,
384
+ placeholder: initialEmailAddress,
385
+ },
386
+ },
387
+ };
388
+ }, []);
389
+
390
+ // Data hook
391
+
392
+ const { requestTokenizedEmail, saving } = useRequestTokenizedEmail({
393
+ onCompleted: (data: any, _: any, variables: any) => {
394
+ const success = data?.requestTokenizedEmail;
395
+ if (success) {
396
+ onSuccess(variables.email);
397
+ }
398
+ },
399
+ onError: (err: any) => {
400
+ setError(err);
401
+ },
402
+ });
403
+
404
+ /* Await the authentication request so submission state includes failures and completion. */
405
+ const onSubmit = async (fv: { email: string }) => {
406
+ const result = await requestTokenizedEmail({
407
+ variables: {
408
+ ...fv,
409
+ requestType,
410
+ },
411
+ });
412
+ return submissionResult(result);
413
+ };
414
+
415
+ let instructionText: string | undefined;
416
+ switch (requestType) {
417
+ case 'PASSWORD_RESET':
418
+ instructionText = i18n.t('auth.request_reset_password_instr');
419
+ break;
420
+ case 'EMAIL_VERIFICATION':
421
+ instructionText = i18n.t('auth.resend_verification_instr');
422
+ break;
423
+ default:
424
+ }
425
+
426
+ return (
427
+ <SchemaForm
428
+ busy={saving}
429
+ definition={tokenizedEmailSchema}
430
+ initialValues={{ email: initialEmailAddress || '' }}
431
+ onError={setError}
432
+ onSubmit={onSubmit}
433
+ buttonText={i18n.t('auth.resend_verification')}
434
+ >
435
+ {!error ? null : (
436
+ <ModalErrorMessage
437
+ error={error}
438
+ resetErrors={() => setError(null)}
439
+ />
440
+ )}
441
+
442
+ <Markdown
443
+ as='p'
444
+ className={error ? 'py_xs a_c' : '-mt_5 pb_xs a_c'}
445
+ >
446
+ {instructionText}
447
+ </Markdown>
448
+ </SchemaForm>
449
+ );
450
+ }
451
+
452
+ /**
453
+ * Request for password reset is completed
454
+ */
455
+
456
+ function ResetPasswordCompleted(p: AuthFormProps) {
457
+ const { initialFormData } = p;
458
+ const emailAddress = initialFormData?.identifier;
459
+ const supportEmail = APP_EMAILS.support;
460
+
461
+ // Because this screen is opened by a client-side fetch, emailAddress will not always be present;
462
+ // Only way to have the used email address here is if we used POST form request.
463
+
464
+ return (
465
+ <ModalSimpleContent
466
+ title={i18n.t('auth.email_sent')}
467
+ iconName='circle-check'
468
+ >
469
+ <TextWithLinks as='p'>
470
+ {i18n.t(emailAddress ? 'auth.reset_password_requested_msg' : 'auth.reset_password_requested_msg_no_email', { emailAddress })}
471
+ </TextWithLinks>
472
+ <TextWithLinks as='p'>{i18n.t('auth.if_need_more_help_email', { emailAddress: supportEmail })}</TextWithLinks>
473
+ </ModalSimpleContent>
474
+ );
475
+ }
476
+
477
+ /**
478
+ * Request phone verification
479
+ */
480
+
481
+ function SendPhoneVerification(p: AuthFormProps) {
482
+ const { setAuthIface } = p;
483
+ const sendPhoneVerificationSchema = useMemo(() => makeSendPhoneVerificationSchema(), []);
484
+
485
+ // Data hook
486
+
487
+ const { sendPhoneVerificationCode, saving, error, setError, resetErrors } = useSendPhoneVerificationCode({
488
+ onCompleted: (data: any, _: any, variables: any) => {
489
+ const success = data?.sendPhoneVerificationCode;
490
+ if (success) {
491
+ setAuthIface(['VERIFY_PHONE_SENT', variables.phone]);
492
+ }
493
+ },
494
+ onError: (err: any) => {
495
+ setError(err);
496
+ },
497
+ });
498
+
499
+ /* Await the authentication request so submission state includes failures and completion. */
500
+ const onSubmit = async (fv: { phone: string }) => {
501
+ const result = await sendPhoneVerificationCode({
502
+ variables: {
503
+ phone: fv.phone,
504
+ },
505
+ });
506
+ return submissionResult(result);
507
+ };
508
+
509
+ return (
510
+ <>
511
+ <SchemaForm
512
+ className='mb_df'
513
+ busy={saving}
514
+ definition={sendPhoneVerificationSchema}
515
+ onError={setError}
516
+ onSubmit={onSubmit}
517
+ buttonText={i18n.t('auth.send_verification_code')}
518
+ >
519
+ {!error ? null : (
520
+ <ModalErrorMessage
521
+ error={error}
522
+ resetErrors={resetErrors}
523
+ />
524
+ )}
525
+
526
+ <p className={error ? 'py_xs a_c' : '-mt_5 pb_xs a_c'}>{i18n.t('auth.send_verification_code_msg')}</p>
527
+ </SchemaForm>
528
+
529
+ <div className='a_c h_center'>
530
+ <button
531
+ type='button'
532
+ disabled={saving}
533
+ onClick={() => setAuthIface(null)}
534
+ className='text ft_sm cl_md link'
535
+ >
536
+ {i18n.t('auth.sign_in_other_methods')}
537
+ </button>
538
+ </div>
539
+ </>
540
+ );
541
+ }
542
+
543
+ /**
544
+ * Confirm phone verification code (after it was sent)
545
+ */
546
+
547
+ interface ConfirmPhoneVerificationCodeProps extends AuthFormProps {
548
+ phoneNumber: string;
549
+ }
550
+
551
+ function ConfirmPhoneVerificationCode(p: ConfirmPhoneVerificationCodeProps) {
552
+ const { setAuthIface, phoneNumber, authRoutesMap, popupId, popupMode, returnTo } = p;
553
+ const [retryCount, setRetryCount] = useState(0);
554
+ const navigate = useNavigate();
555
+
556
+ // Data hook
557
+
558
+ const { confirmPhoneVerificationCode, saving, error, setError, resetErrors } = useConfirmPhoneVerificationCode({
559
+ onCompleted: async (data: any, _: any) => {
560
+ const { success, token } = data?.confirmPhoneVerificationCode || {};
561
+
562
+ if (success && token) {
563
+ const persisted = await persistSignInSession(token);
564
+ if (!persisted) {
565
+ setError({
566
+ message: i18n.t('error.network_error'),
567
+ });
568
+ return;
569
+ }
570
+ navigate(
571
+ getSignInSuccessRoute({
572
+ authRoutesMap,
573
+ popupId,
574
+ popupMode,
575
+ returnTo,
576
+ }),
577
+ );
578
+ } else {
579
+ setRetryCount(retryCount + 1);
580
+ setError({
581
+ message: i18n.t('auth.verification_code_wrong'),
582
+ });
583
+ }
584
+ },
585
+ });
586
+
587
+ const onSubmit = (code: string) => {
588
+ confirmPhoneVerificationCode({
589
+ variables: {
590
+ phone: phoneNumber,
591
+ code,
592
+ },
593
+ });
594
+ };
595
+
596
+ return (
597
+ <>
598
+ {!error ? null : (
599
+ <ModalErrorMessage
600
+ error={error}
601
+ resetErrors={resetErrors}
602
+ />
603
+ )}
604
+ <SMSCodeInput
605
+ key={retryCount}
606
+ saving={saving}
607
+ error={error}
608
+ onSubmit={onSubmit}
609
+ />
610
+ <p className='a_c p_n mt_md mb_df rel'>{i18n.t('auth.confirm_verification_code_instr')}</p>
611
+ <div className='a_c h_center'>
612
+ <button
613
+ type='button'
614
+ disabled={saving}
615
+ onClick={() => setAuthIface('VERIFY_PHONE')}
616
+ className='text ft_sm cl_md link'
617
+ >
618
+ {i18n.t('auth.resend_verification_code')}
619
+ </button>
620
+ </div>
621
+ </>
622
+ );
623
+ }
624
+
625
+ /**
626
+ * Sign in form
627
+ */
628
+
629
+ type SignInIface =
630
+ | 'REQUEST_PASSWORD_RESET'
631
+ | 'SSO'
632
+ | 'VERIFY_PHONE'
633
+ | 'VERIFY_EMAIL'
634
+ | 'EMAIL_SENT'
635
+ | 'VERIFY_PHONE_SENT'
636
+ | ['VERIFY_PUBLIC_FORM_EMAIL_SENT', string]
637
+ | ['VERIFY_PHONE_SENT', string];
638
+
639
+ export function SignInForm(p: Omit<AuthFormProps, 'setAuthIface'>) {
640
+ const { initialError } = p;
641
+ const errCode = initialError?.errorCode;
642
+ const initialIface =
643
+ p.initialMethod === 'PHONE' ? 'VERIFY_PHONE' : errCode === '20053' ? 'VERIFY_PHONE' : errCode === '20049' ? 'VERIFY_EMAIL' : null;
644
+ const [signInIface_, setAuthIface] = useState<SignInIface | null>(initialIface);
645
+ const ifaceIsArray = Array.isArray(signInIface_);
646
+
647
+ /* Return changed public-form emails to account discovery before choosing their authentication method. */
648
+ const onReturnToSignIn = () => setAuthIface(null);
649
+
650
+ switch (ifaceIsArray ? signInIface_[0] : signInIface_) {
651
+ case 'VERIFY_PUBLIC_FORM_EMAIL_SENT':
652
+ if (!p.allowPublicFormEmail || !p.formPublicId || !p.onPublicFormRespondentVerified) {
653
+ break;
654
+ }
655
+ return (
656
+ <ConfirmPublicFormEmailCode
657
+ formPublicId={p.formPublicId}
658
+ email={ifaceIsArray ? signInIface_[1] : ''}
659
+ onRespondentToken={p.onPublicFormRespondentVerified}
660
+ onChangeEmail={onReturnToSignIn}
661
+ />
662
+ );
663
+ case 'SSO':
664
+ // Email-first SSO sign in (org home realm discovery)
665
+ return (
666
+ <SsoSignIn
667
+ {...p}
668
+ setAuthIface={setAuthIface}
669
+ />
670
+ );
671
+ case 'VERIFY_PHONE':
672
+ // Attempted phone login but it was not verified
673
+ return (
674
+ <SendPhoneVerification
675
+ {...p}
676
+ setAuthIface={setAuthIface}
677
+ />
678
+ );
679
+ case 'VERIFY_PHONE_SENT':
680
+ // User requested phone verification code, and it was sent
681
+ return (
682
+ <ConfirmPhoneVerificationCode
683
+ {...p}
684
+ phoneNumber={ifaceIsArray ? signInIface_[1] : ''}
685
+ setAuthIface={setAuthIface}
686
+ />
687
+ );
688
+ case 'VERIFY_EMAIL':
689
+ // Attempted email login but it was not verified
690
+ return (
691
+ <RequestTokenizedEmail
692
+ {...p}
693
+ requestType='EMAIL_VERIFICATION'
694
+ setAuthIface={setAuthIface}
695
+ />
696
+ );
697
+ case 'REQUEST_PASSWORD_RESET':
698
+ return (
699
+ <RequestTokenizedEmail
700
+ {...p}
701
+ requestType='PASSWORD_RESET'
702
+ setAuthIface={setAuthIface}
703
+ />
704
+ );
705
+ case 'EMAIL_SENT':
706
+ return (
707
+ <ResetPasswordCompleted
708
+ {...p}
709
+ setAuthIface={setAuthIface}
710
+ />
711
+ );
712
+ default:
713
+ }
714
+
715
+ return (
716
+ <SignInMain
717
+ {...p}
718
+ setAuthIface={setAuthIface}
719
+ />
720
+ );
721
+ }
722
+
723
+ /**
724
+ * Sign up main form
725
+ */
726
+
727
+ interface SignUpMainProps extends Omit<AuthFormProps, 'setAuthIface'> {
728
+ setAuthIface: (iface: SignUpIface) => void;
729
+ setSignUpToken: (token: string | null) => void;
730
+ }
731
+
732
+ function SignUpMain(p: SignUpMainProps) {
733
+ const { authRoutesMap, formPublicId, initialError, returnTo, setAuthIface, setSignUpToken } = p;
734
+ const navigate = useNavigate();
735
+ const signUpSchema = useMemo(makeSignUpSchema, []);
736
+
737
+ const { saving, signUpWithEmail, error, setError, resetErrors } = useSignUpWithEmail({
738
+ initialError,
739
+ onCompleted: (data: any, _: any) => {
740
+ const signUpToken = data?.signUpWithEmail;
741
+
742
+ if (signUpToken) {
743
+ setSignUpToken(signUpToken);
744
+ }
745
+ },
746
+ onError: (err: any) => {
747
+ if (err?.errorCode === '20054') {
748
+ setAuthIface('INVITATION_REQUIRED');
749
+ }
750
+ },
751
+ });
752
+
753
+ /* Await the authentication request so submission state includes failures and completion. */
754
+ const onSubmit = async (formValues: { email: string; password: string; passwordRepeat: string }) => {
755
+ const result = await signUpWithEmail({
756
+ variables: {
757
+ emailAddress: formValues.email,
758
+ password: formValues.password,
759
+ },
760
+ });
761
+ return submissionResult(result);
762
+ };
763
+
764
+ // SSO providers auto-create accounts, so they work as sign up too
765
+ const onFinishSignIn = async (token: string, sessionBootstrapToken?: string | null, sessionPersisted?: boolean) => {
766
+ const persisted = sessionPersisted || (await persistSignInSession(token, sessionBootstrapToken));
767
+ if (!persisted) {
768
+ setError({
769
+ message: i18n.t('error.network_error'),
770
+ });
771
+ return false;
772
+ }
773
+ navigate(getAuthRoute('signin_success', authRoutesMap, getAuthReturnQuery(returnTo)));
774
+ return true;
775
+ };
776
+
777
+ return (
778
+ <>
779
+ <ContinueWithGoogle
780
+ formPublicId={formPublicId}
781
+ onFinishSignIn={onFinishSignIn}
782
+ />
783
+ <ContinueWithMicrosoft
784
+ formPublicId={formPublicId}
785
+ onFinishSignIn={onFinishSignIn}
786
+ />
787
+
788
+ <FormBreak
789
+ className='mt_md'
790
+ colorClassName='strong_bf'
791
+ >
792
+ {i18n.t('c.or')}
793
+ </FormBreak>
794
+
795
+ <SchemaForm
796
+ className='py_df'
797
+ busy={saving}
798
+ definition={signUpSchema}
799
+ onError={setError}
800
+ onSubmit={onSubmit}
801
+ buttonText={i18n.t('auth.agree_and_continue')}
802
+ FooterComponent={
803
+ <TextWithLinks
804
+ as='div'
805
+ className='ft_xs mt_sm cl_md'
806
+ linkClassName='u link cl_md'
807
+ >
808
+ {i18n.t('auth.sign_up_notice_msg')}
809
+ </TextWithLinks>
810
+ }
811
+ >
812
+ {!error ? null : (
813
+ <ModalErrorMessage
814
+ error={error}
815
+ resetErrors={resetErrors}
816
+ // className='mt_sm'
817
+ />
818
+ )}
819
+ </SchemaForm>
820
+
821
+ <div className='a_c h_center'>
822
+ <Link
823
+ to={getAuthRoute('signin', authRoutesMap, getAuthReturnQuery(returnTo))}
824
+ replace
825
+ className='text ft_sm cl_md link'
826
+ >
827
+ {i18n.t('auth.sign_in_w_existing')}
828
+ </Link>
829
+ </div>
830
+ </>
831
+ );
832
+ }
833
+
834
+ /**
835
+ * Sign up; invitation required
836
+ */
837
+
838
+ function SignUpInviteRequired(_p: Omit<AuthFormProps, 'setAuthIface'>) {
839
+ const supportEmail = APP_EMAILS.support;
840
+
841
+ return (
842
+ <ModalSimpleContent
843
+ title={i18n.t('auth.invite_required')}
844
+ iconName='mailbox-filled'
845
+ >
846
+ <TextWithLinks as='p'>{i18n.t('auth.invite_required_msg', { emailAddress: supportEmail })}</TextWithLinks>
847
+ </ModalSimpleContent>
848
+ );
849
+ }
850
+
851
+ /**
852
+ * Sign up; success
853
+ */
854
+
855
+ interface SignUpSuccessProps extends Omit<AuthFormProps, 'setAuthIface'> {
856
+ signUpToken: string;
857
+ }
858
+
859
+ function SignUpSuccess(p: SignUpSuccessProps) {
860
+ const { authRoutesMap, returnTo } = p;
861
+
862
+ return (
863
+ <ModalSimpleContent
864
+ title={i18n.t('auth.account_created')}
865
+ iconName='circle-check'
866
+ className='px_df pt_md'
867
+ >
868
+ <TextWithLinks as='p'>{i18n.t('auth.account_created_msg')}</TextWithLinks>
869
+
870
+ <FullWidthButton
871
+ to={getAuthRoute('signin', authRoutesMap, getAuthReturnQuery(returnTo))}
872
+ preset='bg_primary'
873
+ className='mt_lg shadow'
874
+ replace
875
+ >
876
+ {i18n.t('auth.continue_to_login')}
877
+ </FullWidthButton>
878
+ </ModalSimpleContent>
879
+ );
880
+ }
881
+
882
+ /**
883
+ * Sign up form
884
+ */
885
+
886
+ type SignUpIface = 'INVITATION_REQUIRED' | null;
887
+
888
+ export function SignUpForm(p: Omit<AuthFormProps, 'setAuthIface'>) {
889
+ const [signUpToken, setSignUpToken] = useState<string | null>(null);
890
+ const [signUpIface, setAuthIface] = useState<SignUpIface>(null);
891
+
892
+ if (signUpToken) {
893
+ return (
894
+ <SignUpSuccess
895
+ {...p}
896
+ signUpToken={signUpToken}
897
+ />
898
+ );
899
+ }
900
+
901
+ switch (signUpIface) {
902
+ case 'INVITATION_REQUIRED':
903
+ return <SignUpInviteRequired {...p} />;
904
+ default:
905
+ }
906
+
907
+ return (
908
+ <SignUpMain
909
+ {...p}
910
+ setAuthIface={setAuthIface}
911
+ setSignUpToken={setSignUpToken}
912
+ />
913
+ );
914
+ }