-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauthMachine.ts
More file actions
326 lines (292 loc) · 8.54 KB
/
authMachine.ts
File metadata and controls
326 lines (292 loc) · 8.54 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
/**
* @file Authentication State Machine Example
* @description Demonstrates all primitives: transitionTo, guarded, invoke, describe, action
*
* This example shows a complete authentication flow with:
* - Login/logout transitions
* - Session management
* - Permission guards
* - Async token refresh
* - Logging actions
*/
import { MachineBase } from '../src/index';
import { transitionTo, guard, invoke, describe, action } from '../src/primitives';
// =============================================================================
// CONTEXT TYPES
// =============================================================================
interface LoggedOutContext {
status: 'loggedOut';
lastError?: string;
}
interface LoggingInContext {
status: 'loggingIn';
username: string;
}
interface LoggedInContext {
status: 'loggedIn';
username: string;
token: string;
permissions: string[];
sessionExpiresAt: number;
}
interface SessionExpiredContext {
status: 'sessionExpired';
username: string;
permissions: string[];
}
interface ErrorContext {
status: 'error';
error: string;
previousState: 'loggedOut' | 'loggingIn' | 'loggedIn';
}
// =============================================================================
// STATE MACHINE CLASSES
// =============================================================================
/**
* Initial state - user is logged out
*/
export class LoggedOutMachine extends MachineBase<LoggedOutContext> {
constructor(context: LoggedOutContext = { status: 'loggedOut' }) {
super(context);
}
/**
* Initiate login process
* Transitions to LoggingIn state to perform async authentication
*/
login = describe(
'Start the login process with username and password',
action(
{ name: 'logLoginAttempt', description: 'Log authentication attempt for analytics' },
transitionTo(LoggingInMachine, (username: string, _password: string) => {
return new LoggingInMachine({
status: 'loggingIn',
username,
});
})
)
);
}
/**
* Intermediate state - authentication in progress
*/
export class LoggingInMachine extends MachineBase<LoggingInContext> {
constructor(context: LoggingInContext) {
super(context);
}
/**
* Perform async authentication
* On success: transition to LoggedIn
* On error: transition to Error
*/
authenticate = describe(
'Perform async authentication with the server',
invoke(
{
src: 'authenticateUser',
onDone: LoggedInMachine,
onError: ErrorMachine,
description: 'Call authentication API and retrieve user session token',
},
async ({ signal }) => {
// Simulate API call with AbortSignal support
await new Promise((resolve, reject) => {
const timeout = setTimeout(resolve, 1000);
// Handle cancellation
signal.addEventListener('abort', () => {
clearTimeout(timeout);
reject(new Error('Authentication cancelled'));
});
});
// Check if operation was cancelled
if (signal.aborted) {
throw new Error('Authentication cancelled');
}
// Simulate successful auth
const token = 'mock-jwt-token-' + Date.now();
const permissions = ['read', 'write'];
const sessionExpiresAt = Date.now() + 3600000; // 1 hour
return new LoggedInMachine({
status: 'loggedIn',
username: this.context.username,
token,
permissions,
sessionExpiresAt,
});
}
)
);
/**
* Cancel login attempt
*/
cancel = describe(
'Cancel the login process and return to logged out state',
action(
{ name: 'logLoginCanceled', description: 'Track canceled login attempts' },
transitionTo(LoggedOutMachine, () => {
return new LoggedOutMachine({ status: 'loggedOut' });
})
)
);
}
/**
* Authenticated state - user has valid session
*/
export class LoggedInMachine extends MachineBase<LoggedInContext> {
constructor(context: LoggedInContext) {
super(context);
}
/**
* Log out - clear session and return to logged out state
*/
logout = describe(
'Log out the current user and clear session data',
action(
{ name: 'clearSessionData', description: 'Clear tokens and session from storage' },
transitionTo(LoggedOutMachine, () => {
return new LoggedOutMachine({ status: 'loggedOut' });
})
)
);
/**
* Delete account - only allowed for users with admin permissions
*/
deleteAccount = describe(
'Delete the user account (admin only)',
guard(
(ctx) => ctx.permissions.includes('admin'), // Synchronous permission check
action(
{ name: 'logAccountDeletion', description: 'Audit log for account deletion' },
transitionTo(LoggedOutMachine, () => {
return new LoggedOutMachine({
status: 'loggedOut',
lastError: undefined,
});
})
),
{
onFail: 'throw',
errorMessage: 'Admin permission required to delete accounts',
description: 'User must have admin permission to delete accounts'
}
)
);
/**
* Refresh session token before expiration
*/
refreshToken = describe(
'Refresh the authentication token to extend session',
invoke(
{
src: 'refreshAuthToken',
onDone: LoggedInMachine,
onError: SessionExpiredMachine,
description: 'Call token refresh endpoint with current token',
},
async ({ signal }) => {
// Simulate token refresh API call with AbortSignal support
await new Promise((resolve, reject) => {
const timeout = setTimeout(resolve, 500);
// Handle cancellation
signal.addEventListener('abort', () => {
clearTimeout(timeout);
reject(new Error('Token refresh cancelled'));
});
});
// Check if operation was cancelled
if (signal.aborted) {
throw new Error('Token refresh cancelled');
}
const newToken = 'refreshed-jwt-token-' + Date.now();
const newExpiresAt = Date.now() + 3600000; // 1 hour from now
return new LoggedInMachine({
...this.context,
token: newToken,
sessionExpiresAt: newExpiresAt,
});
}
)
);
/**
* Session expires naturally (timeout)
*/
onSessionExpired = describe(
'Handle session expiration timeout',
transitionTo(SessionExpiredMachine, () => {
return new SessionExpiredMachine({
status: 'sessionExpired',
username: this.context.username,
permissions: this.context.permissions,
});
})
);
}
/**
* Session expired state - token is no longer valid
*/
export class SessionExpiredMachine extends MachineBase<SessionExpiredContext> {
constructor(context: SessionExpiredContext) {
super(context);
}
/**
* Re-authenticate with stored credentials
*/
reAuthenticate = describe(
'Re-authenticate the user after session expiration',
transitionTo(LoggingInMachine, (password: string) => {
return new LoggingInMachine({
status: 'loggingIn',
username: this.context.username,
});
})
);
/**
* Give up and log out completely
*/
logout = describe(
'Log out after session expiration',
transitionTo(LoggedOutMachine, () => {
return new LoggedOutMachine({ status: 'loggedOut' });
})
);
}
/**
* Error state - authentication or session errors
*/
export class ErrorMachine extends MachineBase<ErrorContext> {
constructor(context: ErrorContext) {
super(context);
}
/**
* Retry the failed operation
*/
retry = describe(
'Retry the failed authentication or session operation',
transitionTo(LoggingInMachine, (username: string) => {
return new LoggingInMachine({
status: 'loggingIn',
username,
});
})
);
/**
* Give up and return to logged out state
*/
dismiss = describe(
'Dismiss the error and return to logged out state',
transitionTo(LoggedOutMachine, () => {
return new LoggedOutMachine({
status: 'loggedOut',
lastError: this.context.error,
});
})
);
}
// =============================================================================
// FACTORY FUNCTION (for easier instantiation)
// =============================================================================
/**
* Create a new authentication machine in the logged out state
*/
export function createAuthMachine(): LoggedOutMachine {
return new LoggedOutMachine({ status: 'loggedOut' });
}