-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathprocessHandler.ts
More file actions
332 lines (281 loc) · 10.5 KB
/
processHandler.ts
File metadata and controls
332 lines (281 loc) · 10.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
import type {
BlockBody,
CorbadoError,
EmailVerifyFromUrl,
GeneralBlockVerifyIdentifier,
ProcessCommon,
ProcessResponse,
} from '@corbado/web-core';
import { AuthType, BlockType, type CorbadoApp } from '@corbado/web-core';
import type { GeneralBlockCompleted } from '@corbado/web-core/dist/api/v2';
import type { i18n } from 'i18next';
import type { Result } from 'ts-results';
import { Ok } from 'ts-results';
import type { Block } from './blocks';
import {
ContinueOnOtherEnvBlock,
EmailVerifyBlock,
LoginInitBlock,
PasskeyAppendBlock,
PasskeyAppendedBlock,
PasskeyVerifyBlock,
PhoneVerifyBlock,
SignupInitBlock,
} from './blocks';
import { CompletedBlock } from './blocks/CompletedBlock';
import type { BlockTypes, ScreenNames } from './constants';
import { initScreenBlocks } from './constants';
import { ErrorTranslator } from './errorTranslator';
import { ProcessHistoryHandler } from './processHistoryHandler';
import type { ScreenWithBlock } from './types';
/**
* ProcessHandler is a class that manages the navigation flow of the application.
* It keeps track of the current flow, the current screen, and the screen history.
* It also provides methods for navigating to the next screen, navigating back, and changing the flow.
*/
export class ProcessHandler {
#currentScreen!: ScreenNames;
#currentBlock: Block<unknown> | null = null;
#abortController = new AbortController();
#corbadoApp: CorbadoApp;
#processHistoryHandler: ProcessHistoryHandler;
#errorTranslator: ErrorTranslator;
#postProcess: () => void;
#onScreenChangeCallbacks: Array<(v: ScreenWithBlock) => void> = [];
/**
* The constructor initializes the ProcessHandler with a flow name, a project configuration, and a flow handler configuration.
* It sets the current flow to the specified flow, the current screen to the InitSignup screen, and initializes the screen history as an empty array.
*/
constructor(
i18next: i18n,
corbadoApp: CorbadoApp | undefined,
postProcess: () => void,
handleNavigationEvents = true,
) {
if (!corbadoApp) {
throw new Error('corbadoApp is undefined. This should not happen.');
}
const errorTranslator = new ErrorTranslator(i18next);
this.#corbadoApp = corbadoApp;
this.#processHistoryHandler = new ProcessHistoryHandler(handleNavigationEvents);
this.#errorTranslator = errorTranslator;
this.#postProcess = postProcess;
}
/**
* Initializes the ProcessHandler.
* Call this function after registering all callbacks.
*/
async init(initialBlockFromComponentConfig?: BlockTypes): Promise<Result<void, CorbadoError>> {
const frontendPreferredBlockType = this.#processHistoryHandler.init(
(blockType: BlockTypes) => this.switchToBlock(blockType),
() => this.startAskForAbort(),
);
const emailVerifyFromUrl = this.#corbadoApp.authProcessService.initEmailVerifyFromUrl();
if (emailVerifyFromUrl.err) {
this.handleError(emailVerifyFromUrl.val);
return Ok(void 0);
}
if (emailVerifyFromUrl.val) {
this.handleProcessUpdateFromUrl(emailVerifyFromUrl.val);
return Ok(void 0);
}
// we prefer frontendPreferredBlockType over initialBlockFromComponentConfig
const res = await this.#corbadoApp.authProcessService.init(
this.#abortController,
(frontendPreferredBlockType ?? initialBlockFromComponentConfig) as BlockType,
);
if (res.err) {
return res;
}
this.handleProcessUpdateBackend(res.val);
return Ok(void 0);
}
onProcessCompleted(data: GeneralBlockCompleted) {
this.#corbadoApp.authProcessService.clearProcess();
this.#corbadoApp.authProcessService.dropLastIdentifier(data.passkeyOperation);
this.#currentBlock = null;
this.#corbadoApp.sessionService.setSession(data.sessionToken, data.refreshToken);
this.#postProcess();
}
switchToBlock(blockType: BlockTypes): boolean {
if (this.#currentBlock?.type === blockType) {
this.handleProcessUpdateFrontend(this.#currentBlock, this.#currentBlock.alternatives);
return true;
}
const newBlock = this.#currentBlock?.alternatives.find(b => b.type === blockType);
if (!newBlock) {
return false;
}
const newAlternatives = this.#currentBlock?.alternatives.filter(b => b.type !== blockType) ?? [];
if (this.#currentBlock) {
newAlternatives.push(this.#currentBlock);
}
this.handleProcessUpdateFrontend(newBlock, newAlternatives);
return true;
}
// this adds a ConfirmProcessAbortBlock to the process
startAskForAbort() {
const currentBlock = this.#currentBlock;
if (!currentBlock || initScreenBlocks.includes(currentBlock.type)) {
return;
}
// in login processes we don't want to ask for abort (we auto-confirm it)
if (currentBlock.authType === AuthType.Login) {
void currentBlock.confirmAbort();
return;
}
// The default action is to continue on yes and abort on no because mobile Safari will auto-cancel.
// For reference see (unsolved bug): https://stackoverflow.com/questions/38083702/alert-confirm-and-prompt-not-working-after-using-history-api-on-safari-ios
if (
confirm(
'Going back will restart the signup process and your current progress will be lost. Do you wish to complete the current signup first?',
)
) {
history.forward();
} else {
void currentBlock.confirmAbort();
}
}
dispose() {
this.#corbadoApp.dispose();
this.#abortController.abort();
this.#processHistoryHandler.dispose();
}
get currentScreenName() {
return this.#currentScreen;
}
updateScreen(newScreen: ScreenNames) {
this.#currentScreen = newScreen;
this.#onScreenChangeCallbacks.forEach(cb =>
cb({
screen: newScreen,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
block: this.#currentBlock!,
}),
);
}
onScreenChange(cb: (value: ScreenWithBlock) => void) {
return this.#onScreenChangeCallbacks.push(cb) - 1;
}
removeOnScreenChangeCallback(cbId: number) {
this.#onScreenChangeCallbacks.splice(cbId, 1);
}
handleProcessUpdateFromUrl(emailVerifyFromUrl: EmailVerifyFromUrl) {
const newBlock = EmailVerifyBlock.fromUrl(
this.#corbadoApp,
this,
this.#errorTranslator,
emailVerifyFromUrl.data,
emailVerifyFromUrl.authType,
emailVerifyFromUrl.token,
) as Block<unknown>;
newBlock.init();
this.#updatePrimaryBlock(newBlock);
}
handleProcessUpdateBackend(processResponse: ProcessResponse, error?: CorbadoError) {
const newPrimaryBlock = this.#parseBlockData(processResponse.blockBody, processResponse.common);
if (error) {
newPrimaryBlock.error = error;
}
const alternatives =
processResponse.blockBody.alternatives?.map(b => this.#parseBlockData(b, processResponse.common)) ?? [];
newPrimaryBlock.setAlternatives(alternatives);
newPrimaryBlock.init();
this.#updatePrimaryBlock(newPrimaryBlock);
}
handleProcessUpdateFrontend(newPrimaryBlock: Block<unknown>, newAlternatives: Block<unknown>[] = []) {
newPrimaryBlock.setAlternatives(newAlternatives);
newPrimaryBlock.init();
this.#updatePrimaryBlock(newPrimaryBlock);
}
// updates the current block with the error and updates the screen
handleError(corbadoError: CorbadoError) {
console.log('handleError', corbadoError.name, corbadoError.message);
const primaryBlockWithError = this.#currentBlock;
if (!primaryBlockWithError) {
return;
}
primaryBlockWithError.error = corbadoError;
this.#updatePrimaryBlock(primaryBlockWithError);
return;
}
#updatePrimaryBlock = (newPrimaryBlock: Block<unknown>) => {
// if process has been completed, we don't want to update the screen anymore
if (newPrimaryBlock instanceof CompletedBlock) {
this.onProcessCompleted(newPrimaryBlock.data);
return;
}
const blockHasChanged = this.#currentBlock == null || newPrimaryBlock.type !== this.#currentBlock.type;
if (blockHasChanged) {
this.#currentScreen = newPrimaryBlock.initialScreen;
}
this.#currentBlock = newPrimaryBlock;
this.#onScreenChangeCallbacks.forEach(cb =>
cb({
screen: this.#currentScreen,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
block: this.#currentBlock!,
}),
);
if (blockHasChanged) {
this.#processHistoryHandler.registerBlockChange(newPrimaryBlock.type);
}
};
#parseBlockData = (blockBody: BlockBody, common: ProcessCommon) => {
if (blockBody.continueOnOtherDevice) {
return new ContinueOnOtherEnvBlock(
this.#corbadoApp,
this,
common,
this.#errorTranslator,
blockBody.authType,
blockBody.continueOnOtherDevice,
);
}
let block: Block<unknown>;
switch (blockBody.block) {
case BlockType.PasskeyAppend:
block = new PasskeyAppendBlock(this.#corbadoApp, this, common, this.#errorTranslator, blockBody);
break;
case BlockType.SignupInit:
block = new SignupInitBlock(this.#corbadoApp, this, common, this.#errorTranslator, blockBody);
break;
case BlockType.LoginInit:
block = new LoginInitBlock(this.#corbadoApp, this, common, this.#errorTranslator, blockBody);
break;
case BlockType.PasskeyAppended:
block = new PasskeyAppendedBlock(this.#corbadoApp, this, common, this.#errorTranslator, blockBody);
break;
case BlockType.PostSignupEmailVerify:
case BlockType.EmailVerify:
block = EmailVerifyBlock.fromBackend(
this.#corbadoApp,
this,
common,
this.#errorTranslator,
blockBody.data as GeneralBlockVerifyIdentifier,
blockBody.authType,
);
break;
case BlockType.PhoneVerify:
block = new PhoneVerifyBlock(this.#corbadoApp, this, common, this.#errorTranslator, blockBody);
break;
case BlockType.Completed:
block = new CompletedBlock(this.#corbadoApp, this, common, this.#errorTranslator, blockBody);
break;
case BlockType.PasskeyVerify:
block = new PasskeyVerifyBlock(this.#corbadoApp, this, common, this.#errorTranslator, blockBody);
break;
//TODO: Add MissingFieldsBlock
// case BlockType.MissingFields:
// block = new MissingFieldsBlock(this.#corbadoApp, this, common, this.#errorTranslator, blockBody);
// break;
default:
throw new Error(`Invalid block type: ${blockBody.block}}`);
}
if (blockBody.error) {
block.setError(blockBody.error);
}
return block;
};
}