@nymphjs/tilmeld-client 1.0.0-beta.14 → 1.0.0-beta.141

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