@jsb188/auth-web 1.1.11 → 1.1.13

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,22 +1,17 @@
1
1
  import i18n from '@jsb188/app/i18n/index.ts';
2
2
  import { useRequestChangeEmail } from '@jsb188/graphql/hooks/use-account-mtn';
3
- import { useChangeAccountPassword } from '@jsb188/graphql/hooks/use-auth-mtn';
3
+ import { useChangeAccountPassword, useRequestTokenizedEmail } from '@jsb188/graphql/hooks/use-auth-mtn';
4
+ import { AppContext } from '@jsb188/react/states';
4
5
  import { FullPageLayout } from '@jsb188/react-web/modules/layout/MainLayout';
5
- import SchemaForm from '@jsb188/react-web/modules/SchemaForm';
6
+ import SchemaForm from '@jsb188/form/libs/SchemaForm';
7
+ import { submissionResult } from '@jsb188/form/libs/validation';
6
8
  import { COMMON_ICON_NAMES } from '@jsb188/react-web/svgs/Icon';
7
9
  import { FullWidthButton } from '@jsb188/react-web/ui/Button';
8
10
  import Markdown from '@jsb188/react-web/ui/Markdown';
9
- import {
10
- ModalErrorMessage,
11
- ModalSimpleContent,
12
- } from '@jsb188/react-web/ui/ModalUI';
13
- import { AppContext } from '@jsb188/react/states';
11
+ import { ModalErrorMessage, ModalSimpleContent } from '@jsb188/react-web/ui/ModalUI';
14
12
  import { useContext, useMemo, useState } from 'react';
15
13
  import { AuthFormContainer } from './AuthFormUI';
16
- import {
17
- makeAssignPasswordSchema,
18
- makeRequestTokenizedEmailSchema,
19
- } from './schemas';
14
+ import { makeAssignPasswordSchema, makeRequestTokenizedEmailSchema } from './schemas';
20
15
 
21
16
  /**
22
17
  * Types
@@ -25,6 +20,7 @@ import {
25
20
  interface FinishedResultObj {
26
21
  hasPassword: boolean;
27
22
  email: any;
23
+ emailVerified: boolean;
28
24
  }
29
25
 
30
26
  interface RequiredAuthSwitchCaseProps {
@@ -68,45 +64,46 @@ function SetPasswordForm(p: RequiredAuthSwitchCaseProps) {
68
64
  const { identifier, setFinishedResult } = p;
69
65
  const assignPasswordSchema = useMemo(makeAssignPasswordSchema, []);
70
66
 
71
- const { changeAccountPassword, saving, error, setError, resetErrors } =
72
- useChangeAccountPassword({
73
- doNotFinishForm: true,
74
- onCompleted: (passwordChanged: boolean) => {
75
- if (passwordChanged) {
76
- setFinishedResult((fr: FinishedResultObj) => ({
77
- ...fr,
78
- hasPassword: true,
79
- }));
80
- }
81
- },
82
- });
67
+ const { changeAccountPassword, saving, error, setError, resetErrors } = useChangeAccountPassword({
68
+ doNotFinishForm: true,
69
+ onCompleted: (passwordChanged: boolean) => {
70
+ if (passwordChanged) {
71
+ setFinishedResult((fr: FinishedResultObj) => ({
72
+ ...fr,
73
+ hasPassword: true,
74
+ }));
75
+ }
76
+ },
77
+ });
83
78
 
84
- const onSubmit = (fv: any) => {
85
- changeAccountPassword({
79
+ /* Await the password mutation before completing this form step. */
80
+ const onSubmit = async (fv: { password: string; passwordRepeat: string }) => {
81
+ const result = await changeAccountPassword({
86
82
  variables: {
87
83
  currentPassword: '',
88
84
  password: fv.password,
89
85
  },
90
86
  });
87
+ return submissionResult(result);
91
88
  };
92
89
 
93
90
  return (
94
91
  <>
95
- <p className="a_c mx_df mb_df -mt_5 pb_xs">
96
- {i18n.t('auth.add_password_sign_in_msg', { identifier })}
97
- </p>
92
+ <p className="a_c mx_df mb_df -mt_5 pb_xs">{i18n.t('auth.add_password_sign_in_msg', { identifier })}</p>
98
93
 
99
94
  <SchemaForm
100
95
  className="pb_df fs"
101
- saving={saving}
102
- schema={assignPasswordSchema}
103
- // currentData={{}}
96
+ busy={saving}
97
+ definition={assignPasswordSchema}
104
98
  onError={setError}
105
99
  onSubmit={onSubmit}
106
100
  buttonText={i18n.t('auth.add_password')}
107
101
  >
108
102
  {!error ? null : (
109
- <ModalErrorMessage error={error} resetErrors={resetErrors} />
103
+ <ModalErrorMessage
104
+ error={error}
105
+ resetErrors={resetErrors}
106
+ />
110
107
  )}
111
108
  </SchemaForm>
112
109
  </>
@@ -118,25 +115,59 @@ function SetPasswordForm(p: RequiredAuthSwitchCaseProps) {
118
115
  */
119
116
 
120
117
  function SetEmailForm(p: RequiredAuthSwitchCaseProps) {
121
- const { identifier } = p;
118
+ const { finishedResult, identifier } = p;
122
119
  const [waitingForVerification, setWaitingForVerification] = useState(false);
123
120
  const assignPasswordSchema = useMemo(makeRequestTokenizedEmailSchema, []);
121
+ const existingEmailAddress = finishedResult.email?.address || '';
122
+ const currentData = useMemo(() => ({ email: existingEmailAddress }), [existingEmailAddress]);
123
+ const requiresExistingEmailVerification = !!existingEmailAddress && !finishedResult.emailVerified;
124
124
 
125
- const { requestChangeEmail, error, setError, resetErrors, saving } =
126
- useRequestChangeEmail({
127
- onCompleted: (data: any) => {
128
- if (data.requestChangeEmail) {
129
- setWaitingForVerification(true);
130
- }
131
- },
132
- });
125
+ /*
126
+ * Show the check-email state after either email request succeeds.
127
+ */
128
+ const onEmailRequested = (result: any) => {
129
+ if (result?.requestChangeEmail || result?.requestTokenizedEmail) {
130
+ setWaitingForVerification(true);
131
+ }
132
+ };
133
133
 
134
- const onSubmit = (fv: any) => {
135
- requestChangeEmail({
134
+ const changeEmail = useRequestChangeEmail();
135
+ const verifyEmail = useRequestTokenizedEmail();
136
+ const error = changeEmail.error || verifyEmail.error;
137
+ const saving = changeEmail.saving || verifyEmail.saving;
138
+
139
+ /*
140
+ * Clear errors from both possible email-request mutations.
141
+ */
142
+ const resetErrors = () => {
143
+ changeEmail.resetErrors();
144
+ verifyEmail.resetErrors();
145
+ };
146
+
147
+ /*
148
+ * Send a verification link for the current address, or a change-email link
149
+ * when the user supplies a different address.
150
+ */
151
+ const onSubmit = async (fv: { email: string }) => {
152
+ const emailAddress = fv.email.trim();
153
+ if (emailAddress.toLowerCase() === existingEmailAddress.trim().toLowerCase()) {
154
+ const result = await verifyEmail.requestTokenizedEmail({
155
+ variables: {
156
+ email: emailAddress,
157
+ requestType: 'EMAIL_VERIFICATION',
158
+ },
159
+ });
160
+ onEmailRequested(result);
161
+ return submissionResult(result);
162
+ }
163
+
164
+ const result = await changeEmail.requestChangeEmail({
136
165
  variables: {
137
- emailAddress: fv.email,
166
+ emailAddress,
138
167
  },
139
168
  });
169
+ onEmailRequested(result);
170
+ return submissionResult(result);
140
171
  };
141
172
 
142
173
  if (waitingForVerification) {
@@ -153,20 +184,25 @@ function SetEmailForm(p: RequiredAuthSwitchCaseProps) {
153
184
  return (
154
185
  <>
155
186
  <p className="a_c mx_df mb_df -mt_5 pb_xs">
156
- {i18n.t('auth.add_email_to_login_msg', { identifier })}
187
+ {i18n.t(requiresExistingEmailVerification ? 'auth.verify_email_to_login_msg' : 'auth.add_email_to_login_msg', {
188
+ identifier,
189
+ })}
157
190
  </p>
158
191
 
159
192
  <SchemaForm
160
193
  className="pb_df fs"
161
- saving={saving}
162
- schema={assignPasswordSchema}
163
- // currentData={{}}
164
- onError={setError}
194
+ initialValues={currentData}
195
+ busy={saving}
196
+ definition={assignPasswordSchema}
197
+ onError={changeEmail.setError}
165
198
  onSubmit={onSubmit}
166
- buttonText={i18n.t('auth.add_email')}
199
+ buttonText={i18n.t(requiresExistingEmailVerification ? 'auth.resend_verification' : 'auth.add_email')}
167
200
  >
168
201
  {!error ? null : (
169
- <ModalErrorMessage error={error} resetErrors={resetErrors} />
202
+ <ModalErrorMessage
203
+ error={error}
204
+ resetErrors={resetErrors}
205
+ />
170
206
  )}
171
207
  </SchemaForm>
172
208
  </>
@@ -182,8 +218,9 @@ function RequiredAuthSwitchCase(p: RequiredAuthSwitchCaseProps) {
182
218
 
183
219
  if (!finishedResult.hasPassword) {
184
220
  return <SetPasswordForm {...p} />;
185
- } else if (!finishedResult.email) {
186
- // Keep email check last, becuase it has a verification step
221
+ }
222
+ if (!finishedResult.emailVerified) {
223
+ // Keep the email check last because it has a verification step.
187
224
  return <SetEmailForm {...p} />;
188
225
  }
189
226
 
@@ -194,20 +231,17 @@ function RequiredAuthSwitchCase(p: RequiredAuthSwitchCaseProps) {
194
231
  * Force users to provide required authentication info
195
232
  */
196
233
 
197
- export function AssignRequiredAuth(p: {
198
- hasPassword: boolean;
199
- hasEmail: boolean;
200
- }) {
234
+ export function AssignRequiredAuth(p: { hasPassword: boolean; hasVerifiedEmail: boolean }) {
201
235
  const {
202
236
  dispatchApp,
203
237
  appState: { hasPassword, account },
204
238
  } = useContext(AppContext);
205
- const identifier =
206
- account?.email?.address || account?.phone?.number || account?.id;
239
+ const identifier = account?.email?.address || account?.phone?.number || account?.id;
207
240
 
208
241
  const [finishedResult, setFinishedResult] = useState({
209
242
  hasPassword,
210
243
  email: account?.email?.address ? account?.email : null,
244
+ emailVerified: p.hasVerifiedEmail,
211
245
  });
212
246
 
213
247
  const onFinish = () => {
@@ -16,7 +16,7 @@ interface AuthFormContainerProps {
16
16
 
17
17
  export const AuthFormContainer = memo((p: AuthFormContainerProps) => {
18
18
  const { title, className, backHref, children } = p;
19
- const goBackLabel = backHref ? i18n.t('form.go_back') : '';
19
+ const goBackLabel = backHref ? i18n.t('c.go_back') : '';
20
20
 
21
21
  return (
22
22
  <div className="cw xs">
@@ -31,7 +31,7 @@ export const AuthFormContainer = memo((p: AuthFormContainerProps) => {
31
31
  </a>
32
32
  )}
33
33
  <div className="a_c -mb_5 anim_lift_scale_center on_mount spd_4">
34
- <h1 className="ft_lg ft_bold ls_1 lh_1 p_n cl_secondary op_50 visible">
34
+ <h1 className={cn("ft_lg ft_bold ls_1 lh_1 p_n cl_secondary op_50 visible", !title && 'mt_25')}>
35
35
  {title}
36
36
  </h1>
37
37
  </div>
@@ -1,16 +1,14 @@
1
1
  import i18n from '@jsb188/app/i18n/index.ts';
2
2
  import { useGetSsoLoginOptions } from '@jsb188/graphql/hooks/use-auth-mtn';
3
- import SchemaForm from '@jsb188/react-web/modules/SchemaForm';
3
+ import SchemaForm from '@jsb188/form/libs/SchemaForm';
4
+ import { submissionResult } from '@jsb188/form/libs/validation';
4
5
  import { FullWidthButton } from '@jsb188/react-web/ui/Button';
5
6
  import { ModalErrorMessage } from '@jsb188/react-web/ui/ModalUI';
6
7
  import { useCallback, useMemo, useState } from 'react';
7
8
  import { useNavigate } from 'react-router';
8
9
  import type { OnFinishSignInFn, SsoLoginOptionData } from '../hooks/use-oauth';
9
- import {
10
- useContinueWithGoogle,
11
- useContinueWithMicrosoft,
12
- } from '../hooks/use-oauth';
13
- import { getAuthRoute, persistSignInSession } from './_helpers';
10
+ import { useContinueWithGoogle, useContinueWithMicrosoft } from '../hooks/use-oauth';
11
+ import { getAuthReturnQuery, getAuthRoute, persistSignInSession } from './_helpers';
14
12
  import { makeRequestTokenizedEmailSchema } from './schemas';
15
13
 
16
14
  /**
@@ -19,6 +17,7 @@ import { makeRequestTokenizedEmailSchema } from './schemas';
19
17
 
20
18
  interface SsoSignInProps {
21
19
  authRoutesMap?: Record<string, string>;
20
+ returnTo?: string | null;
22
21
  setAuthIface: (iface: null) => void;
23
22
  }
24
23
 
@@ -28,11 +27,7 @@ interface SsoSignInProps {
28
27
  * allowed to open the OAuth popup)
29
28
  */
30
29
 
31
- function SsoOrgOptions(p: {
32
- email: string;
33
- options: SsoLoginOptionData[];
34
- onFinishSignIn: OnFinishSignInFn;
35
- }) {
30
+ function SsoOrgOptions(p: { email: string; options: SsoLoginOptionData[]; onFinishSignIn: OnFinishSignInFn }) {
36
31
  const { email, options, onFinishSignIn } = p;
37
32
  const {
38
33
  onInitiateGoogleSignIn,
@@ -67,7 +62,7 @@ function SsoOrgOptions(p: {
67
62
  );
68
63
  break;
69
64
  case 'MICROSOFT':
70
- onInitiateMicrosoftSignIn(option, email);
65
+ onInitiateMicrosoftSignIn(option, email ?? null);
71
66
  break;
72
67
  default:
73
68
  }
@@ -85,23 +80,13 @@ function SsoOrgOptions(p: {
85
80
  onClick={() => onSelectOption(option)}
86
81
  preset="em"
87
82
  className="mb_sm"
88
- iconName={
89
- option.provider === 'GOOGLE'
90
- ? 'brand-google-color'
91
- : 'brand-microsoft-color'
92
- }
83
+ iconName={option.provider === 'GOOGLE' ? 'brand-google-color' : 'brand-microsoft-color'}
93
84
  >
94
85
  {option.organizationName}
95
86
  </FullWidthButton>
96
87
  ))}
97
88
 
98
- <p className="a_c p_n mt_md mb_df rel">
99
- {i18n.t(
100
- options.length > 1
101
- ? 'auth.sso_choose_org_instr'
102
- : 'auth.sso_continue_instr',
103
- )}
104
- </p>
89
+ <p className="a_c p_n mt_md mb_df rel">{i18n.t(options.length > 1 ? 'auth.sso_choose_org_instr' : 'auth.sso_continue_instr')}</p>
105
90
  </>
106
91
  );
107
92
  }
@@ -113,7 +98,7 @@ function SsoOrgOptions(p: {
113
98
  */
114
99
 
115
100
  export function SsoSignIn(p: SsoSignInProps) {
116
- const { authRoutesMap, setAuthIface } = p;
101
+ const { authRoutesMap, returnTo, setAuthIface } = p;
117
102
  const navigate = useNavigate();
118
103
  const [email, setEmail] = useState('');
119
104
  const [options, setOptions] = useState<SsoLoginOptionData[] | null>(null);
@@ -121,51 +106,45 @@ export function SsoSignIn(p: SsoSignInProps) {
121
106
 
122
107
  // Data hook
123
108
 
124
- const { getSsoLoginOptions, saving, error, setError, resetErrors } =
125
- useGetSsoLoginOptions({
126
- onCompleted: (data: any) => {
127
- const list = data?.getSsoLoginOptions;
128
- if (list?.length) {
129
- setOptions(list);
130
- }
131
- },
132
- onError: (err: any) => {
133
- setError(err);
134
- },
135
- });
109
+ const { getSsoLoginOptions, saving, error, setError, resetErrors } = useGetSsoLoginOptions({
110
+ onCompleted: (data: any) => {
111
+ const list = data?.getSsoLoginOptions;
112
+ if (list?.length) {
113
+ setOptions(list);
114
+ }
115
+ },
116
+ onError: (err: any) => {
117
+ setError(err);
118
+ },
119
+ });
136
120
 
137
121
  /* Persist the signed-in session before navigating to the success route. */
138
122
  const onFinishSignIn = useCallback(
139
- async (
140
- token: string,
141
- sessionBootstrapToken?: string | null,
142
- sessionPersisted?: boolean,
143
- ) => {
144
- const persisted =
145
- sessionPersisted ||
146
- (await persistSignInSession(token, sessionBootstrapToken));
123
+ async (token: string, sessionBootstrapToken?: string | null, sessionPersisted?: boolean) => {
124
+ const persisted = sessionPersisted || (await persistSignInSession(token, sessionBootstrapToken));
147
125
  if (!persisted) {
148
126
  setError({
149
127
  message: i18n.t('error.network_error'),
150
128
  });
151
129
  return false;
152
130
  }
153
- navigate(getAuthRoute('signin_success', authRoutesMap));
131
+ navigate(getAuthRoute('signin_success', authRoutesMap, getAuthReturnQuery(returnTo)));
154
132
  return true;
155
133
  },
156
- [authRoutesMap, navigate, setError],
134
+ [authRoutesMap, navigate, returnTo, setError],
157
135
  );
158
136
 
159
137
  /* Normalize the submitted email before resolving organization SSO options. */
160
138
  const onSubmit = useCallback(
161
- (fv: { email?: string | null }) => {
139
+ async (fv: { email: string }) => {
162
140
  const nextEmail = fv.email?.trim().toLowerCase() || '';
163
141
  setEmail(nextEmail);
164
- getSsoLoginOptions({
142
+ const result = await getSsoLoginOptions({
165
143
  variables: {
166
144
  email: nextEmail,
167
145
  },
168
146
  });
147
+ return submissionResult(result);
169
148
  },
170
149
  [getSsoLoginOptions],
171
150
  );
@@ -190,33 +169,31 @@ export function SsoSignIn(p: SsoSignInProps) {
190
169
  ) : (
191
170
  <SchemaForm
192
171
  className="mb_df"
193
- saving={saving}
194
- schema={emailSchema}
172
+ busy={saving}
173
+ definition={emailSchema}
195
174
  onError={setError}
196
175
  onSubmit={onSubmit}
197
- buttonText={i18n.t('form.continue')}
176
+ buttonText={i18n.t('c.continue')}
198
177
  >
199
178
  {!error ? null : (
200
- <ModalErrorMessage error={error} resetErrors={resetErrors} />
179
+ <ModalErrorMessage
180
+ error={error}
181
+ resetErrors={resetErrors}
182
+ />
201
183
  )}
202
184
 
203
- <p className={error ? 'py_xs a_c' : '-mt_5 pb_xs a_c'}>
204
- {i18n.t('auth.sso_email_instr')}
205
- </p>
185
+ <p className={error ? 'py_xs a_c' : '-mt_5 pb_xs a_c'}>{i18n.t('auth.sso_email_instr')}</p>
206
186
  </SchemaForm>
207
187
  )}
208
188
 
209
189
  <div className="a_c h_center">
210
190
  <button
191
+ type="button"
211
192
  disabled={saving}
212
193
  onClick={onBack}
213
- className="text ft_sm cl_md link"
194
+ className="text_link ft_sm cl_md link"
214
195
  >
215
- {i18n.t(
216
- options?.length
217
- ? 'auth.sso_use_different_email'
218
- : 'auth.sign_in_other_methods',
219
- )}
196
+ {i18n.t(options?.length ? 'auth.sso_use_different_email' : 'auth.sign_in_other_methods')}
220
197
  </button>
221
198
  </div>
222
199
  </>