@nymphjs/tilmeld-client 1.0.0-beta.15 → 1.0.0-beta.150

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.
package/src/User.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { Nymph, Entity } from '@nymphjs/client';
2
2
 
3
- import type Group from './Group';
4
- import type { AdminGroupData, CurrentGroupData } from './Group';
3
+ import type { Group, AdminGroupData, CurrentGroupData } from './Group.js';
4
+ import { LDAPSource } from './LDAPSource.js';
5
5
 
6
6
  export type EventType = 'register' | 'login' | 'logout';
7
7
  export type RegisterCallback = (user: User & CurrentUserData) => void;
8
8
  export type LoginCallback = (user: User & CurrentUserData) => void;
9
- export type LogoutCallback = (user: User & UserData) => void;
9
+ export type LogoutCallback = (user: User) => void;
10
10
 
11
11
  export type ClientConfig = {
12
12
  regFields: string[];
@@ -19,7 +19,7 @@ export type ClientConfig = {
19
19
  unverifiedAccess: boolean;
20
20
  };
21
21
 
22
- export type UserData = {
22
+ export interface UserData {
23
23
  /**
24
24
  * The user's username.
25
25
  */
@@ -49,9 +49,9 @@ export type UserData = {
49
49
  * Whether the user can log in.
50
50
  */
51
51
  enabled?: boolean;
52
- };
52
+ }
53
53
 
54
- export type CurrentUserData = UserData & {
54
+ export interface CurrentUserData extends UserData {
55
55
  /**
56
56
  * The abilities granted to the user.
57
57
  */
@@ -76,9 +76,14 @@ export type CurrentUserData = UserData & {
76
76
  * Whether the user should inherit the abilities of his groups.
77
77
  */
78
78
  inheritAbilities?: boolean;
79
- };
79
+ /**
80
+ * If the user has changed their email address, this is the new one, awaiting
81
+ * verification.
82
+ */
83
+ newEmailAddress?: string;
84
+ }
80
85
 
81
- export type AdminUserData = CurrentUserData & {
86
+ export interface AdminUserData extends CurrentUserData {
82
87
  /**
83
88
  * The user's primary group.
84
89
  */
@@ -123,9 +128,17 @@ export type AdminUserData = CurrentUserData & {
123
128
  * Used by admins to change a user's password. Not saved to the database.
124
129
  */
125
130
  passwordTemp?: string;
126
- };
131
+ /**
132
+ * If set, this timestamp is the cutoff point for JWT issue dates. Any token
133
+ * issued before this date will not authenticate the user.
134
+ */
135
+ revokeTokenDate?: number;
127
136
 
128
- let currentToken: string | null = null;
137
+ /**
138
+ * The source of this user.
139
+ */
140
+ source?: LDAPSource;
141
+ }
129
142
 
130
143
  type InstanceStore = {
131
144
  registerCallbacks: RegisterCallback[];
@@ -134,9 +147,13 @@ type InstanceStore = {
134
147
  clientConfig?: ClientConfig;
135
148
  clientConfigPromise?: Promise<ClientConfig>;
136
149
  removeNymphResponseListener?: () => void;
150
+ currentToken?: string;
151
+ switchToken?: string;
137
152
  };
138
153
 
139
- export default class User extends Entity<UserData> {
154
+ export interface User extends UserData {}
155
+
156
+ export class User extends Entity<UserData> {
140
157
  protected static stores = new WeakMap<Nymph, InstanceStore>();
141
158
 
142
159
  // The name of the server class
@@ -163,27 +180,12 @@ export default class User extends Entity<UserData> {
163
180
  store.removeNymphResponseListener();
164
181
  }
165
182
  store.removeNymphResponseListener = nymph.on('response', (response) =>
166
- this.handleToken(response)
183
+ this.handleToken(response),
167
184
  );
168
185
  this.handleToken();
169
186
  }
170
187
 
171
- constructor(guid?: string) {
172
- super(guid);
173
-
174
- if (guid == null) {
175
- this.$data.enabled = true;
176
- (this.$data as CurrentUserData).abilities = [];
177
- (this.$data as CurrentUserData).groups = [];
178
- (this.$data as CurrentUserData).inheritAbilities = true;
179
- }
180
- }
181
-
182
- static async factory(guid?: string): Promise<User & UserData> {
183
- return (await super.factory(guid)) as User & UserData;
184
- }
185
-
186
- static async factoryUsername(username?: string): Promise<User & UserData> {
188
+ static async factoryUsername(username?: string): Promise<User> {
187
189
  const entity = new this();
188
190
  if (username != null) {
189
191
  const entity = await this.nymph.getEntity(
@@ -193,7 +195,7 @@ export default class User extends Entity<UserData> {
193
195
  {
194
196
  type: '&',
195
197
  ilike: ['username', username.replace(/([\\%_])/g, (s) => `\\${s}`)],
196
- }
198
+ },
197
199
  );
198
200
  if (entity != null) {
199
201
  return entity;
@@ -202,33 +204,50 @@ export default class User extends Entity<UserData> {
202
204
  return entity;
203
205
  }
204
206
 
205
- static factorySync(guid?: string): User & UserData {
206
- return super.factorySync(guid) as User & UserData;
207
+ static async getDomainUsers(
208
+ domain: string,
209
+ options?: {
210
+ limit?: number;
211
+ offset?: number;
212
+ sort?: string;
213
+ reverse?: boolean;
214
+ },
215
+ ): Promise<User[]> {
216
+ return await this.serverCallStatic('getDomainUsers', [domain, options]);
207
217
  }
208
218
 
209
- public async $checkUsername(): Promise<{
210
- result: boolean;
211
- message: string;
212
- }> {
213
- return await this.$serverCall('$checkUsername', [], true);
219
+ constructor() {
220
+ super();
221
+
222
+ this.enabled = true;
223
+ (this as User & CurrentUserData).abilities = [];
224
+ (this as User & CurrentUserData).groups = [];
225
+ (this as User & CurrentUserData).inheritAbilities = true;
226
+ this.$markClean();
214
227
  }
215
228
 
216
- public async $checkEmail(): Promise<{
217
- result: boolean;
218
- message: string;
219
- }> {
220
- return await this.$serverCall('$checkEmail', [], true);
229
+ public async $checkUsername(): Promise<{ result: boolean; message: string }> {
230
+ return await this.$serverCall('$checkUsername', [], {
231
+ pushState: true,
232
+ });
221
233
  }
222
234
 
223
- public async $checkPhone(): Promise<{
224
- result: boolean;
225
- message: string;
226
- }> {
227
- return await this.$serverCall('$checkPhone', [], true);
235
+ public async $checkEmail(): Promise<{ result: boolean; message: string }> {
236
+ return await this.$serverCall('$checkEmail', [], {
237
+ pushState: true,
238
+ });
239
+ }
240
+
241
+ public async $checkPhone(): Promise<{ result: boolean; message: string }> {
242
+ return await this.$serverCall('$checkPhone', [], {
243
+ pushState: true,
244
+ });
228
245
  }
229
246
 
230
247
  public async $getAvatar(): Promise<string> {
231
- return await this.$serverCall('$getAvatar', [], true);
248
+ return await this.$serverCall('$getAvatar', [], {
249
+ pushState: true,
250
+ });
232
251
  }
233
252
 
234
253
  public async $register(data: {
@@ -238,11 +257,14 @@ export default class User extends Entity<UserData> {
238
257
  const store = User.stores.get(this.$nymph);
239
258
  if (store == null) {
240
259
  throw new Error(
241
- 'This user class was never initialized with an instance of Nymph'
260
+ 'This user class was never initialized with an instance of Nymph',
242
261
  );
243
262
  }
244
263
 
245
- const response = await this.$serverCall('$register', [data]);
264
+ const response = await this.$serverCall('$register', [data], {
265
+ pushState: true,
266
+ pullState: true,
267
+ });
246
268
  if (response.result) {
247
269
  for (let i = 0; i < store.registerCallbacks.length; i++) {
248
270
  store.registerCallbacks[i] && store.registerCallbacks[i](this);
@@ -257,11 +279,31 @@ export default class User extends Entity<UserData> {
257
279
  return response;
258
280
  }
259
281
 
282
+ public async $switchUser(data?: {
283
+ additionalData?: { [k: string]: any };
284
+ }): Promise<{ result: boolean; message: string }> {
285
+ const store = User.stores.get(this.$nymph);
286
+ if (store == null) {
287
+ throw new Error(
288
+ 'This user class was never initialized with an instance of Nymph',
289
+ );
290
+ }
291
+
292
+ const response = await this.$serverCall('$switchUser', [data]);
293
+ if (response.result) {
294
+ (this.constructor as typeof User).handleToken();
295
+ for (let i = 0; i < store.loginCallbacks.length; i++) {
296
+ store.loginCallbacks[i] && store.loginCallbacks[i](this);
297
+ }
298
+ }
299
+ return response;
300
+ }
301
+
260
302
  public async $logout(): Promise<{ result: boolean; message: string }> {
261
303
  const store = User.stores.get(this.$nymph);
262
304
  if (store == null) {
263
305
  throw new Error(
264
- 'This user class was never initialized with an instance of Nymph'
306
+ 'This user class was never initialized with an instance of Nymph',
265
307
  );
266
308
  }
267
309
 
@@ -276,24 +318,70 @@ export default class User extends Entity<UserData> {
276
318
  }
277
319
 
278
320
  public async $gatekeeper(ability?: string): Promise<boolean> {
279
- return await this.$serverCall('$gatekeeper', [ability], true);
321
+ return await this.$serverCall('$gatekeeper', [ability]);
280
322
  }
281
323
 
282
324
  public async $changePassword(data: {
283
325
  newPassword: string;
284
326
  currentPassword: string;
327
+ revokeCurrentTokens?: boolean;
328
+ }): Promise<{ result: boolean; message: string }> {
329
+ return await this.$serverCall('$changePassword', [data], {
330
+ pullState: true,
331
+ });
332
+ }
333
+
334
+ public async $revokeCurrentTokens(data?: {
335
+ password: string;
336
+ }): Promise<{ result: boolean; message: string }> {
337
+ return await this.$serverCall('$revokeCurrentTokens', [data], {
338
+ pullState: true,
339
+ });
340
+ }
341
+
342
+ public async $hasTOTPSecret(): Promise<boolean> {
343
+ return await this.$serverCall('$hasTOTPSecret', []);
344
+ }
345
+
346
+ public async $getNewTOTPSecret(): Promise<{
347
+ uri: string;
348
+ qrcode: string;
349
+ secret: string;
350
+ }> {
351
+ return await this.$serverCall('$getNewTOTPSecret', []);
352
+ }
353
+
354
+ public async $saveTOTPSecret(data: {
355
+ password: string;
356
+ secret: string;
357
+ code: string;
358
+ }): Promise<{ result: boolean; message: string }> {
359
+ return await this.$serverCall('$saveTOTPSecret', [data], {
360
+ pullState: true,
361
+ });
362
+ }
363
+
364
+ public async $removeTOTPSecret(data?: {
365
+ password: string;
366
+ code: string;
285
367
  }): Promise<{ result: boolean; message: string }> {
286
- return await this.$serverCall('$changePassword', [data]);
368
+ return await this.$serverCall(
369
+ '$removeTOTPSecret',
370
+ [...(data ? [data] : [])],
371
+ {
372
+ pullState: true,
373
+ },
374
+ );
287
375
  }
288
376
 
289
377
  public static async current(
290
- returnObjectIfNotExist: true
378
+ returnObjectIfNotExist: true,
291
379
  ): Promise<User & CurrentUserData>;
292
380
  public static async current(
293
- returnObjectIfNotExist?: false
381
+ returnObjectIfNotExist?: false,
294
382
  ): Promise<(User & CurrentUserData) | null>;
295
383
  public static async current(
296
- returnObjectIfNotExist?: boolean
384
+ returnObjectIfNotExist?: boolean,
297
385
  ): Promise<(User & CurrentUserData) | null> {
298
386
  const currentUser = await this.serverCallStatic('current', [false]);
299
387
  if (currentUser == null) {
@@ -305,16 +393,18 @@ export default class User extends Entity<UserData> {
305
393
  public static async loginUser(data: {
306
394
  username: string;
307
395
  password: string;
396
+ code?: string;
308
397
  additionalData?: { [k: string]: any };
309
398
  }): Promise<{
310
399
  result: boolean;
311
400
  message: string;
401
+ needTOTP?: true;
312
402
  user?: User & CurrentUserData;
313
403
  }> {
314
404
  const store = User.stores.get(this.nymph);
315
405
  if (store == null) {
316
406
  throw new Error(
317
- 'This user class was never initialized with an instance of Nymph'
407
+ 'This user class was never initialized with an instance of Nymph',
318
408
  );
319
409
  }
320
410
 
@@ -347,7 +437,7 @@ export default class User extends Entity<UserData> {
347
437
  const store = User.stores.get(this.nymph);
348
438
  if (store == null) {
349
439
  throw new Error(
350
- 'This user class was never initialized with an instance of Nymph'
440
+ 'This user class was never initialized with an instance of Nymph',
351
441
  );
352
442
  }
353
443
 
@@ -357,7 +447,7 @@ export default class User extends Entity<UserData> {
357
447
  if (!store.clientConfigPromise) {
358
448
  store.clientConfigPromise = this.serverCallStatic(
359
449
  'getClientConfig',
360
- []
450
+ [],
361
451
  ).then((config) => {
362
452
  store.clientConfig = config;
363
453
  store.clientConfigPromise = undefined;
@@ -368,27 +458,47 @@ export default class User extends Entity<UserData> {
368
458
  }
369
459
 
370
460
  private static handleToken(response?: Response) {
461
+ const store = User.stores.get(this.nymph);
462
+
463
+ if (store == null) {
464
+ throw new Error(
465
+ 'This user class was never initialized with an instance of Nymph',
466
+ );
467
+ }
468
+
371
469
  let token: string | null = null;
470
+ let switchToken: string | null = null;
471
+ let hasNoCookie =
472
+ typeof document === 'undefined' || typeof document.cookie === 'undefined';
372
473
  const authCookiePattern =
373
474
  /(?:(?:^|.*;\s*)TILMELDAUTH\s*=\s*([^;]*).*$)|^.*$/;
475
+ const switchCookiePattern =
476
+ /(?:(?:^|.*;\s*)TILMELDSWITCH\s*=\s*([^;]*).*$)|^.*$/;
374
477
  if (response && response.headers.has('X-TILMELDAUTH')) {
375
- token = response.headers.get('X-TILMELDAUTH');
478
+ token = response.headers.get('X-TILMELDAUTH') || null;
479
+ switchToken = response.headers.get('X-TILMELDSWITCH') || null;
376
480
  } else if (
377
481
  typeof document !== 'undefined' &&
378
482
  document.cookie.match(authCookiePattern)
379
483
  ) {
380
- token = document.cookie.replace(authCookiePattern, '$1');
484
+ token = document.cookie.replace(authCookiePattern, '$1') || null;
485
+ switchToken = document.cookie.replace(switchCookiePattern, '$1') || null;
381
486
  } else {
382
487
  return;
383
488
  }
384
- if (currentToken !== token) {
385
- if (token == null || token === '') {
386
- if (currentToken != null) {
387
- this.nymph.setXsrfToken(null);
489
+ if (store.currentToken != token || store.switchToken != switchToken) {
490
+ if (token == null) {
491
+ if (store.currentToken != null) {
492
+ delete this.nymph.headers['X-Xsrf-Token'];
493
+ delete this.nymph.headers['X-TILMELDAUTH'];
494
+ delete this.nymph.headers['X-TILMELDSWITCH'];
388
495
  if (this.nymph.pubsub) {
389
- this.nymph.pubsub.setToken(null);
496
+ this.nymph.pubsub.authenticate(null);
390
497
  }
391
- currentToken = null;
498
+ // Make sure entities requested under a previous user are not reused.
499
+ this.nymph.clearCaches();
500
+ delete store.currentToken;
501
+ delete store.switchToken;
392
502
  }
393
503
  } else {
394
504
  const base64Url = token.split('.')[1];
@@ -398,11 +508,21 @@ export default class User extends Entity<UserData> {
398
508
  ? Buffer.from(base64, 'base64').toString('binary') // node
399
509
  : atob(base64); // browser
400
510
  const jwt = JSON.parse(json);
401
- this.nymph.setXsrfToken(jwt.xsrfToken);
511
+ this.nymph.headers['X-Xsrf-Token'] = jwt.xsrfToken;
512
+ if (hasNoCookie) {
513
+ this.nymph.headers['X-TILMELDAUTH'] = token;
514
+ delete this.nymph.headers['X-TILMELDSWITCH'];
515
+ if (switchToken != null) {
516
+ this.nymph.headers['X-TILMELDSWITCH'] = switchToken;
517
+ }
518
+ }
402
519
  if (this.nymph.pubsub) {
403
- this.nymph.pubsub.setToken(token);
520
+ this.nymph.pubsub.authenticate(token, switchToken);
404
521
  }
405
- currentToken = token;
522
+ // Make sure entities requested under a previous user are not reused.
523
+ this.nymph.clearCaches();
524
+ store.currentToken = token;
525
+ store.switchToken = switchToken ?? undefined;
406
526
  }
407
527
  }
408
528
  }
@@ -412,25 +532,25 @@ export default class User extends Entity<UserData> {
412
532
  callback: T extends 'register'
413
533
  ? RegisterCallback
414
534
  : T extends 'login'
415
- ? LoginCallback
416
- : T extends 'logout'
417
- ? LogoutCallback
418
- : never
535
+ ? LoginCallback
536
+ : T extends 'logout'
537
+ ? LogoutCallback
538
+ : never,
419
539
  ) {
420
540
  const store = User.stores.get(this.nymph);
421
541
  if (store == null) {
422
542
  throw new Error(
423
- 'This user class was never initialized with an instance of Nymph'
543
+ 'This user class was never initialized with an instance of Nymph',
424
544
  );
425
545
  }
426
546
 
427
547
  const prop = (event + 'Callbacks') as T extends 'register'
428
548
  ? 'registerCallbacks'
429
549
  : T extends 'login'
430
- ? 'loginCallbacks'
431
- : T extends 'logout'
432
- ? 'logoutCallbacks'
433
- : never;
550
+ ? 'loginCallbacks'
551
+ : T extends 'logout'
552
+ ? 'logoutCallbacks'
553
+ : never;
434
554
  if (!(prop in store)) {
435
555
  throw new Error('Invalid event type.');
436
556
  }
@@ -444,25 +564,25 @@ export default class User extends Entity<UserData> {
444
564
  callback: T extends 'register'
445
565
  ? RegisterCallback
446
566
  : T extends 'login'
447
- ? LoginCallback
448
- : T extends 'logout'
449
- ? LogoutCallback
450
- : never
567
+ ? LoginCallback
568
+ : T extends 'logout'
569
+ ? LogoutCallback
570
+ : never,
451
571
  ) {
452
572
  const store = User.stores.get(this.nymph);
453
573
  if (store == null) {
454
574
  throw new Error(
455
- 'This user class was never initialized with an instance of Nymph'
575
+ 'This user class was never initialized with an instance of Nymph',
456
576
  );
457
577
  }
458
578
 
459
579
  const prop = (event + 'Callbacks') as T extends 'register'
460
580
  ? 'registerCallbacks'
461
581
  : T extends 'login'
462
- ? 'loginCallbacks'
463
- : T extends 'logout'
464
- ? 'logoutCallbacks'
465
- : never;
582
+ ? 'loginCallbacks'
583
+ : T extends 'logout'
584
+ ? 'logoutCallbacks'
585
+ : never;
466
586
  if (!(prop in store)) {
467
587
  return false;
468
588
  }
package/src/helpers.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type UserClass from './User';
2
- import type { ClientConfig, CurrentUserData } from './User';
1
+ import type { User as UserClass } from './User.js';
2
+ import type { ClientConfig, CurrentUserData } from './User.js';
3
3
 
4
4
  export type RegistrationDetails = {
5
5
  /**
@@ -40,11 +40,14 @@ export type RegistrationDetails = {
40
40
  additionalData?: { [k: string]: any };
41
41
  };
42
42
 
43
+ export class NeedTOTPError extends Error {}
44
+
43
45
  export async function login(
44
46
  User: typeof UserClass,
45
47
  username: string,
46
48
  password: string,
47
- additionalData?: { [k: string]: any }
49
+ code?: string,
50
+ additionalData?: { [k: string]: any },
48
51
  ) {
49
52
  if (username === '') {
50
53
  throw new Error('You need to enter a username.');
@@ -54,16 +57,24 @@ export async function login(
54
57
  }
55
58
 
56
59
  try {
57
- const { result, ...response } = await User.loginUser({
60
+ const { result, needTOTP, ...response } = await User.loginUser({
58
61
  username,
59
62
  password,
63
+ code,
60
64
  ...(additionalData ? { additionalData } : {}),
61
65
  });
62
66
  if (!result) {
67
+ if (needTOTP) {
68
+ throw new NeedTOTPError(response.message);
69
+ }
70
+
63
71
  throw new Error(response.message);
64
72
  }
65
73
  return response;
66
74
  } catch (e: any) {
75
+ if (e instanceof NeedTOTPError) {
76
+ throw e;
77
+ }
67
78
  throw new Error(e?.message ?? 'An error occurred.');
68
79
  }
69
80
  }
@@ -71,7 +82,7 @@ export async function login(
71
82
  export async function register(
72
83
  User: typeof UserClass,
73
84
  userDetails: RegistrationDetails,
74
- clientConfig?: ClientConfig
85
+ clientConfig?: ClientConfig,
75
86
  ): Promise<{
76
87
  loggedin: boolean;
77
88
  message: string;
@@ -95,16 +106,18 @@ export async function register(
95
106
  user.username = userDetails.username;
96
107
  const config = clientConfig || (await User.getClientConfig());
97
108
 
98
- if (config.emailUsernames) {
99
- user.email = userDetails.username;
100
- } else if (config.regFields.indexOf('email') !== -1) {
101
- user.email = userDetails.email;
109
+ if (config.regFields.includes('email')) {
110
+ if (config.emailUsernames) {
111
+ user.email = userDetails.username;
112
+ } else {
113
+ user.email = userDetails.email;
114
+ }
102
115
  }
103
- if (config.regFields.indexOf('name') !== -1) {
116
+ if (config.regFields.includes('name')) {
104
117
  user.nameFirst = userDetails.nameFirst;
105
118
  user.nameLast = userDetails.nameLast;
106
119
  }
107
- if (config.regFields.indexOf('phone') !== -1) {
120
+ if (config.regFields.includes('phone')) {
108
121
  user.phone = userDetails.phone;
109
122
  }
110
123
 
@@ -127,7 +140,7 @@ export async function register(
127
140
  export async function checkUsername(
128
141
  User: typeof UserClass,
129
142
  username: string,
130
- clientConfig?: ClientConfig
143
+ clientConfig?: ClientConfig,
131
144
  ) {
132
145
  let user = User.factorySync() as UserClass & CurrentUserData;
133
146
  user.username = username;