@jsb188/auth-web 1.1.3 → 1.1.10

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,638 +0,0 @@
1
- import { SUPPORT_EMAILS } from '@jsb188/app/constants/app';
2
- import i18n from '@jsb188/app/i18n';
3
- import { cn } from '@jsb188/app/utils/string';
4
- import { composeSignUp, useEmailVerification, useRequestTokenizedEmail, useSignIn } from '@jsb188/graphql/hooks/use-auth-mtn';
5
- import { FormBreak, Input } from '@jsb188/react-web/modules/Form';
6
- import SchemaForm from '@jsb188/react-web/modules/SchemaForm';
7
- import { Pill } from '@jsb188/react-web/ui/Avatar';
8
- import { FullWidthButton } from '@jsb188/react-web/ui/Button';
9
- import { ModalErrorMessage, ModalSimpleContent } from '@jsb188/react-web/ui/ModalUI';
10
- import { useModalHandlers } from '@jsb188/react/states';
11
- import { Link, useNavigate } from 'react-router';
12
- import { useState, useMemo } from 'react';
13
- import { ContinueWithApple, ContinueWithGoogle } from './OAuthButtons';
14
- import { makeRequestTokenizedEmailSchema, makeSignInSchema, makeSignUpSchema } from './schemas';
15
-
16
- /**
17
- * Page meta tags
18
- */
19
-
20
- export const meta = [{
21
- title: i18n.t('app.route_', { text: i18n.t('app.route_auth') })
22
- }];
23
-
24
- /**
25
- * Types
26
- */
27
-
28
- export type AuthScreenState = {
29
- name: 'sign_in' | 'sign_up' | 'sign_up_success' | 'reset_password' | 'resend_verification_email' | 'reset_password_completed';
30
- [namespace: string]: any;
31
- };
32
-
33
- interface AuthFormProps {
34
- appNamespace: string;
35
- initialError: any;
36
- initialFormData: any;
37
- onError?: (error: any) => void;
38
- }
39
-
40
- interface AuthFormIfaceProps extends AuthFormProps {
41
- doNotAlertErrors: boolean;
42
- screen: AuthScreenState;
43
- setScreen: (screen: AuthScreenState) => void;
44
- }
45
-
46
- /**
47
- * Sign in form
48
- */
49
-
50
- function SignInForm(p: any) {
51
- const { initialError, initialFormData, screen, setScreen } = p;
52
- const navigate = useNavigate();
53
- const [waitingForPostRequest, setWaitingForPostRequest] = useState(false);
54
- const signInSchema = useMemo(makeSignInSchema, []);
55
- const { saving, checkUsernameOrEmail, dataForSchema, setDataForSchema, error, setError, resetErrors } = useSignIn({
56
- initialError,
57
- initialFormData
58
- });
59
- const hidePassword = dataForSchema.hidePassword;
60
-
61
- const onFormValuesChange = (formValues: any, _currentValues: any, setFormValues: (val: any) => void) => {
62
- const hasInput = !!formValues.identifier?.trim();
63
- if (
64
- !hidePassword &&
65
- formValues.identifier !== dataForSchema.lastIdentifier
66
- ) {
67
- setDataForSchema({
68
- ...dataForSchema,
69
- hasInput,
70
- lastIdentifier: '',
71
- hidePassword: true,
72
- });
73
-
74
- setFormValues({
75
- ...formValues,
76
- password: '',
77
- });
78
- } else if (hasInput !== dataForSchema.hasInput) {
79
- setDataForSchema({
80
- ...dataForSchema,
81
- hasInput,
82
- });
83
- }
84
- };
85
-
86
- async function onSubmit(formValues: any, _currentValues: any, setFormValues: any) {
87
- const identifier = formValues.identifier?.trim();
88
- if (hidePassword) {
89
- const { checkUsernameOrEmail: result } = await checkUsernameOrEmail({
90
- variables: {
91
- usernameOrEmail: identifier,
92
- authCheck: true,
93
- },
94
- });
95
-
96
- switch (result?.type) {
97
- case 'PHONE': {
98
- if (!result.taken) {
99
- setError({
100
- message: i18n.t('auth.no_account_with_phone'),
101
- });
102
- return false;
103
- }
104
- // Do this if you want to redirect to sign up
105
- // setScreen({
106
- // name: 'sign_up',
107
- // email: result.value,
108
- // });
109
- // return false;
110
- } break;
111
- case 'EMAIL': {
112
- if (!result.taken) {
113
- setError({
114
- message: i18n.t('auth.no_account_with_email'),
115
- });
116
- // Do this if you want to redirect to sign up
117
- // setScreen({
118
- // name: 'sign_up',
119
- // email: result.value,
120
- // });
121
- return false;
122
- }
123
- } break;
124
- default:
125
- // This auth type is not supported
126
- console.dev('Unknown auth type:', result);
127
-
128
- setError({
129
- message: i18n.t(result?.type ? 'auth.not_valid_email_or_phone' : (error?.message || i18n.t('error.unknown_error'))),
130
- });
131
- return false;
132
- }
133
-
134
- setDataForSchema({
135
- ...dataForSchema,
136
- lastIdentifier: identifier || '',
137
- hidePassword: !result?.taken,
138
- });
139
-
140
- setFormValues({
141
- ...formValues,
142
- identifier: identifier || '',
143
- });
144
- } else if (formValues.password && identifier) {
145
-
146
- // const signInResult = await signIn({
147
- // variables: {
148
- // identifier,
149
- // password: formValues.password,
150
- // },
151
- // });
152
-
153
- // const { signIn: result, aborted } = signInResult;
154
- // if (aborted) {
155
- // // Unmounted or canceled
156
- // return;
157
- // }
158
-
159
- // if (!result?.user?.activated && result?.user?.email?.verified === false) {
160
- // setScreen({
161
- // name: 'sign_up_success',
162
- // result: {
163
- // token: result.token,
164
- // userId: result.user.id,
165
- // username: result.user.username,
166
- // emailAddress: result.user.email.address,
167
- // },
168
- // });
169
- // } else if (result?.token) {
170
- // onFinishSignIn();
171
- // /// Can't do this because app state will be lost
172
- // // globalThis.location.replace(`/${result.user.id}`);
173
- // }
174
-
175
- setWaitingForPostRequest(true);
176
- return true; // "Do" post form
177
- }
178
-
179
- return false; // Do not post form
180
- }
181
-
182
- const showSignUpLink = hidePassword && !error;
183
- const onFinishSignIn = (token: string) => {
184
- navigate('/auth/success?token=' + token);
185
- };
186
-
187
- return (
188
- <>
189
- <ContinueWithGoogle screen={screen} onFinishSignIn={onFinishSignIn} />
190
- <ContinueWithApple screen={screen} onFinishSignIn={onFinishSignIn} />
191
-
192
- <FormBreak className='mt_md'>
193
- {i18n.t('form.or')}
194
- </FormBreak>
195
-
196
- <SchemaForm
197
- doNotPostForm={fv => !fv.identifier || !fv.password}
198
- httpMethod='post'
199
- actionUrl='/auth'
200
- className='py_df'
201
- buttonClassName='mt_sm'
202
- currentData={{ identifier: screen?.identifier || '' }}
203
- saving={saving || waitingForPostRequest}
204
- schema={signInSchema}
205
- dataForSchema={dataForSchema}
206
- onSubmit={onSubmit}
207
- onFormValuesChange={onFormValuesChange}
208
- >
209
- {!error ? null : (
210
- <ModalErrorMessage
211
- error={error}
212
- resetErrors={resetErrors}
213
- // className='mt_sm'
214
- >
215
- {error.errorCode === '20049' && (
216
- <p>
217
- <button
218
- className='link text cl_main mr_xs'
219
- onClick={() => {
220
- resetErrors(); // Must be done before setScreen() due to mounted check
221
- setScreen({ name: 'resend_verification_email' });
222
- }}
223
- >
224
- {i18n.t('form.click_here')}
225
- </button>
226
- {i18n.t('auth._send_new_verification')}
227
- </p>
228
- )}
229
- </ModalErrorMessage>
230
- )}
231
- </SchemaForm>
232
-
233
- <div className='a_c'>
234
- <a
235
- role='button'
236
- onClick={() => {
237
- resetErrors(); // Must be done before setScreen() due to mounted check
238
- setScreen({ name: hidePassword ? 'sign_up' : 'reset_password' });
239
- }}
240
- className={cn('text ft_sm', showSignUpLink ? 'cl_md' : 'cl_secondary')}
241
- >
242
- {i18n.t(showSignUpLink ? 'auth.signup_email' : 'auth.forgot_password_')}
243
- </a>
244
- </div>
245
- </>
246
- );
247
- }
248
-
249
- /**
250
- * Forgot password form
251
- */
252
-
253
- function RequestTokenizedEmailForm(p: any) {
254
-
255
- const { requestType, screen, setScreen, resetErrors } = p;
256
- const [error, setError] = useState<any>(null);
257
- const tokenizedEmailSchema = useMemo(makeRequestTokenizedEmailSchema, []);
258
-
259
- // Data hook
260
-
261
- const { requestTokenizedEmail, saving } = useRequestTokenizedEmail({
262
- onCompleted: (data: any, _: any, variables: any) => {
263
- const success = data?.requestTokenizedEmail;
264
- if (success) {
265
- setScreen({
266
- name: 'reset_password_completed' ,
267
- emailAddress: variables?.email,
268
- });
269
- }
270
- },
271
- onError: (err: any) => {
272
- setError(err);
273
- }
274
- });
275
-
276
- const onSubmit = (fv: any) => {
277
- requestTokenizedEmail({
278
- variables: {
279
- ...fv,
280
- requestType
281
- }
282
- });
283
- };
284
-
285
- let instructionText;
286
- switch (requestType) {
287
- case 'PASSWORD_RESET':
288
- instructionText = i18n.t('auth.request_reset_password_instr');
289
- break;
290
- case 'EMAIL_VERIFICATION':
291
- instructionText = i18n.t('auth.resend_verification_instr');
292
- break;
293
- default:
294
- }
295
-
296
- return (
297
- <SchemaForm
298
- className='pb_df'
299
- saving={saving}
300
- schema={tokenizedEmailSchema}
301
- currentData={{ email: screen?.email || '' }}
302
- onError={setError}
303
- onSubmit={onSubmit}
304
- buttonText={i18n.t('form.continue')}
305
- >
306
- {!error ? null : (
307
- <ModalErrorMessage
308
- error={error}
309
- resetErrors={resetErrors}
310
- />
311
- )}
312
-
313
- <p className={error ? 'pt_3' : undefined}>
314
- {instructionText}
315
- </p>
316
- </SchemaForm>
317
- );
318
- }
319
-
320
- /**
321
- * Request for password reset is completed
322
- */
323
-
324
- function ResetPasswordCompleted(p: AuthFormIfaceProps) {
325
- const { appNamespace, screen } = p;
326
- const emailAddress = screen.emailAddress;
327
- const supportEmail = SUPPORT_EMAILS[appNamespace] || SUPPORT_EMAILS.default;
328
-
329
- return (
330
- <ModalSimpleContent
331
- title={i18n.t('auth.email_sent')}
332
- iconName='circle-check-filled'
333
- >
334
- <p>
335
- {i18n.t('auth.reset_password_requested_1')}
336
- <strong>{emailAddress || '?'}</strong>
337
- {i18n.t('auth.reset_password_requested_2')}
338
- </p>
339
- <p>
340
- {i18n.t('auth.if_need_more_help')}
341
- <a href={`mailto:${supportEmail}`}>{supportEmail}</a>
342
- .
343
- </p>
344
- </ModalSimpleContent>
345
- );
346
- }
347
-
348
- /**
349
- * Sign up form
350
- */
351
-
352
- function SignUpForm_(p: any) {
353
- const { screen, setScreen, signUp, saving, error, setError, resetErrors } = p;
354
- const signUpSchema = useMemo(makeSignUpSchema, []);
355
-
356
- const onSubmit = async(formValues: any) => {
357
- const variables = {
358
- displayName: formValues.displayName,
359
- email: formValues.email,
360
- password: formValues.password,
361
- username: formValues.username,
362
- };
363
-
364
- const { signUp: result } = await signUp({ variables });
365
-
366
- if (result?.token) {
367
- setScreen({
368
- name: 'sign_up_success',
369
- result,
370
- });
371
- } else if (result) {
372
- // Has result but no token
373
- setError({
374
- message: i18n.t('error.unknown_error'),
375
- });
376
- }
377
- };
378
-
379
- return (
380
- <>
381
- <SchemaForm
382
- className='pb_df'
383
- saving={saving}
384
- schema={signUpSchema}
385
- currentData={{ email: screen?.email || '' }}
386
- onError={setError}
387
- onSubmit={onSubmit}
388
- buttonText={i18n.t('auth.agree_and_continue')}
389
- FooterComponent={
390
- <div className='ft_xs mt_sm cl_md'>
391
- {i18n.t('auth.sign_up_notice_1')}
392
- <Link to='/tos' className='u'>
393
- {i18n.t('app.tos')}
394
- </Link>
395
- {i18n.t('auth.sign_up_notice_2')}
396
- <Link to='/privacy' className='u'>
397
- {i18n.t('app.privacy')}
398
- </Link>
399
- .
400
- </div>
401
- }
402
- >
403
- {!error ? null : (
404
- <ModalErrorMessage
405
- error={error}
406
- resetErrors={resetErrors}
407
- // className='mt_sm'
408
- />
409
- )}
410
- </SchemaForm>
411
-
412
- <div className='a_c h_center'>
413
- <a
414
- role='button'
415
- onClick={() => setScreen({ name: 'sign_in' })}
416
- className='text ft_sm'
417
- >
418
- {i18n.t('auth.signup_using_other')}
419
- </a>
420
- </div>
421
- </>
422
- );
423
- }
424
-
425
- const SignUpForm = composeSignUp(SignUpForm_);
426
-
427
- /**
428
- * Sign up success
429
- */
430
-
431
- function SignUpSuccess(p: any) {
432
- const { screen, setScreen } = p;
433
- const result = screen?.result;
434
- const { token, userId, username, emailAddress } = result;
435
-
436
- const { openModalPopUp } = useModalHandlers();
437
- const [successForm, setSuccessForm] = useState({ emailAddress, change: false });
438
- const isChangeEmail = successForm.change;
439
- const { emailVerificationStatus, sendEmailVerification, sending, verifying } = useEmailVerification({}, openModalPopUp);
440
- const saving = sending || verifying;
441
-
442
- // Click continue and check email verification status
443
-
444
- const onClickContinue = async () => {
445
- const { emailVerificationStatus: result } = await emailVerificationStatus({
446
- variables: {
447
- token,
448
- },
449
- });
450
-
451
- if (result) {
452
- setScreen({
453
- name: 'sign_in',
454
- identifier: emailAddress,
455
- });
456
- } else if (result === false) {
457
- // If null. that's an error, and the alertSignal will handle it
458
- openModalPopUp({
459
- name: 'not_verified_email',
460
- });
461
- }
462
- };
463
-
464
- // Change/Re-send verification e-mail
465
-
466
- const onToggleResend = () => {
467
- setSuccessForm({ ...successForm, change: !successForm.change });
468
- };
469
-
470
- const onResendEmailVerification = async () => {
471
- const { sendEmailVerification: resendResult } = await sendEmailVerification(
472
- {
473
- variables: {
474
- email: successForm.emailAddress,
475
- userId,
476
- },
477
- },
478
- );
479
-
480
- if (resendResult) {
481
- setScreen({
482
- name: 'sign_up_success',
483
- result: resendResult,
484
- });
485
-
486
- setSuccessForm({ emailAddress: resendResult.emailAddress, change: false });
487
- }
488
- };
489
-
490
- if (isChangeEmail) {
491
- // Change email or re-send verification e-mail
492
- return (
493
- <div className='v_center p_md a_c'>
494
- <h1>
495
- {i18n.t('auth.verify_account')}
496
- </h1>
497
- <p>
498
- {i18n.t('auth.verify_email_msg')}
499
- </p>
500
- <Input
501
- name='change_email_address'
502
- className='mt_df mb_sm fs a_c'
503
- type='email'
504
- value={successForm.emailAddress}
505
- onChange={(e) => setSuccessForm({ ...successForm, emailAddress: e.target.value })}
506
- />
507
- <FullWidthButton
508
- loading={saving}
509
- disabled={!successForm.emailAddress?.trim()}
510
- preset='bg_main'
511
- onClick={onResendEmailVerification}
512
- className='mb_sm'
513
- >
514
- {i18n.t('auth.resend_verification')}
515
- </FullWidthButton>
516
-
517
- <a
518
- role='button'
519
- onClick={() => setScreen({ name: 'sign_in' })}
520
- className='text ft_sm'
521
- >
522
- {i18n.t('auth.signup_using_other')}
523
- </a>
524
- </div>
525
- );
526
- }
527
-
528
- return (
529
- <div className='v_center p_md a_c'>
530
- <h1>
531
- {i18n.t('auth.user_created')}
532
- </h1>
533
- <p>
534
- {i18n.t('auth.check_email_1')}
535
- <strong>{emailAddress}</strong>
536
- {i18n.t('auth.check_email_2')}
537
- </p>
538
- <p>
539
- {i18n.t('auth.check_email_3')}
540
- <strong>{`@${username}`}</strong>
541
- {i18n.t('auth.check_email_4')}
542
- </p>
543
- <Pill
544
- loading={saving}
545
- className='mt_md mb_df bg_primary'
546
- onClick={onClickContinue}
547
- >
548
- {i18n.t('form.continue')}
549
- </Pill>
550
-
551
- <a
552
- role='button'
553
- onClick={onToggleResend}
554
- className='text ft_sm'
555
- >
556
- {i18n.t('auth.resend_change_verification')}
557
- </a>
558
- </div>
559
- );
560
- }
561
-
562
- /**
563
- * Auth interfaces
564
- */
565
-
566
- function AuthFormIface(p: AuthFormIfaceProps) {
567
- const screenName = p.screen.name;
568
- switch (screenName) {
569
- case 'sign_in':
570
- return <SignInForm {...p} />;
571
- case 'reset_password':
572
- case 'resend_verification_email':
573
- return <RequestTokenizedEmailForm
574
- {...p}
575
- requestType={screenName === 'reset_password' ? 'PASSWORD_RESET' : 'EMAIL_VERIFICATION'}
576
- />;
577
- case 'reset_password_completed':
578
- return <ResetPasswordCompleted {...p} />;
579
- case 'sign_up':
580
- return <SignUpForm {...p} />;
581
- case 'sign_up_success':
582
- return <SignUpSuccess {...p} doNotAlertErrors={false} />;
583
- default:
584
- }
585
- return null;
586
- }
587
-
588
- /**
589
- * Auth form
590
- */
591
-
592
- export function AuthForm(p: AuthFormProps) {
593
- const { appNamespace, initialError, initialFormData } = p;
594
- const [screen, setScreen] = useState({
595
- name: 'sign_in',
596
- identifier: initialFormData?.identifier
597
- } as AuthScreenState);
598
-
599
- let title;
600
- switch (screen.name) {
601
- case 'sign_in':
602
- title = i18n.t('auth.welcome_back');
603
- break;
604
- case 'sign_up':
605
- case 'sign_up_success':
606
- title = i18n.t('auth.create_account');
607
- break;
608
- case 'reset_password':
609
- case 'reset_password_completed':
610
- title = i18n.t('auth.reset_password');
611
- break;
612
- case 'resend_verification_email':
613
- title = i18n.t('auth.verify_your_acc');
614
- break;
615
- default:
616
- }
617
-
618
- return (
619
- <div className='cw xxs'>
620
- <div className='a_c -mb_1 anim_lift_center on_mount spd_2'>
621
- <h1 className='ft_md ls_2 lh_1 p_n cl_secondary op_50 visible'>
622
- {title}
623
- </h1>
624
- </div>
625
- <div className='bg py_lg px_md r_df rel z2 shadow_bg_alt_lg'>
626
- <AuthFormIface
627
- appNamespace={appNamespace}
628
- doNotAlertErrors
629
- initialError={initialError}
630
- initialFormData={initialFormData}
631
- // isModal={isModal}
632
- screen={screen}
633
- setScreen={setScreen}
634
- />
635
- </div>
636
- </div>
637
- );
638
- }