@jsb188/auth-web 1.1.11 → 1.1.12

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,8 @@ import { makeRequestTokenizedEmailSchema } from './schemas';
19
17
 
20
18
  interface SsoSignInProps {
21
19
  authRoutesMap?: Record<string, string>;
20
+ formPublicId?: string | null;
21
+ returnTo?: string | null;
22
22
  setAuthIface: (iface: null) => void;
23
23
  }
24
24
 
@@ -30,10 +30,11 @@ interface SsoSignInProps {
30
30
 
31
31
  function SsoOrgOptions(p: {
32
32
  email: string;
33
+ formPublicId?: string | null;
33
34
  options: SsoLoginOptionData[];
34
35
  onFinishSignIn: OnFinishSignInFn;
35
36
  }) {
36
- const { email, options, onFinishSignIn } = p;
37
+ const { email, formPublicId, options, onFinishSignIn } = p;
37
38
  const {
38
39
  onInitiateGoogleSignIn,
39
40
  oauthButtonDisabled: googleDisabled,
@@ -64,15 +65,16 @@ function SsoOrgOptions(p: {
64
65
  hint: email || undefined,
65
66
  },
66
67
  option.id,
68
+ formPublicId ?? null,
67
69
  );
68
70
  break;
69
71
  case 'MICROSOFT':
70
- onInitiateMicrosoftSignIn(option, email);
72
+ onInitiateMicrosoftSignIn(option, email, formPublicId ?? null);
71
73
  break;
72
74
  default:
73
75
  }
74
76
  },
75
- [email, onInitiateGoogleSignIn, onInitiateMicrosoftSignIn],
77
+ [email, formPublicId, onInitiateGoogleSignIn, onInitiateMicrosoftSignIn],
76
78
  );
77
79
 
78
80
  return (
@@ -85,23 +87,13 @@ function SsoOrgOptions(p: {
85
87
  onClick={() => onSelectOption(option)}
86
88
  preset="em"
87
89
  className="mb_sm"
88
- iconName={
89
- option.provider === 'GOOGLE'
90
- ? 'brand-google-color'
91
- : 'brand-microsoft-color'
92
- }
90
+ iconName={option.provider === 'GOOGLE' ? 'brand-google-color' : 'brand-microsoft-color'}
93
91
  >
94
92
  {option.organizationName}
95
93
  </FullWidthButton>
96
94
  ))}
97
95
 
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>
96
+ <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
97
  </>
106
98
  );
107
99
  }
@@ -113,7 +105,7 @@ function SsoOrgOptions(p: {
113
105
  */
114
106
 
115
107
  export function SsoSignIn(p: SsoSignInProps) {
116
- const { authRoutesMap, setAuthIface } = p;
108
+ const { authRoutesMap, formPublicId, returnTo, setAuthIface } = p;
117
109
  const navigate = useNavigate();
118
110
  const [email, setEmail] = useState('');
119
111
  const [options, setOptions] = useState<SsoLoginOptionData[] | null>(null);
@@ -121,51 +113,45 @@ export function SsoSignIn(p: SsoSignInProps) {
121
113
 
122
114
  // Data hook
123
115
 
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
- });
116
+ const { getSsoLoginOptions, saving, error, setError, resetErrors } = useGetSsoLoginOptions({
117
+ onCompleted: (data: any) => {
118
+ const list = data?.getSsoLoginOptions;
119
+ if (list?.length) {
120
+ setOptions(list);
121
+ }
122
+ },
123
+ onError: (err: any) => {
124
+ setError(err);
125
+ },
126
+ });
136
127
 
137
128
  /* Persist the signed-in session before navigating to the success route. */
138
129
  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));
130
+ async (token: string, sessionBootstrapToken?: string | null, sessionPersisted?: boolean) => {
131
+ const persisted = sessionPersisted || (await persistSignInSession(token, sessionBootstrapToken));
147
132
  if (!persisted) {
148
133
  setError({
149
134
  message: i18n.t('error.network_error'),
150
135
  });
151
136
  return false;
152
137
  }
153
- navigate(getAuthRoute('signin_success', authRoutesMap));
138
+ navigate(getAuthRoute('signin_success', authRoutesMap, getAuthReturnQuery(returnTo)));
154
139
  return true;
155
140
  },
156
- [authRoutesMap, navigate, setError],
141
+ [authRoutesMap, navigate, returnTo, setError],
157
142
  );
158
143
 
159
144
  /* Normalize the submitted email before resolving organization SSO options. */
160
145
  const onSubmit = useCallback(
161
- (fv: { email?: string | null }) => {
146
+ async (fv: { email: string }) => {
162
147
  const nextEmail = fv.email?.trim().toLowerCase() || '';
163
148
  setEmail(nextEmail);
164
- getSsoLoginOptions({
149
+ const result = await getSsoLoginOptions({
165
150
  variables: {
166
151
  email: nextEmail,
167
152
  },
168
153
  });
154
+ return submissionResult(result);
169
155
  },
170
156
  [getSsoLoginOptions],
171
157
  );
@@ -184,39 +170,38 @@ export function SsoSignIn(p: SsoSignInProps) {
184
170
  {options?.length ? (
185
171
  <SsoOrgOptions
186
172
  email={email}
173
+ formPublicId={formPublicId}
187
174
  options={options}
188
175
  onFinishSignIn={onFinishSignIn}
189
176
  />
190
177
  ) : (
191
178
  <SchemaForm
192
179
  className="mb_df"
193
- saving={saving}
194
- schema={emailSchema}
180
+ busy={saving}
181
+ definition={emailSchema}
195
182
  onError={setError}
196
183
  onSubmit={onSubmit}
197
- buttonText={i18n.t('form.continue')}
184
+ buttonText={i18n.t('c.continue')}
198
185
  >
199
186
  {!error ? null : (
200
- <ModalErrorMessage error={error} resetErrors={resetErrors} />
187
+ <ModalErrorMessage
188
+ error={error}
189
+ resetErrors={resetErrors}
190
+ />
201
191
  )}
202
192
 
203
- <p className={error ? 'py_xs a_c' : '-mt_5 pb_xs a_c'}>
204
- {i18n.t('auth.sso_email_instr')}
205
- </p>
193
+ <p className={error ? 'py_xs a_c' : '-mt_5 pb_xs a_c'}>{i18n.t('auth.sso_email_instr')}</p>
206
194
  </SchemaForm>
207
195
  )}
208
196
 
209
197
  <div className="a_c h_center">
210
198
  <button
199
+ type="button"
211
200
  disabled={saving}
212
201
  onClick={onBack}
213
202
  className="text ft_sm cl_md link"
214
203
  >
215
- {i18n.t(
216
- options?.length
217
- ? 'auth.sso_use_different_email'
218
- : 'auth.sign_in_other_methods',
219
- )}
204
+ {i18n.t(options?.length ? 'auth.sso_use_different_email' : 'auth.sign_in_other_methods')}
220
205
  </button>
221
206
  </div>
222
207
  </>