@jsb188/auth-web 1.1.3

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.
package/package.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "@jsb188/auth-web",
3
+ "version": "1.1.3",
4
+ "description": "Authentication module for web.",
5
+ "license": "ISC",
6
+ "author": "jsb188",
7
+ "type": "module",
8
+ "main": "src/main.ts",
9
+ "peerDependencies": {
10
+ "@jsb188/app": "1.1.3",
11
+ "@jsb188/react-web": "1.1.3",
12
+ "react-router": "^7.6.2",
13
+ "jotai": "^2.12.5",
14
+ "react": "^19.1.0"
15
+ },
16
+ "scripts": {
17
+ "test": "echo \"Error: no test specified\" && exit 1",
18
+ "build": "tsc"
19
+ }
20
+ }
@@ -0,0 +1,174 @@
1
+ import { getENVVariable } from '@jsb188/app';
2
+ import { getTimeBasedUnique } from '@jsb188/app/utils/string';
3
+ import { useMutation } from '@jsb188/graphql/client';
4
+ import { signInWithGoogleMtn } from '@jsb188/graphql/mutations/accountAuth';
5
+ import type { OnErrorGQLFn } from '@jsb188/graphql/types.d';
6
+ import { AppContext, onAccountLogin, useOpenModalPopUp } from '@jsb188/react/states';
7
+ import { useCallback, useContext, useEffect, useRef, useState } from 'react';
8
+
9
+ /**
10
+ * Types
11
+ */
12
+
13
+ interface ContinueWithGoogleParams {
14
+ doNotAlertErrors?: boolean;
15
+ onFinishSignIn: (token: string) => void;
16
+ }
17
+
18
+ interface GoogleLoginHookParams extends ContinueWithGoogleParams {
19
+ scriptLoaded: boolean;
20
+ scope?: string;
21
+ onError?: OnErrorGQLFn;
22
+ onNonOAuthError?: (err: any) => void;
23
+ overrideScope?: boolean;
24
+ state?: string;
25
+ }
26
+
27
+ /**
28
+ * Google OAuth login
29
+ */
30
+
31
+ function useGoogleLogin(p: GoogleLoginHookParams) {
32
+ const {
33
+ scriptLoaded,
34
+ scope = '',
35
+ onError,
36
+ onNonOAuthError,
37
+ onFinishSignIn,
38
+ overrideScope,
39
+ state,
40
+ doNotAlertErrors,
41
+ ...props
42
+ } = p;
43
+
44
+ const { dispatchApp } = useContext(AppContext);
45
+ const openModalPopUp = useOpenModalPopUp();
46
+ const [signInWithGoogle, { saving }] = useMutation(
47
+ signInWithGoogleMtn,
48
+ {
49
+ openModalPopUp: doNotAlertErrors ? null : openModalPopUp,
50
+ onError,
51
+ onCompleted: (data) => {
52
+ const result = data?.signInWithGoogle;
53
+ if (result?.token && result.user?.id) {
54
+ onAccountLogin(result, dispatchApp);
55
+ onFinishSignIn(result?.token);
56
+ }
57
+ },
58
+ },
59
+ );
60
+
61
+ const clientRef = useRef<any>();
62
+
63
+ const onErrorRef = useRef(onError);
64
+ onErrorRef.current = onError;
65
+
66
+ const onNonOAuthErrorRef = useRef(onNonOAuthError);
67
+ onNonOAuthErrorRef.current = onNonOAuthError;
68
+
69
+ useEffect(() => {
70
+ if (scriptLoaded) {
71
+ // @ts-expect-error - If using this package, it is expected that you install your own Google OAuth script
72
+ const client = globalThis.google?.accounts?.oauth2.initTokenClient({
73
+ client_id: getENVVariable('GOOGLE_OAUTH'),
74
+ scope: overrideScope ? scope : `openid profile email ${scope}`,
75
+ callback: (response: any) => {
76
+ if (response.error) {
77
+ return onErrorRef.current?.(response, null);
78
+ }
79
+
80
+ const { access_token: oauthToken } = response;
81
+ signInWithGoogle({
82
+ variables: {
83
+ oauthToken,
84
+ },
85
+ });
86
+ },
87
+ error_callback: (nonOAuthError: any) => {
88
+ onNonOAuthErrorRef.current?.(nonOAuthError);
89
+ },
90
+ state,
91
+ ...props,
92
+ });
93
+
94
+ clientRef.current = client;
95
+ }
96
+ }, [scriptLoaded, scope, state]);
97
+
98
+ const onInitiateGoogleSignIn = useCallback((overrideConfig?: object) => {
99
+ clientRef.current?.requestAccessToken(overrideConfig);
100
+ }, []);
101
+
102
+ return {
103
+ onInitiateGoogleSignIn,
104
+ waitingForOAuth: saving,
105
+ };
106
+ }
107
+
108
+ /**
109
+ * Web sign in with Google
110
+ */
111
+
112
+ export function useContinueWithGoogle(params: ContinueWithGoogleParams) {
113
+ const { doNotAlertErrors, onFinishSignIn } = params;
114
+ const [scriptLoaded, setScriptLoaded] = useState(false);
115
+
116
+ useEffect(() => {
117
+ const scriptTag = document.createElement('script');
118
+ scriptTag.src = 'https://accounts.google.com/gsi/client';
119
+ scriptTag.async = true;
120
+ scriptTag.defer = true;
121
+ // scriptTag.nonce = nonce;
122
+
123
+ scriptTag.onload = () => {
124
+ setScriptLoaded(true);
125
+ };
126
+ scriptTag.onerror = () => {
127
+ setScriptLoaded(false);
128
+ };
129
+
130
+ document.body.appendChild(scriptTag);
131
+ return () => {
132
+ document.body.removeChild(scriptTag);
133
+ };
134
+ }, []);
135
+
136
+ const { onInitiateGoogleSignIn, waitingForOAuth } = useGoogleLogin({
137
+ doNotAlertErrors,
138
+ onFinishSignIn,
139
+ scriptLoaded,
140
+ onError: (err: any) => {
141
+ console.log('ERROR', err);
142
+ },
143
+ });
144
+
145
+ return {
146
+ waitingForOAuth,
147
+ onInitiateGoogleSignIn,
148
+ scriptLoaded
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Web sign in with Apple
154
+ */
155
+
156
+ export function useContinueWithApple() {
157
+
158
+ const onInitiateAppleSignIn = () => {
159
+ globalThis.location.href = (
160
+ 'https://appleid.apple.com/auth/authorize' +
161
+ '?client_id=' + getENVVariable('APPLE_APP_ID') +
162
+ '&redirect_uri=' + encodeURIComponent(getENVVariable('APP_URL') + 'auth/apple') +
163
+ '&response_type=' + encodeURIComponent('code id_token') +
164
+ '&state=' + getTimeBasedUnique() +
165
+ '&scope=' + encodeURIComponent('email name') +
166
+ '&response_mode=form_post'
167
+ // '&frame_id'=36394414-f7d7-4021-8f98-64e7be74e283&m=11&v=1.5.5'
168
+ );
169
+ };
170
+
171
+ return {
172
+ onInitiateAppleSignIn
173
+ };
174
+ }
package/src/main.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './modules/AuthForm';
2
+ export * from './modules/AuthGate';
3
+ export * from './modules/schemas';
@@ -0,0 +1,638 @@
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
+ }
@@ -0,0 +1,71 @@
1
+ import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app.d';
2
+ import type { ErrorMessageProps } from '@jsb188/react-web/ui/Layout';
3
+ import { FullPageLayout, ErrorMessage } from '@jsb188/react-web/ui/Layout';
4
+ import { BigLoading } from '@jsb188/react-web/ui/Loading';
5
+ import { useIsLoggedIn } from '@jsb188/react/states';
6
+ import i18n from '@jsb188/app/i18n';
7
+
8
+ /**
9
+ * Loading or Error interface
10
+ */
11
+
12
+ interface AuthGateProps extends ErrorMessageProps {
13
+ children: React.ReactNode;
14
+ connectedToServer?: boolean;
15
+ notReady?: boolean;
16
+ loading?: boolean;
17
+ loadingMessage?: string;
18
+ defaultErrorMessage?: string;
19
+ error?: ServerErrorObj | SimpleErrorType | null;
20
+ }
21
+
22
+ export function AuthGate(p: AuthGateProps) {
23
+ const { notReady, loading, loadingMessage, defaultErrorMessage, error, children, connectedToServer, ...other } = p;
24
+ const isLoggedIn = useIsLoggedIn();
25
+ const isNetworkError = (error as ServerErrorObj)?.errorCode === 'network_error';
26
+
27
+ if (isLoggedIn && !notReady) {
28
+ return children;
29
+ }
30
+
31
+ if (notReady || (loading && !isLoggedIn)) {
32
+ return <FullPageLayout>
33
+ <BigLoading color='active' />
34
+ {loadingMessage && (
35
+ <p className='mt_df cl_md'>
36
+ {loadingMessage}
37
+ </p>
38
+ )}
39
+ </FullPageLayout>;
40
+ }
41
+
42
+ if (!isLoggedIn && !isNetworkError) {
43
+ // Gota do log in form here
44
+ // Gota do log in form here
45
+ // Gota do log in form here
46
+ // Gota do log in form here
47
+ }
48
+
49
+ // IMPORTANT NOTE:
50
+ // {connectedToServer} is currently always true, passed down from graphql hooks.
51
+ // This is a placeholder logic, and must properly return a real network state in the future.
52
+
53
+ let errorMessage;
54
+ if (error?.message) {
55
+ errorMessage = error.message;
56
+ } else if (isNetworkError || !connectedToServer) {
57
+ errorMessage = i18n.t('error.network_error');
58
+ } else if (!isLoggedIn) {
59
+ errorMessage = i18n.t('error.20019');
60
+ } else {
61
+ errorMessage = defaultErrorMessage;
62
+ }
63
+
64
+ return <FullPageLayout>
65
+ <ErrorMessage
66
+ message={errorMessage}
67
+ {...error}
68
+ {...other}
69
+ />
70
+ </FullPageLayout>;
71
+ }
@@ -0,0 +1,105 @@
1
+ import { useCallback, useEffect, useRef } from 'react';
2
+ import { getTimeBasedUnique } from '@jsb188/app/utils/string';
3
+ import { getENVVariable } from '@jsb188/app';
4
+
5
+ /**
6
+ * Types
7
+ */
8
+
9
+ interface AppleLoginProps {
10
+ scriptLoaded: boolean;
11
+ scope?: string;
12
+ onSuccess?: (res: any) => void;
13
+ onError?: (err: any) => void;
14
+ onNonOAuthError?: (err: any) => void;
15
+ overrideScope?: boolean;
16
+ state?: string;
17
+ }
18
+
19
+ /**
20
+ * Apple OAuth login
21
+ */
22
+
23
+ function useAppleLogin(p: AppleLoginProps) {
24
+ const {
25
+ scriptLoaded,
26
+ scope = '',
27
+ onSuccess,
28
+ onError,
29
+ onNonOAuthError,
30
+ overrideScope,
31
+ state,
32
+ ...props
33
+ } = p;
34
+
35
+ const clientRef = useRef<any>();
36
+
37
+ const onSuccessRef = useRef(onSuccess);
38
+ onSuccessRef.current = onSuccess;
39
+
40
+ const onErrorRef = useRef(onError);
41
+ onErrorRef.current = onError;
42
+
43
+ const onNonOAuthErrorRef = useRef(onNonOAuthError);
44
+ onNonOAuthErrorRef.current = onNonOAuthError;
45
+
46
+ useEffect(() => {
47
+ if (scriptLoaded) {
48
+ const client = globalThis.google?.accounts?.oauth2.initTokenClient({
49
+ client_id: getENVVariable('GOOGLE_OAUTH'),
50
+ scope: overrideScope ? scope : `openid profile email ${scope}`,
51
+ callback: (response) => {
52
+ if (response.error) {
53
+ return onErrorRef.current?.(response);
54
+ }
55
+ onSuccessRef.current?.(response as any);
56
+ },
57
+ error_callback: (nonOAuthError) => {
58
+ onNonOAuthErrorRef.current?.(nonOAuthError);
59
+ },
60
+ state,
61
+ ...props,
62
+ });
63
+
64
+ clientRef.current = client;
65
+ }
66
+ }, [scriptLoaded, scope, state]);
67
+
68
+ return useCallback((overrideConfig?: object) => {
69
+ clientRef.current?.requestAccessToken(overrideConfig);
70
+ }, []);
71
+ }
72
+
73
+ /**
74
+ * Web sign in with Apple
75
+ */
76
+
77
+ function useContinueWithApple(Cmp) {
78
+ function WebSignInWithApple(p) {
79
+
80
+ const onInitiateAppleSignIn = () => {
81
+ globalThis.location.href = (
82
+ 'https://appleid.apple.com/auth/authorize' +
83
+ '?client_id=' + getENVVariable('APPLE_APP_ID') +
84
+ '&redirect_uri=' + encodeURIComponent('https://bigplanet.ai/auth/apple') +
85
+ '&response_type=' + encodeURIComponent('code id_token') +
86
+ '&state=' + getTimeBasedUnique() +
87
+ '&scope=' + encodeURIComponent('email name') +
88
+ '&response_mode=form_post'
89
+ // '&frame_id'=36394414-f7d7-4021-8f98-64e7be74e283&m=11&v=1.5.5'
90
+ );
91
+ };
92
+
93
+ return (
94
+ <Cmp
95
+ {...p}
96
+ onInitiateAppleSignIn={onInitiateAppleSignIn}
97
+ />
98
+ );
99
+ }
100
+
101
+ // return composeSignInWithApple(WebSignInWithApple);
102
+ return WebSignInWithApple;
103
+ }
104
+
105
+ export default useContinueWithApple = useContinueWithApple;
@@ -0,0 +1,48 @@
1
+ import i18n from '@jsb188/app/i18n';
2
+ import { SpecialIcon } from '@jsb188/react-web/icons';
3
+ import { FullWidthButton } from '@jsb188/react-web/ui/Button';
4
+ import { useContinueWithGoogle, useContinueWithApple } from '../hooks/use-oauth';
5
+
6
+ /**
7
+ * Google OAuth button
8
+ */
9
+
10
+ export const ContinueWithGoogle = (p: any) => {
11
+ const { onFinishSignIn } = p;
12
+ const { onInitiateGoogleSignIn, waitingForOAuth } = useContinueWithGoogle({
13
+ onFinishSignIn
14
+ });
15
+
16
+ return (
17
+ <FullWidthButton
18
+ loading={waitingForOAuth}
19
+ onClick={onInitiateGoogleSignIn}
20
+ preset='em'
21
+ className='mb_sm'
22
+ IconComponent={SpecialIcon}
23
+ iconName='google'
24
+ >
25
+ {i18n.t('auth.continue_with_google')}
26
+ </FullWidthButton>
27
+ );
28
+ };
29
+
30
+ /**
31
+ * Apple OAuth button
32
+ */
33
+
34
+ export const ContinueWithApple = (p: any) => {
35
+ const { onInitiateAppleSignIn } = useContinueWithApple();
36
+
37
+ return (
38
+ <FullWidthButton
39
+ onClick={onInitiateAppleSignIn}
40
+ preset='em'
41
+ className='mb_sm'
42
+ iconName='brand-apple-filled'
43
+ // iconName='heart'
44
+ >
45
+ {i18n.t('auth.continue_with_apple')}
46
+ </FullWidthButton>
47
+ );
48
+ };
@@ -0,0 +1,262 @@
1
+ import i18n from '@jsb188/app/i18n';
2
+ import { isEmail, passwordStrength } from '@jsb188/app/utils/string';
3
+
4
+ /**
5
+ * Types
6
+ */
7
+
8
+ interface SignInFormType {
9
+ identifier?: string;
10
+ password?: string;
11
+ }
12
+
13
+ interface SignUpFormType {
14
+ email: string;
15
+ password: string;
16
+ passwordRepeat: string;
17
+ }
18
+
19
+ interface ForgotPasswordFormType {
20
+ email: string;
21
+ }
22
+
23
+ interface SignInDataForSchema {
24
+ hidePassword: boolean;
25
+ lastIdentifier: string;
26
+ }
27
+
28
+ /**
29
+ * Values for validation
30
+ */
31
+
32
+ const MIN_LEN_VALUES = {
33
+ password: 8,
34
+ pronouns: 20,
35
+ description: 750,
36
+ };
37
+
38
+ /**
39
+ * Rules for each field
40
+ */
41
+
42
+ const makeRules = () => ({
43
+ email: {
44
+ for: 'email',
45
+ rule: isEmail,
46
+ error: (value: string) => ({
47
+ message: i18n.t('error.msg_email_invalid', { value }),
48
+ }),
49
+ },
50
+ password: {
51
+ for: 'password',
52
+ rule: (value: string) => passwordStrength(value, MIN_LEN_VALUES.password).valid,
53
+ error: (value: string) => {
54
+ const { isLongEnough, hasLowercase, hasUppercase, hasDigit, hasSpecial } = passwordStrength(value, MIN_LEN_VALUES.password);
55
+ const errorMessages = [];
56
+
57
+ if (!isLongEnough) {
58
+ errorMessages.push(
59
+ i18n.t('error.msg_password_too_short', { length: MIN_LEN_VALUES.password }),
60
+ );
61
+ }
62
+ if (!hasLowercase) {
63
+ errorMessages.push(i18n.t('error.msg_password_lowercase'));
64
+ }
65
+ if (!hasUppercase) {
66
+ errorMessages.push(i18n.t('error.msg_password_uppercase'));
67
+ }
68
+ if (!hasDigit) {
69
+ errorMessages.push(i18n.t('error.msg_password_digit'));
70
+ }
71
+ if (!hasSpecial) {
72
+ errorMessages.push(i18n.t('error.msg_password_special'));
73
+ }
74
+
75
+ return {
76
+ message: errorMessages.length > 1 ? i18n.t('error.msg_password_insecure') : errorMessages[0],
77
+ };
78
+ },
79
+ },
80
+ passwordRepeat: {
81
+ for: 'passwordRepeat',
82
+ rule: (value: string, formValues: Partial<SignUpFormType>) => value === formValues.password,
83
+ error: {
84
+ message: i18n.t('error.msg_password_mismatch'),
85
+ },
86
+ },
87
+ });
88
+
89
+ const RULES = makeRules();
90
+
91
+ /**
92
+ * Schema; Change password
93
+ */
94
+
95
+ export const makeChangePasswordSchema = () => ({
96
+ listData: [{
97
+ __type: 'input',
98
+ hidden: (dataForSchema?: SignInDataForSchema) => !!dataForSchema?.hidePassword,
99
+ item: {
100
+ autoFocus: true,
101
+ name: 'currentPassword',
102
+ type: 'password',
103
+ label: i18n.t('user.currentPassword'),
104
+ placeholder: i18n.t('user.password_ph'),
105
+ // info: 'whatever you want',
106
+ },
107
+ }, {
108
+ __type: 'password',
109
+ item: {
110
+ name: 'password',
111
+ type: 'password',
112
+ label: i18n.t('user.newPassword'),
113
+ // placeholder: ''
114
+ // info: 'whatever you want',
115
+ },
116
+ }, {
117
+ __type: 'password',
118
+ item: {
119
+ name: 'passwordRepeat',
120
+ type: 'password',
121
+ label: i18n.t('user.newPasswordRepeat'),
122
+ },
123
+ }],
124
+ rules: [
125
+ RULES.password,
126
+ ],
127
+ });
128
+
129
+ /**
130
+ * Schema; Edit profile
131
+ */
132
+
133
+ export const makeEditProfileSchema = () => ({
134
+ listData: [{
135
+ // __type: 'input',
136
+ // item: {
137
+ // autoFocus: true,
138
+ // maxLength: MIN_LEN_VALUES.displayName,
139
+ // name: 'displayName',
140
+ // label: i18n.t('user.displayName'),
141
+ // placeholder: i18n.t('user.displayName_ph'),
142
+ // info: i18n.t('user.displayName_info'),
143
+ // autoComplete: 'off',
144
+ // },
145
+ // }, {
146
+ __type: 'input',
147
+ item: {
148
+ name: 'pronouns',
149
+ maxLength: MIN_LEN_VALUES.pronouns,
150
+ setter: (data: any) => data?.profile?.pronouns,
151
+ label: i18n.t('user.pronouns'),
152
+ placeholder: i18n.t('user.pronouns_ph'),
153
+ autoComplete: 'off',
154
+ },
155
+ }, {
156
+ __type: 'textarea',
157
+ item: {
158
+ name: 'description',
159
+ maxLength: MIN_LEN_VALUES.description,
160
+ setter: (data: any) => data?.profile?.description,
161
+ label: i18n.t('user.about'),
162
+ placeholder: i18n.t('user.about_ph'),
163
+ preset: 'in_modal',
164
+ autoComplete: 'off',
165
+ },
166
+ }],
167
+ rules: [
168
+ // RULES.displayName,
169
+ ],
170
+ });
171
+
172
+ /**
173
+ * Schema; sign in
174
+ */
175
+
176
+ export const makeSignInSchema = () => ({
177
+ listData: [{
178
+ __type: 'input',
179
+ // Can't do this because disabling the input will make post form ignore this field
180
+ // locked: ({ hidePassword, lastIdentifier }: SignInDataForSchema) => !hidePassword && !!lastIdentifier,
181
+ item: {
182
+ name: 'identifier',
183
+ allowClearIfLocked: true,
184
+ label: i18n.t('auth.login_opts_phone_email'),
185
+ placeholder: i18n.t('user.phone_ph'),
186
+ },
187
+ }, {
188
+ __type: 'password',
189
+ hidden: (dataForSchema?: SignInDataForSchema) => !!dataForSchema?.hidePassword,
190
+ autoFocus: true,
191
+ item: {
192
+ name: 'password',
193
+ type: 'password',
194
+ label: i18n.t('user.password'),
195
+ placeholder: i18n.t('user.password_ph'),
196
+ },
197
+ }],
198
+ isButtonDisabled: (formValues: SignInFormType) => {
199
+ return !formValues?.identifier?.trim();
200
+ },
201
+ });
202
+
203
+ /**
204
+ * Schema; Sign up
205
+ */
206
+
207
+ export const makeSignUpSchema = () => ({
208
+ listData: [{
209
+ __type: 'input',
210
+ item: {
211
+ name: 'email',
212
+ label: i18n.t('user.email'),
213
+ placeholder: i18n.t('user.email_ph'),
214
+ },
215
+ }, {
216
+ __type: 'password',
217
+ item: {
218
+ name: 'password',
219
+ type: 'password',
220
+ label: i18n.t('user.password'),
221
+ placeholder: i18n.t('user.password_ph'),
222
+ },
223
+ }, {
224
+ __type: 'password',
225
+ item: {
226
+ name: 'passwordRepeat',
227
+ type: 'password',
228
+ label: i18n.t('user.passwordRepeat'),
229
+ placeholder: i18n.t('user.password_ph'),
230
+ },
231
+ }],
232
+ isButtonDisabled: (formValues: Partial<SignUpFormType>) => {
233
+ return ['email', 'password', 'passwordRepeat']
234
+ .some((s) => !formValues[s]?.trim());
235
+ },
236
+ rules: [
237
+ RULES.email,
238
+ RULES.password,
239
+ RULES.passwordRepeat,
240
+ ],
241
+ });
242
+
243
+ /**
244
+ * Schema; Request a link to reset password
245
+ */
246
+
247
+ export const makeRequestTokenizedEmailSchema = () => ({
248
+ listData: [{
249
+ __type: 'input',
250
+ item: {
251
+ name: 'email',
252
+ label: i18n.t('user.email'),
253
+ placeholder: i18n.t('user.email_ph'),
254
+ },
255
+ }],
256
+ isButtonDisabled: (formValues: Partial<ForgotPasswordFormType>) => {
257
+ return !formValues.email?.trim();
258
+ },
259
+ rules: [
260
+ RULES.email,
261
+ ],
262
+ });