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

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.
@@ -0,0 +1,13 @@
1
+ import { Group } from './Group.js';
2
+ import { User } from './User.js';
3
+
4
+ export interface AccessControlData {
5
+ user?: User;
6
+ group?: Group;
7
+ acUser?: number;
8
+ acGroup?: number;
9
+ acOther?: number;
10
+ acFull?: string[];
11
+ acWrite?: string[];
12
+ acRead?: string[];
13
+ }
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,28 +198,36 @@ 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
+ constructor() {
214
+ super();
215
+
216
+ this.enabled = true;
217
+ (this as CurrentUserData).abilities = [];
218
+ (this as CurrentUserData).groups = [];
219
+ (this as CurrentUserData).inheritAbilities = true;
220
+ }
221
+
222
+ public async $checkUsername(): Promise<{ result: boolean; message: string }> {
213
223
  return await this.$serverCall('$checkUsername', [], true);
214
224
  }
215
225
 
216
- public async $checkEmail(): Promise<{
217
- result: boolean;
218
- message: string;
219
- }> {
226
+ public async $checkEmail(): Promise<{ result: boolean; message: string }> {
220
227
  return await this.$serverCall('$checkEmail', [], true);
221
228
  }
222
229
 
223
- public async $checkPhone(): Promise<{
224
- result: boolean;
225
- message: string;
226
- }> {
230
+ public async $checkPhone(): Promise<{ result: boolean; message: string }> {
227
231
  return await this.$serverCall('$checkPhone', [], true);
228
232
  }
229
233
 
@@ -238,7 +242,7 @@ export default class User extends Entity<UserData> {
238
242
  const store = User.stores.get(this.$nymph);
239
243
  if (store == null) {
240
244
  throw new Error(
241
- 'This user class was never initialized with an instance of Nymph'
245
+ 'This user class was never initialized with an instance of Nymph',
242
246
  );
243
247
  }
244
248
 
@@ -257,11 +261,31 @@ export default class User extends Entity<UserData> {
257
261
  return response;
258
262
  }
259
263
 
264
+ public async $switchUser(data?: {
265
+ additionalData?: { [k: string]: any };
266
+ }): Promise<{ result: boolean; message: string }> {
267
+ const store = User.stores.get(this.$nymph);
268
+ if (store == null) {
269
+ throw new Error(
270
+ 'This user class was never initialized with an instance of Nymph',
271
+ );
272
+ }
273
+
274
+ const response = await this.$serverCall('$switchUser', [data]);
275
+ if (response.result) {
276
+ (this.constructor as typeof User).handleToken();
277
+ for (let i = 0; i < store.loginCallbacks.length; i++) {
278
+ store.loginCallbacks[i] && store.loginCallbacks[i](this);
279
+ }
280
+ }
281
+ return response;
282
+ }
283
+
260
284
  public async $logout(): Promise<{ result: boolean; message: string }> {
261
285
  const store = User.stores.get(this.$nymph);
262
286
  if (store == null) {
263
287
  throw new Error(
264
- 'This user class was never initialized with an instance of Nymph'
288
+ 'This user class was never initialized with an instance of Nymph',
265
289
  );
266
290
  }
267
291
 
@@ -282,18 +306,54 @@ export default class User extends Entity<UserData> {
282
306
  public async $changePassword(data: {
283
307
  newPassword: string;
284
308
  currentPassword: string;
309
+ revokeCurrentTokens?: boolean;
285
310
  }): Promise<{ result: boolean; message: string }> {
286
311
  return await this.$serverCall('$changePassword', [data]);
287
312
  }
288
313
 
314
+ public async $revokeCurrentTokens(data?: {
315
+ password: string;
316
+ }): Promise<{ result: boolean; message: string }> {
317
+ return await this.$serverCall('$revokeCurrentTokens', [data]);
318
+ }
319
+
320
+ public async $hasTOTPSecret(): Promise<boolean> {
321
+ return await this.$serverCall('$hasTOTPSecret', [], true);
322
+ }
323
+
324
+ public async $getNewTOTPSecret(): Promise<{
325
+ uri: string;
326
+ qrcode: string;
327
+ secret: string;
328
+ }> {
329
+ return await this.$serverCall('$getNewTOTPSecret', [], true);
330
+ }
331
+
332
+ public async $saveTOTPSecret(data: {
333
+ password: string;
334
+ secret: string;
335
+ code: string;
336
+ }): Promise<{ result: boolean; message: string }> {
337
+ return await this.$serverCall('$saveTOTPSecret', [data]);
338
+ }
339
+
340
+ public async $removeTOTPSecret(data?: {
341
+ password: string;
342
+ code: string;
343
+ }): Promise<{ result: boolean; message: string }> {
344
+ return await this.$serverCall('$removeTOTPSecret', [
345
+ ...(data ? [data] : []),
346
+ ]);
347
+ }
348
+
289
349
  public static async current(
290
- returnObjectIfNotExist: true
350
+ returnObjectIfNotExist: true,
291
351
  ): Promise<User & CurrentUserData>;
292
352
  public static async current(
293
- returnObjectIfNotExist?: false
353
+ returnObjectIfNotExist?: false,
294
354
  ): Promise<(User & CurrentUserData) | null>;
295
355
  public static async current(
296
- returnObjectIfNotExist?: boolean
356
+ returnObjectIfNotExist?: boolean,
297
357
  ): Promise<(User & CurrentUserData) | null> {
298
358
  const currentUser = await this.serverCallStatic('current', [false]);
299
359
  if (currentUser == null) {
@@ -305,16 +365,18 @@ export default class User extends Entity<UserData> {
305
365
  public static async loginUser(data: {
306
366
  username: string;
307
367
  password: string;
368
+ code?: string;
308
369
  additionalData?: { [k: string]: any };
309
370
  }): Promise<{
310
371
  result: boolean;
311
372
  message: string;
373
+ needTOTP?: true;
312
374
  user?: User & CurrentUserData;
313
375
  }> {
314
376
  const store = User.stores.get(this.nymph);
315
377
  if (store == null) {
316
378
  throw new Error(
317
- 'This user class was never initialized with an instance of Nymph'
379
+ 'This user class was never initialized with an instance of Nymph',
318
380
  );
319
381
  }
320
382
 
@@ -347,7 +409,7 @@ export default class User extends Entity<UserData> {
347
409
  const store = User.stores.get(this.nymph);
348
410
  if (store == null) {
349
411
  throw new Error(
350
- 'This user class was never initialized with an instance of Nymph'
412
+ 'This user class was never initialized with an instance of Nymph',
351
413
  );
352
414
  }
353
415
 
@@ -357,7 +419,7 @@ export default class User extends Entity<UserData> {
357
419
  if (!store.clientConfigPromise) {
358
420
  store.clientConfigPromise = this.serverCallStatic(
359
421
  'getClientConfig',
360
- []
422
+ [],
361
423
  ).then((config) => {
362
424
  store.clientConfig = config;
363
425
  store.clientConfigPromise = undefined;
@@ -368,27 +430,47 @@ export default class User extends Entity<UserData> {
368
430
  }
369
431
 
370
432
  private static handleToken(response?: Response) {
433
+ const store = User.stores.get(this.nymph);
434
+
435
+ if (store == null) {
436
+ throw new Error(
437
+ 'This user class was never initialized with an instance of Nymph',
438
+ );
439
+ }
440
+
371
441
  let token: string | null = null;
442
+ let switchToken: string | null = null;
443
+ let hasNoCookie =
444
+ typeof document === 'undefined' || typeof document.cookie === 'undefined';
372
445
  const authCookiePattern =
373
446
  /(?:(?:^|.*;\s*)TILMELDAUTH\s*=\s*([^;]*).*$)|^.*$/;
447
+ const switchCookiePattern =
448
+ /(?:(?:^|.*;\s*)TILMELDSWITCH\s*=\s*([^;]*).*$)|^.*$/;
374
449
  if (response && response.headers.has('X-TILMELDAUTH')) {
375
450
  token = response.headers.get('X-TILMELDAUTH');
451
+ switchToken = response.headers.get('X-TILMELDSWITCH');
376
452
  } else if (
377
453
  typeof document !== 'undefined' &&
378
454
  document.cookie.match(authCookiePattern)
379
455
  ) {
380
456
  token = document.cookie.replace(authCookiePattern, '$1');
457
+ switchToken = document.cookie.replace(switchCookiePattern, '$1');
381
458
  } else {
382
459
  return;
383
460
  }
384
- if (currentToken !== token) {
461
+ if (store.currentToken != token || store.switchToken != switchToken) {
385
462
  if (token == null || token === '') {
386
- if (currentToken != null) {
387
- this.nymph.setXsrfToken(null);
463
+ if (store.currentToken != null) {
464
+ delete this.nymph.headers['X-Xsrf-Token'];
465
+ delete this.nymph.headers['X-TILMELDAUTH'];
466
+ delete this.nymph.headers['X-TILMELDSWITCH'];
388
467
  if (this.nymph.pubsub) {
389
- this.nymph.pubsub.setToken(null);
468
+ this.nymph.pubsub.authenticate(null);
390
469
  }
391
- currentToken = null;
470
+ // Make sure entities requested under a previous user are not reused.
471
+ this.nymph.clearCaches();
472
+ delete store.currentToken;
473
+ delete store.switchToken;
392
474
  }
393
475
  } else {
394
476
  const base64Url = token.split('.')[1];
@@ -398,11 +480,21 @@ export default class User extends Entity<UserData> {
398
480
  ? Buffer.from(base64, 'base64').toString('binary') // node
399
481
  : atob(base64); // browser
400
482
  const jwt = JSON.parse(json);
401
- this.nymph.setXsrfToken(jwt.xsrfToken);
483
+ this.nymph.headers['X-Xsrf-Token'] = jwt.xsrfToken;
484
+ if (hasNoCookie) {
485
+ this.nymph.headers['X-TILMELDAUTH'] = token;
486
+ delete this.nymph.headers['X-TILMELDSWITCH'];
487
+ if (switchToken != null) {
488
+ this.nymph.headers['X-TILMELDSWITCH'] = switchToken;
489
+ }
490
+ }
402
491
  if (this.nymph.pubsub) {
403
- this.nymph.pubsub.setToken(token);
492
+ this.nymph.pubsub.authenticate(token, switchToken);
404
493
  }
405
- currentToken = token;
494
+ // Make sure entities requested under a previous user are not reused.
495
+ this.nymph.clearCaches();
496
+ store.currentToken = token;
497
+ store.switchToken = switchToken ?? undefined;
406
498
  }
407
499
  }
408
500
  }
@@ -412,25 +504,25 @@ export default class User extends Entity<UserData> {
412
504
  callback: T extends 'register'
413
505
  ? RegisterCallback
414
506
  : T extends 'login'
415
- ? LoginCallback
416
- : T extends 'logout'
417
- ? LogoutCallback
418
- : never
507
+ ? LoginCallback
508
+ : T extends 'logout'
509
+ ? LogoutCallback
510
+ : never,
419
511
  ) {
420
512
  const store = User.stores.get(this.nymph);
421
513
  if (store == null) {
422
514
  throw new Error(
423
- 'This user class was never initialized with an instance of Nymph'
515
+ 'This user class was never initialized with an instance of Nymph',
424
516
  );
425
517
  }
426
518
 
427
519
  const prop = (event + 'Callbacks') as T extends 'register'
428
520
  ? 'registerCallbacks'
429
521
  : T extends 'login'
430
- ? 'loginCallbacks'
431
- : T extends 'logout'
432
- ? 'logoutCallbacks'
433
- : never;
522
+ ? 'loginCallbacks'
523
+ : T extends 'logout'
524
+ ? 'logoutCallbacks'
525
+ : never;
434
526
  if (!(prop in store)) {
435
527
  throw new Error('Invalid event type.');
436
528
  }
@@ -444,25 +536,25 @@ export default class User extends Entity<UserData> {
444
536
  callback: T extends 'register'
445
537
  ? RegisterCallback
446
538
  : T extends 'login'
447
- ? LoginCallback
448
- : T extends 'logout'
449
- ? LogoutCallback
450
- : never
539
+ ? LoginCallback
540
+ : T extends 'logout'
541
+ ? LogoutCallback
542
+ : never,
451
543
  ) {
452
544
  const store = User.stores.get(this.nymph);
453
545
  if (store == null) {
454
546
  throw new Error(
455
- 'This user class was never initialized with an instance of Nymph'
547
+ 'This user class was never initialized with an instance of Nymph',
456
548
  );
457
549
  }
458
550
 
459
551
  const prop = (event + 'Callbacks') as T extends 'register'
460
552
  ? 'registerCallbacks'
461
553
  : T extends 'login'
462
- ? 'loginCallbacks'
463
- : T extends 'logout'
464
- ? 'logoutCallbacks'
465
- : never;
554
+ ? 'loginCallbacks'
555
+ : T extends 'logout'
556
+ ? 'logoutCallbacks'
557
+ : never;
466
558
  if (!(prop in store)) {
467
559
  return false;
468
560
  }
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;