@jsb188/auth-web 1.1.3 → 1.1.11

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,240 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { useRequestChangeEmail } from '@jsb188/graphql/hooks/use-account-mtn';
3
+ import { useChangeAccountPassword } from '@jsb188/graphql/hooks/use-auth-mtn';
4
+ import { FullPageLayout } from '@jsb188/react-web/modules/layout/MainLayout';
5
+ import SchemaForm from '@jsb188/react-web/modules/SchemaForm';
6
+ import { COMMON_ICON_NAMES } from '@jsb188/react-web/svgs/Icon';
7
+ import { FullWidthButton } from '@jsb188/react-web/ui/Button';
8
+ 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';
14
+ import { useContext, useMemo, useState } from 'react';
15
+ import { AuthFormContainer } from './AuthFormUI';
16
+ import {
17
+ makeAssignPasswordSchema,
18
+ makeRequestTokenizedEmailSchema,
19
+ } from './schemas';
20
+
21
+ /**
22
+ * Types
23
+ */
24
+
25
+ interface FinishedResultObj {
26
+ hasPassword: boolean;
27
+ email: any;
28
+ }
29
+
30
+ interface RequiredAuthSwitchCaseProps {
31
+ identifier: string;
32
+ onFinish: () => void;
33
+ finishedResult: FinishedResultObj;
34
+ setFinishedResult: any;
35
+ }
36
+
37
+ /**
38
+ * Account secured message; after all required auth info has been provided
39
+ */
40
+
41
+ function AccountSecuredMessage(p: RequiredAuthSwitchCaseProps) {
42
+ const { onFinish } = p;
43
+
44
+ return (
45
+ <ModalSimpleContent
46
+ // title='Finished!'
47
+ iconName={COMMON_ICON_NAMES.verified}
48
+ className="px_df pt_md"
49
+ >
50
+ <Markdown as="p">{i18n.t('auth.required_auth_fin_msg')}</Markdown>
51
+
52
+ <FullWidthButton
53
+ preset="bg_primary"
54
+ className="mt_md shadow"
55
+ onClick={onFinish}
56
+ >
57
+ {i18n.t('auth.continue_to_app')}
58
+ </FullWidthButton>
59
+ </ModalSimpleContent>
60
+ );
61
+ }
62
+
63
+ /**
64
+ * Set auth password form
65
+ */
66
+
67
+ function SetPasswordForm(p: RequiredAuthSwitchCaseProps) {
68
+ const { identifier, setFinishedResult } = p;
69
+ const assignPasswordSchema = useMemo(makeAssignPasswordSchema, []);
70
+
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
+ });
83
+
84
+ const onSubmit = (fv: any) => {
85
+ changeAccountPassword({
86
+ variables: {
87
+ currentPassword: '',
88
+ password: fv.password,
89
+ },
90
+ });
91
+ };
92
+
93
+ return (
94
+ <>
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>
98
+
99
+ <SchemaForm
100
+ className="pb_df fs"
101
+ saving={saving}
102
+ schema={assignPasswordSchema}
103
+ // currentData={{}}
104
+ onError={setError}
105
+ onSubmit={onSubmit}
106
+ buttonText={i18n.t('auth.add_password')}
107
+ >
108
+ {!error ? null : (
109
+ <ModalErrorMessage error={error} resetErrors={resetErrors} />
110
+ )}
111
+ </SchemaForm>
112
+ </>
113
+ );
114
+ }
115
+
116
+ /**
117
+ * Set email form
118
+ */
119
+
120
+ function SetEmailForm(p: RequiredAuthSwitchCaseProps) {
121
+ const { identifier } = p;
122
+ const [waitingForVerification, setWaitingForVerification] = useState(false);
123
+ const assignPasswordSchema = useMemo(makeRequestTokenizedEmailSchema, []);
124
+
125
+ const { requestChangeEmail, error, setError, resetErrors, saving } =
126
+ useRequestChangeEmail({
127
+ onCompleted: (data: any) => {
128
+ if (data.requestChangeEmail) {
129
+ setWaitingForVerification(true);
130
+ }
131
+ },
132
+ });
133
+
134
+ const onSubmit = (fv: any) => {
135
+ requestChangeEmail({
136
+ variables: {
137
+ emailAddress: fv.email,
138
+ },
139
+ });
140
+ };
141
+
142
+ if (waitingForVerification) {
143
+ return (
144
+ <ModalSimpleContent
145
+ className="px_df pt_md pb_25"
146
+ iconName={COMMON_ICON_NAMES.email_address}
147
+ title={i18n.t('auth.check_email')}
148
+ message={i18n.t('auth.check_email_to_login_msg')}
149
+ />
150
+ );
151
+ }
152
+
153
+ return (
154
+ <>
155
+ <p className="a_c mx_df mb_df -mt_5 pb_xs">
156
+ {i18n.t('auth.add_email_to_login_msg', { identifier })}
157
+ </p>
158
+
159
+ <SchemaForm
160
+ className="pb_df fs"
161
+ saving={saving}
162
+ schema={assignPasswordSchema}
163
+ // currentData={{}}
164
+ onError={setError}
165
+ onSubmit={onSubmit}
166
+ buttonText={i18n.t('auth.add_email')}
167
+ >
168
+ {!error ? null : (
169
+ <ModalErrorMessage error={error} resetErrors={resetErrors} />
170
+ )}
171
+ </SchemaForm>
172
+ </>
173
+ );
174
+ }
175
+
176
+ /**
177
+ * Switch case for required auth
178
+ */
179
+
180
+ function RequiredAuthSwitchCase(p: RequiredAuthSwitchCaseProps) {
181
+ const { finishedResult } = p;
182
+
183
+ if (!finishedResult.hasPassword) {
184
+ return <SetPasswordForm {...p} />;
185
+ } else if (!finishedResult.email) {
186
+ // Keep email check last, becuase it has a verification step
187
+ return <SetEmailForm {...p} />;
188
+ }
189
+
190
+ return <AccountSecuredMessage {...p} />;
191
+ }
192
+
193
+ /**
194
+ * Force users to provide required authentication info
195
+ */
196
+
197
+ export function AssignRequiredAuth(p: {
198
+ hasPassword: boolean;
199
+ hasEmail: boolean;
200
+ }) {
201
+ const {
202
+ dispatchApp,
203
+ appState: { hasPassword, account },
204
+ } = useContext(AppContext);
205
+ const identifier =
206
+ account?.email?.address || account?.phone?.number || account?.id;
207
+
208
+ const [finishedResult, setFinishedResult] = useState({
209
+ hasPassword,
210
+ email: account?.email?.address ? account?.email : null,
211
+ });
212
+
213
+ const onFinish = () => {
214
+ if (!hasPassword) {
215
+ dispatchApp({
216
+ __type: 'APP_EDIT_AUTH',
217
+ data: {
218
+ id: account?.id,
219
+ ...finishedResult,
220
+ },
221
+ });
222
+ }
223
+ };
224
+
225
+ return (
226
+ <FullPageLayout className="pattern_dot active_bf bg_fade">
227
+ <AuthFormContainer
228
+ title={i18n.t('auth.one_last_step_')}
229
+ className="bd_5 bd_main"
230
+ >
231
+ <RequiredAuthSwitchCase
232
+ identifier={identifier!}
233
+ finishedResult={finishedResult}
234
+ setFinishedResult={setFinishedResult}
235
+ onFinish={onFinish}
236
+ />
237
+ </AuthFormContainer>
238
+ </FullPageLayout>
239
+ );
240
+ }
@@ -0,0 +1,45 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { cn } from '@jsb188/app/utils/string.ts';
3
+ import { Icon } from '@jsb188/react-web/svgs/Icon';
4
+ import { memo } from 'react';
5
+
6
+ /**
7
+ * Auth form container
8
+ */
9
+
10
+ interface AuthFormContainerProps {
11
+ title?: string;
12
+ className?: string;
13
+ backHref?: string | null;
14
+ children: React.ReactNode;
15
+ }
16
+
17
+ export const AuthFormContainer = memo((p: AuthFormContainerProps) => {
18
+ const { title, className, backHref, children } = p;
19
+ const goBackLabel = backHref ? i18n.t('form.go_back') : '';
20
+
21
+ return (
22
+ <div className="cw xs">
23
+ {!!backHref && (
24
+ <a
25
+ href={backHref}
26
+ aria-label={goBackLabel}
27
+ title={goBackLabel}
28
+ className="abs_tl_df av av_df r h_center bg cl_df bg_active_hv shadow_line z2 link"
29
+ >
30
+ <Icon name="arrow-left" />
31
+ </a>
32
+ )}
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">
35
+ {title}
36
+ </h1>
37
+ </div>
38
+ <div className={cn('bg px_md py_lg r_dfw rel z2', className)}>
39
+ {children}
40
+ </div>
41
+ </div>
42
+ );
43
+ });
44
+
45
+ AuthFormContainer.displayName = 'AuthFormContainer';
@@ -0,0 +1,224 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { useGetSsoLoginOptions } from '@jsb188/graphql/hooks/use-auth-mtn';
3
+ import SchemaForm from '@jsb188/react-web/modules/SchemaForm';
4
+ import { FullWidthButton } from '@jsb188/react-web/ui/Button';
5
+ import { ModalErrorMessage } from '@jsb188/react-web/ui/ModalUI';
6
+ import { useCallback, useMemo, useState } from 'react';
7
+ import { useNavigate } from 'react-router';
8
+ 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';
14
+ import { makeRequestTokenizedEmailSchema } from './schemas';
15
+
16
+ /**
17
+ * Types
18
+ */
19
+
20
+ interface SsoSignInProps {
21
+ authRoutesMap?: Record<string, string>;
22
+ setAuthIface: (iface: null) => void;
23
+ }
24
+
25
+ /**
26
+ * SSO org picker; one button per matching org SSO connection, clicking it
27
+ * launches that org's provider flow (the click is the user gesture that is
28
+ * allowed to open the OAuth popup)
29
+ */
30
+
31
+ function SsoOrgOptions(p: {
32
+ email: string;
33
+ options: SsoLoginOptionData[];
34
+ onFinishSignIn: OnFinishSignInFn;
35
+ }) {
36
+ const { email, options, onFinishSignIn } = p;
37
+ const {
38
+ onInitiateGoogleSignIn,
39
+ oauthButtonDisabled: googleDisabled,
40
+ waitingForOAuth: waitingForGoogle,
41
+ } = useContinueWithGoogle({
42
+ onFinishSignIn,
43
+ });
44
+ const {
45
+ onInitiateMicrosoftSignIn,
46
+ oauthButtonDisabled: microsoftDisabled,
47
+ waitingForOAuth: waitingForMicrosoft,
48
+ } = useContinueWithMicrosoft({
49
+ onFinishSignIn,
50
+ });
51
+
52
+ const oauthButtonDisabled = googleDisabled || microsoftDisabled;
53
+ const waitingForOAuth = waitingForGoogle || waitingForMicrosoft;
54
+
55
+ /* Launch the provider flow associated with an organization SSO option. */
56
+ const onSelectOption = useCallback(
57
+ (option: SsoLoginOptionData) => {
58
+ switch (option.provider) {
59
+ case 'GOOGLE':
60
+ // "hint" pre-selects the typed email in Google's account chooser;
61
+ // the server validates the returned "hd" claim against the connection
62
+ onInitiateGoogleSignIn(
63
+ {
64
+ hint: email || undefined,
65
+ },
66
+ option.id,
67
+ );
68
+ break;
69
+ case 'MICROSOFT':
70
+ onInitiateMicrosoftSignIn(option, email);
71
+ break;
72
+ default:
73
+ }
74
+ },
75
+ [email, onInitiateGoogleSignIn, onInitiateMicrosoftSignIn],
76
+ );
77
+
78
+ return (
79
+ <>
80
+ {options.map((option) => (
81
+ <FullWidthButton
82
+ key={option.id}
83
+ disabled={oauthButtonDisabled}
84
+ loading={waitingForOAuth}
85
+ onClick={() => onSelectOption(option)}
86
+ preset="em"
87
+ className="mb_sm"
88
+ iconName={
89
+ option.provider === 'GOOGLE'
90
+ ? 'brand-google-color'
91
+ : 'brand-microsoft-color'
92
+ }
93
+ >
94
+ {option.organizationName}
95
+ </FullWidthButton>
96
+ ))}
97
+
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>
105
+ </>
106
+ );
107
+ }
108
+
109
+ /**
110
+ * SSO sign in (email-first home realm discovery); asks for the email
111
+ * address, resolves which org SSO connections can sign it in, then routes
112
+ * to the matching provider flow
113
+ */
114
+
115
+ export function SsoSignIn(p: SsoSignInProps) {
116
+ const { authRoutesMap, setAuthIface } = p;
117
+ const navigate = useNavigate();
118
+ const [email, setEmail] = useState('');
119
+ const [options, setOptions] = useState<SsoLoginOptionData[] | null>(null);
120
+ const emailSchema = useMemo(makeRequestTokenizedEmailSchema, []);
121
+
122
+ // Data hook
123
+
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
+ });
136
+
137
+ /* Persist the signed-in session before navigating to the success route. */
138
+ 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));
147
+ if (!persisted) {
148
+ setError({
149
+ message: i18n.t('error.network_error'),
150
+ });
151
+ return false;
152
+ }
153
+ navigate(getAuthRoute('signin_success', authRoutesMap));
154
+ return true;
155
+ },
156
+ [authRoutesMap, navigate, setError],
157
+ );
158
+
159
+ /* Normalize the submitted email before resolving organization SSO options. */
160
+ const onSubmit = useCallback(
161
+ (fv: { email?: string | null }) => {
162
+ const nextEmail = fv.email?.trim().toLowerCase() || '';
163
+ setEmail(nextEmail);
164
+ getSsoLoginOptions({
165
+ variables: {
166
+ email: nextEmail,
167
+ },
168
+ });
169
+ },
170
+ [getSsoLoginOptions],
171
+ );
172
+
173
+ /* Return to the prior email or authentication-method selection step. */
174
+ const onBack = useCallback(() => {
175
+ if (options?.length) {
176
+ setOptions(null);
177
+ return;
178
+ }
179
+ setAuthIface(null);
180
+ }, [options, setAuthIface]);
181
+
182
+ return (
183
+ <>
184
+ {options?.length ? (
185
+ <SsoOrgOptions
186
+ email={email}
187
+ options={options}
188
+ onFinishSignIn={onFinishSignIn}
189
+ />
190
+ ) : (
191
+ <SchemaForm
192
+ className="mb_df"
193
+ saving={saving}
194
+ schema={emailSchema}
195
+ onError={setError}
196
+ onSubmit={onSubmit}
197
+ buttonText={i18n.t('form.continue')}
198
+ >
199
+ {!error ? null : (
200
+ <ModalErrorMessage error={error} resetErrors={resetErrors} />
201
+ )}
202
+
203
+ <p className={error ? 'py_xs a_c' : '-mt_5 pb_xs a_c'}>
204
+ {i18n.t('auth.sso_email_instr')}
205
+ </p>
206
+ </SchemaForm>
207
+ )}
208
+
209
+ <div className="a_c h_center">
210
+ <button
211
+ disabled={saving}
212
+ onClick={onBack}
213
+ className="text ft_sm cl_md link"
214
+ >
215
+ {i18n.t(
216
+ options?.length
217
+ ? 'auth.sso_use_different_email'
218
+ : 'auth.sign_in_other_methods',
219
+ )}
220
+ </button>
221
+ </div>
222
+ </>
223
+ );
224
+ }