-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathLoginInitScreen.tsx
More file actions
342 lines (287 loc) · 11.5 KB
/
LoginInitScreen.tsx
File metadata and controls
342 lines (287 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import type { ConnectError } from '@corbado/web-core';
import { base64decode, ConnectErrorType, PasskeyLoginSource } from '@corbado/web-core';
import type { ConnectLoginFinishRsp } from '@corbado/web-core/dist/api/v2';
import log from 'loglevel';
import type { FC } from 'react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import useLoginProcess from '../../hooks/useLoginProcess';
import useShared from '../../hooks/useShared';
import { Flags } from '../../types/flags';
import { LoginScreenType } from '../../types/screenTypes';
import { getLoginErrorMessage, LoginSituationCode } from '../../types/situations';
import { StatefulLoader } from '../../utils/statefulLoader';
import LoginInitLoaded from './base/LoginInitLoaded';
import LoginInitLoading from './base/LoginInitLoading';
export type CboApiFallbackOperationError = {
initFallback: boolean;
identifierFallback: string;
message: string | null;
};
export enum LoginInitState {
SilentLoading,
Loading,
Loaded,
}
interface Props {
showFallback?: boolean;
prefilledIdentifier?: string;
}
export const connectLoginFinishToComplete = (v: ConnectLoginFinishRsp): string => {
if (v.session.length > 0) {
return v.session;
}
return v.signedPasskeyData;
};
export const connectLoginFinishToWebauthnId = (v: ConnectLoginFinishRsp): string => {
const parts = v.signedPasskeyData.split('.');
const base64decoded = JSON.parse(base64decode(parts[1]));
return base64decoded['webauthnId'];
};
const LoginInitScreen: FC<Props> = ({ showFallback = false }) => {
const { config, navigateToScreen, setCurrentIdentifier, setFlags, flags, loadedMs, fallback } = useLoginProcess();
const { sharedConfig, getConnectService } = useShared();
const [cuiBasedLoading, setCuiBasedLoading] = useState(false);
const [identifierBasedLoading, setIdentifierBasedLoading] = useState(false);
const [error, setError] = useState('');
const [isFallbackInitiallyTriggered, setIsFallbackInitiallyTriggered] = useState(false);
const [loginInitState, setLoginInitState] = useState(LoginInitState.SilentLoading);
const [identifier, setIdentifier] = useState<string>('');
const statefulLoader = useRef(
new StatefulLoader(
() => setLoginInitState(LoginInitState.Loading),
() => {
config.onLoaded?.('loading finished', isFallbackInitiallyTriggered);
setLoginInitState(LoginInitState.Loaded);
},
() => {
config?.onLoaded?.('loading finished', isFallbackInitiallyTriggered);
setLoginInitState(LoginInitState.Loaded);
},
),
);
const simulateError = (): boolean => {
const urlParams = new URLSearchParams(window.location.search);
const maybeError = urlParams.get('cboSimulate');
if (!maybeError) {
return false;
}
// parse string to AppendSituationCode
const typed = LoginSituationCode[maybeError as keyof typeof LoginSituationCode];
handleSituation(typed);
return true;
};
useEffect(() => {
const init = async (ac: AbortController) => {
if (simulateError()) {
return;
}
log.debug('running init');
statefulLoader.current.start();
const url = new URL(window.location.href);
const invitationToken = url.searchParams.get('invitationToken');
if (invitationToken) {
getConnectService().setInvitation(invitationToken);
}
getConnectService().enrichClientState(config.clientState);
const res = await getConnectService().loginInit(ac);
if (res.err) {
if (res.val.type === ConnectErrorType.Cancel) {
return;
}
statefulLoader.current.finishWithError();
return handleSituation(LoginSituationCode.CboApiNotAvailablePreAuthenticator, res.val);
}
// we load flags from backend first, then we override them with the ones that are specified in the component's config
const flags = new Flags(res.val.flags);
if (sharedConfig.flags) {
flags.addFlags(sharedConfig.flags);
}
setFlags(flags);
if (!res.val.loginAllowed || showFallback) {
return handleSituation(LoginSituationCode.DeniedByPartialRollout);
}
const lastLogin = getConnectService().getLastLogin();
if (lastLogin) {
log.debug('starting relogin UI');
return navigateToScreen(LoginScreenType.PasskeyReLogin);
} else if (flags.hasSupportForConditionalUI()) {
log.debug('starting conditional UI');
void startConditionalUI(res.val.conditionalUIChallenge);
}
statefulLoader.current.finish();
};
const ac = new AbortController();
void init(ac);
return () => {
ac.abort();
getConnectService().dispose();
};
}, [getConnectService]);
const startConditionalUI = async (challenge: string | null) => {
if (!challenge) {
return;
}
let cuiStarted = false;
const res = await getConnectService().conditionalUILogin(
ac => config.onConditionalLoginStart?.(ac),
() => {
setCuiBasedLoading(true);
cuiStarted = true;
},
() => {
return;
},
loadedMs,
);
if (res.err) {
// if a user cancel during CUI, she can try again
if (res.val.type === ConnectErrorType.Cancel) {
return handleSituation(LoginSituationCode.ClientPasskeyConditionalOperationCancelled, res.val);
}
// cuiStarted === true indicates that user has passed the authenticator
if (cuiStarted) {
return handleSituation(LoginSituationCode.CboApiNotAvailablePostConditionalAuthenticator, res.val);
}
return handleSituation(LoginSituationCode.CboApiNotAvailablePreConditionalAuthenticator, res.val);
}
if (res.val.fallbackOperationError) {
const data: CboApiFallbackOperationError = {
initFallback: res.val.fallbackOperationError.initFallback,
identifierFallback: res.val.fallbackOperationError.identifier ?? '',
message: res.val.fallbackOperationError.error?.message ?? null,
};
return handleSituation(LoginSituationCode.CboApiFallbackOperationError, undefined, data);
}
try {
await config.onComplete(
connectLoginFinishToComplete(res.val),
getConnectService().encodeClientState(),
connectLoginFinishToWebauthnId(res.val),
);
} catch {
return handleSituation(LoginSituationCode.CtApiNotAvailablePostAuthenticator);
}
};
const handleSubmit = useCallback(async () => {
if (identifier === '') {
return setError('Enter your email address.');
}
setIdentifierBasedLoading(true);
setCurrentIdentifier(identifier);
config.onLoginStart?.();
const resStart = await getConnectService().loginStart(identifier, PasskeyLoginSource.TextField, loadedMs);
if (resStart.err) {
return handleSituation(LoginSituationCode.CboApiNotAvailablePreAuthenticator, resStart.val);
}
if (resStart.val.isCDA) {
navigateToScreen(LoginScreenType.LoginHybridScreen, resStart.val);
return;
}
if (resStart.val.assertionOptions.length === 0) {
const data: CboApiFallbackOperationError = {
initFallback: resStart.val.fallbackOperationError.initFallback,
identifierFallback: resStart.val.fallbackOperationError.identifier ?? '',
message: resStart.val.fallbackOperationError.error?.message ?? null,
};
return handleSituation(LoginSituationCode.CboApiFallbackOperationError, undefined, data);
}
const res = await getConnectService().loginContinue(resStart.val);
if (res.err) {
setIdentifierBasedLoading(false);
if (res.val.type === ConnectErrorType.Cancel) {
return handleSituation(
LoginSituationCode.ClientPasskeyOperationCancelled,
res.val,
resStart.val.assertionOptions,
);
}
return handleSituation(LoginSituationCode.CboApiNotAvailablePostAuthenticator, res.val);
}
try {
await config.onComplete(
connectLoginFinishToComplete(res.val),
getConnectService().encodeClientState(),
connectLoginFinishToWebauthnId(res.val),
);
} catch {
void getConnectService().recordEventLoginErrorUntyped();
return handleSituation(LoginSituationCode.CtApiNotAvailablePostAuthenticator);
}
}, [getConnectService, config, loadedMs, identifier]);
const automaticFallback = (identifier: string, message: string | null) => {
navigateToScreen(LoginScreenType.Invisible);
setIsFallbackInitiallyTriggered(true);
fallback(identifier, message);
};
const explicitFallback = () => {
navigateToScreen(LoginScreenType.Invisible);
fallback(identifier, null);
};
const handleSituation = (situationCode: LoginSituationCode, error?: ConnectError, data?: unknown) => {
const messageCode = `situation: ${situationCode} ${error?.track()}`;
log.debug(messageCode);
const message = getLoginErrorMessage(situationCode);
switch (situationCode) {
case LoginSituationCode.CboApiNotAvailablePreAuthenticator:
automaticFallback(identifier, message);
void getConnectService().recordEventLoginErrorUnexpected(messageCode);
statefulLoader.current.finish();
break;
case LoginSituationCode.DeniedByPartialRollout:
automaticFallback(identifier, message);
statefulLoader.current.finish();
break;
case LoginSituationCode.CboApiNotAvailablePostConditionalAuthenticator:
case LoginSituationCode.CboApiNotAvailablePreConditionalAuthenticator:
case LoginSituationCode.CtApiNotAvailablePostAuthenticator:
case LoginSituationCode.CboApiNotAvailablePostAuthenticator:
automaticFallback(identifier, message);
void getConnectService().recordEventLoginErrorUnexpected(messageCode);
setIdentifierBasedLoading(false);
break;
case LoginSituationCode.ClientPasskeyOperationCancelled: {
const assertionOptions = data as string;
navigateToScreen(LoginScreenType.ErrorSoft, { previousAssertionOptions: assertionOptions });
void getConnectService().recordEventLoginError(messageCode);
config.onError?.(situationCode.toString());
setIdentifierBasedLoading(false);
break;
}
case LoginSituationCode.ExplicitFallbackByUser:
explicitFallback();
void getConnectService().recordEventLoginExplicitAbort();
break;
case LoginSituationCode.CboApiFallbackOperationError: {
const typed = data as CboApiFallbackOperationError;
if (typed.initFallback) {
return automaticFallback(typed.identifierFallback, typed.message);
}
setError(typed.message ?? '');
setCuiBasedLoading(false);
setIdentifierBasedLoading(false);
break;
}
}
};
// Enable auto complete for username and webauthn if conditional UI is supported
// This is needed to enable multiple login instances on the same page however only one should have the autocomplete
// Else the conditionalUI won't work
const autoComplete = useMemo(() => (flags?.hasSupportForConditionalUI() ? 'username webauthn' : ''), [flags]);
switch (loginInitState) {
case LoginInitState.SilentLoading:
return <></>;
case LoginInitState.Loading:
return <LoginInitLoading />;
case LoginInitState.Loaded:
return (
<LoginInitLoaded
isLoading={cuiBasedLoading || identifierBasedLoading}
error={error}
autoComplete={autoComplete}
handleSubmit={() => void handleSubmit()}
handleIdentifierUpdate={(v: string) => setIdentifier(v)}
/>
);
}
};
export default LoginInitScreen;