@nymphjs/tilmeld 1.0.0-beta.12 → 1.0.0-beta.121

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.
Files changed (93) hide show
  1. package/CHANGELOG.md +550 -0
  2. package/README.md +15 -2
  3. package/dist/AbleObject.d.ts +15 -0
  4. package/dist/AbleObject.js +18 -6
  5. package/dist/AbleObject.js.map +1 -1
  6. package/dist/Group.d.ts +182 -15
  7. package/dist/Group.js +571 -191
  8. package/dist/Group.js.map +1 -1
  9. package/dist/Group.testArtifacts.d.ts +3 -0
  10. package/dist/Group.testArtifacts.js +120 -0
  11. package/dist/Group.testArtifacts.js.map +1 -0
  12. package/dist/Tilmeld.d.ts +241 -12
  13. package/dist/Tilmeld.js +721 -273
  14. package/dist/Tilmeld.js.map +1 -1
  15. package/dist/Tilmeld.types.d.ts +5 -5
  16. package/dist/Tilmeld.types.js +1 -2
  17. package/dist/User.d.ts +396 -22
  18. package/dist/User.js +1386 -367
  19. package/dist/User.js.map +1 -1
  20. package/dist/User.testArtifacts.d.ts +3 -0
  21. package/dist/User.testArtifacts.js +175 -0
  22. package/dist/User.testArtifacts.js.map +1 -0
  23. package/dist/conf/defaults.d.ts +1 -1
  24. package/dist/conf/defaults.js +196 -141
  25. package/dist/conf/defaults.js.map +1 -1
  26. package/dist/conf/index.d.ts +355 -2
  27. package/dist/conf/index.js +2 -8
  28. package/dist/conf/index.js.map +1 -1
  29. package/dist/enforceTilmeld.d.ts +3 -0
  30. package/dist/enforceTilmeld.js +18 -0
  31. package/dist/enforceTilmeld.js.map +1 -0
  32. package/dist/errors/AccessControlError.d.ts +2 -1
  33. package/dist/errors/AccessControlError.js +3 -6
  34. package/dist/errors/AccessControlError.js.map +1 -1
  35. package/dist/errors/BadDataError.d.ts +2 -1
  36. package/dist/errors/BadDataError.js +3 -6
  37. package/dist/errors/BadDataError.js.map +1 -1
  38. package/dist/errors/BadEmailError.d.ts +2 -1
  39. package/dist/errors/BadEmailError.js +3 -6
  40. package/dist/errors/BadEmailError.js.map +1 -1
  41. package/dist/errors/BadUsernameError.d.ts +2 -1
  42. package/dist/errors/BadUsernameError.js +3 -6
  43. package/dist/errors/BadUsernameError.js.map +1 -1
  44. package/dist/errors/CouldNotChangeDefaultPrimaryGroupError.js +1 -5
  45. package/dist/errors/CouldNotChangeDefaultPrimaryGroupError.js.map +1 -1
  46. package/dist/errors/EmailChangeRateLimitExceededError.js +1 -5
  47. package/dist/errors/EmailChangeRateLimitExceededError.js.map +1 -1
  48. package/dist/errors/index.d.ts +6 -6
  49. package/dist/errors/index.js +6 -22
  50. package/dist/errors/index.js.map +1 -1
  51. package/dist/index.d.ts +11 -10
  52. package/dist/index.js +16 -35
  53. package/dist/index.js.map +1 -1
  54. package/dist/testArtifacts.d.ts +19 -0
  55. package/dist/testArtifacts.js +1173 -0
  56. package/dist/testArtifacts.js.map +1 -0
  57. package/dist/tilmeldJoiProps.d.ts +3 -3
  58. package/dist/tilmeldJoiProps.js +13 -18
  59. package/dist/tilmeldJoiProps.js.map +1 -1
  60. package/jest.config.js +31 -5
  61. package/package.json +41 -34
  62. package/src/AbleObject.ts +2 -2
  63. package/src/Group.testArtifacts.ts +159 -0
  64. package/src/Group.ts +684 -225
  65. package/src/Tilmeld.ts +547 -283
  66. package/src/Tilmeld.types.ts +5 -5
  67. package/src/User.testArtifacts.ts +226 -0
  68. package/src/User.ts +1635 -461
  69. package/src/conf/defaults.ts +172 -109
  70. package/src/conf/index.ts +370 -2
  71. package/src/enforceTilmeld.ts +20 -0
  72. package/src/errors/AccessControlError.ts +4 -2
  73. package/src/errors/BadDataError.ts +4 -2
  74. package/src/errors/BadEmailError.ts +4 -2
  75. package/src/errors/BadUsernameError.ts +4 -2
  76. package/src/errors/index.ts +6 -6
  77. package/src/index.ts +12 -10
  78. package/src/testArtifacts.ts +1979 -0
  79. package/src/tilmeldJoiProps.ts +8 -23
  80. package/tsconfig.json +6 -3
  81. package/typedoc.json +4 -0
  82. package/dist/Group.test.d.ts +0 -1
  83. package/dist/Group.test.js +0 -48
  84. package/dist/Group.test.js.map +0 -1
  85. package/dist/User.test.d.ts +0 -1
  86. package/dist/User.test.js +0 -51
  87. package/dist/User.test.js.map +0 -1
  88. package/dist/conf/d.d.ts +0 -55
  89. package/dist/conf/d.js +0 -3
  90. package/dist/conf/d.js.map +0 -1
  91. package/src/Group.test.ts +0 -58
  92. package/src/User.test.ts +0 -61
  93. package/src/conf/d.ts +0 -303
package/dist/Tilmeld.js CHANGED
@@ -1,113 +1,233 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const nymph_1 = require("@nymphjs/nymph");
7
- const url_1 = require("url");
8
- const lodash_1 = require("lodash");
9
- const conf_1 = require("./conf");
10
- const errors_1 = require("./errors");
11
- const Group_1 = __importDefault(require("./Group"));
12
- const User_1 = __importDefault(require("./User"));
13
- class Tilmeld {
1
+ import { URL } from 'node:url';
2
+ import { TilmeldAccessLevels, TilmeldAccessRequest, } from '@nymphjs/nymph';
3
+ import { xor } from 'lodash-es';
4
+ import { splitn } from '@sciactive/splitn';
5
+ import { ConfigDefaults as defaults } from './conf/index.js';
6
+ import { AccessControlError } from './errors/index.js';
7
+ import Group from './Group.js';
8
+ import User from './User.js';
9
+ import { enforceTilmeld } from './enforceTilmeld.js';
10
+ /**
11
+ * A user and group system for Nymph.js.
12
+ *
13
+ * Written by Hunter Perrin for SciActive.
14
+ *
15
+ * @author Hunter Perrin <hperrin@port87.com>
16
+ * @copyright SciActive Inc
17
+ * @see http://nymph.io/
18
+ */
19
+ export default class Tilmeld {
20
+ /**
21
+ * The Nymph instance.
22
+ */
23
+ nymph = {};
24
+ /**
25
+ * The Tilmeld config.
26
+ */
27
+ config;
28
+ /**
29
+ * The currently logged in user.
30
+ */
31
+ currentUser = null;
32
+ /**
33
+ * The user class for this instance of Tilmeld.
34
+ */
35
+ User = User;
36
+ /**
37
+ * The group class for this instance of Tilmeld.
38
+ */
39
+ Group = Group;
40
+ /**
41
+ * If you will be performing authentication functions (logging in/out), you
42
+ * should set these so Tilmeld can read and write cookies and headers.
43
+ *
44
+ * If you want the user to be authenticated with the cookie and/or header they
45
+ * provide, you should set at least the request. It's better to set both, so
46
+ * the JWT can be updated if needed.
47
+ *
48
+ * After you set these, call `authenticate()` to read user authentication data
49
+ * from them and fill the user's session.
50
+ *
51
+ * If you want to support cookie based authentication (which still requires an
52
+ * XSRF token for security), you should enable the cookie parser middleware.
53
+ */
54
+ request = null;
55
+ response = null;
56
+ /**
57
+ * Used to avoid infinite loop.
58
+ */
59
+ alreadyLoggedOutSwitch = false;
60
+ /**
61
+ * Gatekeeper ability cache.
62
+ *
63
+ * Gatekeeper will cache the user's abilities that it calculates, so it can
64
+ * check faster if that user has been checked before.
65
+ */
66
+ gatekeeperCache = null;
67
+ /**
68
+ * Create a new instance of Tilmeld.
69
+ *
70
+ * @param config The Tilmeld configuration.
71
+ */
14
72
  constructor(config) {
15
- this.nymph = {};
16
- this.currentUser = null;
17
- this.User = User_1.default;
18
- this.Group = Group_1.default;
19
- this.request = null;
20
- this.response = null;
21
- this.skipAuthenticate = false;
22
- this.config = { ...conf_1.ConfigDefaults, ...config };
73
+ this.config = { ...defaults, ...config };
74
+ if (this.config.emailUsernames &&
75
+ (!this.config.userFields.includes('email') ||
76
+ !this.config.regFields.includes('email'))) {
77
+ throw new Error('You must include email in userFields and regFields if you use emailUsernames.');
78
+ }
79
+ for (let field of this.config.regFields) {
80
+ if (!this.config.userFields.includes(field)) {
81
+ throw new Error(`All fields in regFields must also be in userFields: ${field}`);
82
+ }
83
+ }
84
+ if (this.config.emailUsernames && this.config.domainSupport) {
85
+ throw new Error('Email usernames and domain support cannot both be enabled.');
86
+ }
23
87
  }
88
+ /**
89
+ * This is used internally by Nymph. Don't call it yourself.
90
+ *
91
+ * @returns A clone of this instance.
92
+ */
24
93
  clone() {
25
94
  const tilmeld = new Tilmeld(this.config);
26
95
  tilmeld.request = this.request;
27
96
  tilmeld.response = this.response;
28
97
  tilmeld.currentUser = this.currentUser;
29
- tilmeld.skipAuthenticate = true;
98
+ tilmeld.gatekeeperCache = this.gatekeeperCache;
30
99
  return tilmeld;
31
100
  }
101
+ /**
102
+ * Initialize Tilmeld.
103
+ *
104
+ * This is meant to be called internally by Nymph. Don't call this directly.
105
+ *
106
+ * @param nymph The Nymph instance.
107
+ */
32
108
  init(nymph) {
33
109
  this.nymph = nymph;
34
- const tilmeld = this;
35
110
  if (this.nymph.driver == null) {
36
111
  throw new Error("Tilmeld can't be configured before Nymph.");
37
112
  }
38
- class NymphUser extends User_1.default {
113
+ // Configure the classes.
114
+ if (nymph.parent) {
115
+ // This is a cloned Nymph, it should have classes already.
116
+ this.User = this.nymph.getEntityClass(User);
117
+ this.Group = this.nymph.getEntityClass(Group);
39
118
  }
40
- NymphUser.nymph = nymph;
41
- NymphUser.tilmeld = tilmeld;
42
- NymphUser.skipOnClone = true;
43
- this.User = this.nymph.addEntityClass(NymphUser);
44
- class NymphGroup extends Group_1.default {
119
+ else {
120
+ // This is a new Nymph, add the classes.
121
+ this.User = this.nymph.addEntityClass(User);
122
+ this.Group = this.nymph.addEntityClass(Group);
45
123
  }
46
- NymphGroup.nymph = nymph;
47
- NymphGroup.tilmeld = tilmeld;
48
- NymphUser.skipOnClone = true;
49
- this.Group = this.nymph.addEntityClass(NymphGroup);
50
- this.initAccessControl();
51
- if (this.request != null && !this.skipAuthenticate) {
52
- this.authenticate();
124
+ // Clone the current user so its Nymph instance is correct.
125
+ if (this.currentUser) {
126
+ const currentUserGUID = this.currentUser.guid;
127
+ const currentUserCDate = this.currentUser.cdate;
128
+ const currentUserMDate = this.currentUser.mdate;
129
+ const currentUserTags = this.currentUser.tags;
130
+ const currentUserData = this.currentUser.$getData();
131
+ const currentUserSData = this.currentUser.$getSData();
132
+ const user = this.User.factorySync();
133
+ user.guid = currentUserGUID;
134
+ user.cdate = currentUserCDate;
135
+ user.mdate = currentUserMDate;
136
+ user.tags = currentUserTags;
137
+ user.$putData(currentUserData, currentUserSData);
138
+ user.$originalEmail = this.currentUser.$originalEmail;
139
+ user.$originalUsername = this.currentUser.$originalUsername;
140
+ this.currentUser = user;
141
+ this.currentUser.$updateDataProtection();
142
+ this.currentUser.$updateGroupDataProtection();
53
143
  }
54
- this.skipAuthenticate = false;
144
+ // Set up access control hooks when Nymph is called.
145
+ this.nymph.config.debugInfo('tilmeld', 'Initializing access controls.');
146
+ this.initAccessControl();
55
147
  }
148
+ /**
149
+ * Check to see if the current user has an ability.
150
+ *
151
+ * If `ability` is undefined, it will check to see if a user is currently
152
+ * logged in.
153
+ *
154
+ * @param ability The ability.
155
+ * @returns Whether the user has the given ability.
156
+ */
56
157
  gatekeeper(ability) {
57
- if (this.currentUser == null) {
158
+ if (this.currentUser == null || this.gatekeeperCache == null) {
58
159
  return false;
59
160
  }
60
- return this.currentUser.$gatekeeper(ability);
161
+ if (ability == null) {
162
+ return true;
163
+ }
164
+ return ((ability in this.gatekeeperCache && !!this.gatekeeperCache[ability]) ||
165
+ !!this.currentUser.abilities?.includes('system/admin'));
61
166
  }
62
167
  initAccessControl() {
168
+ // Check for the skip access control option and add AC selectors.
63
169
  const handleQuery = function (nymph, options, selectors) {
64
- const tilmeld = nymph.tilmeld;
170
+ const tilmeld = enforceTilmeld(nymph);
65
171
  if (!options ||
66
172
  !('skipAc' in options) ||
67
173
  !options.skipAc ||
68
174
  options.source === 'client') {
69
175
  if (options?.source === 'client') {
70
- if (!tilmeld.gatekeeper('tilmeld/admin') &&
176
+ if ((!tilmeld.currentUser ||
177
+ (!tilmeld.currentUser.abilities?.includes('tilmeld/admin') &&
178
+ !tilmeld.currentUser.abilities?.includes('system/admin'))) && // The user is not an admin.
71
179
  ((!tilmeld.config.enableUserSearch &&
72
- options.class?.factorySync() instanceof User_1.default) ||
180
+ options.class?.factorySync() instanceof User) || // The use is searching for a user and searching is disabled.
73
181
  (!tilmeld.config.enableGroupSearch &&
74
- options.class?.factorySync() instanceof Group_1.default)) &&
75
- (selectors[0] == null ||
76
- selectors[0].type !== '&' ||
77
- (!('guid' in selectors[0]) && !('equal' in selectors[0])) ||
182
+ options.class?.factorySync() instanceof Group)) && // Or the same, but for a group.
183
+ (selectors[0] == null || // No selector specified.
184
+ selectors[0].type !== '&' || // Or the type is not and.
185
+ (!('guid' in selectors[0]) && !('equal' in selectors[0])) || // Or they're searching for something other than guid or equal.
78
186
  ('guid' in selectors[0] &&
79
187
  (!selectors[0].guid?.length ||
80
- !selectors[0].guid?.[0]?.length)) ||
188
+ !selectors[0].guid?.[0]?.length)) || // Or they're not searching for a specific guid.
81
189
  ('equal' in selectors[0] &&
82
190
  selectors[0].equal?.[0]?.[0] !== 'username' &&
83
- selectors[0].equal?.[0]?.[0] !== 'groupname'))) {
84
- throw new errors_1.AccessControlError('No permission to search.');
191
+ selectors[0].equal?.[0]?.[0] !== 'groupname')) // Or they're not searching for a specific username/groupname.
192
+ ) {
193
+ // If the user is not specifically searching for a GUID or username,
194
+ // and they're not allowed to search, it should fail.
195
+ throw new AccessControlError('No permission to search.');
85
196
  }
86
197
  }
198
+ // Add access control selectors
87
199
  tilmeld.addAccessControlSelectors(options, selectors);
88
200
  }
89
201
  };
90
202
  handleQuery.skipOnClone = true;
203
+ // Filter entities being deleted for user permissions.
91
204
  const checkPermissionsDelete = async function (nymph, entity) {
92
- const tilmeld = nymph.tilmeld;
205
+ const tilmeld = enforceTilmeld(nymph);
93
206
  if (typeof entity.$tilmeldDeleteSkipAC === 'function' &&
94
207
  entity.$tilmeldDeleteSkipAC()) {
95
208
  return;
96
209
  }
97
- if (!tilmeld.checkPermissions(entity, nymph_1.TilmeldAccessLevels.FULL_ACCESS)) {
98
- throw new errors_1.AccessControlError('No permission to delete.');
210
+ // Test for permissions.
211
+ if (!tilmeld.checkPermissions(entity, TilmeldAccessLevels.FULL_ACCESS)) {
212
+ throw new AccessControlError('No permission to delete.');
99
213
  }
100
214
  };
101
215
  checkPermissionsDelete.skipOnClone = true;
216
+ // Filter entities being deleted for user permissions.
102
217
  const checkPermissionsDeleteByID = async function (nymph, guid, className) {
103
- const entity = nymph.driver.getEntitySync({ class: nymph.getEntityClass(className ?? 'Entity') }, { type: '&', guid: guid });
218
+ if (className === 'User' || className === 'Group') {
219
+ throw new AccessControlError("You can't delete users or groups by ID.");
220
+ }
221
+ const entity = await nymph.getEntity({ class: nymph.getEntityClass(className ?? 'Entity') }, { type: '&', guid: guid });
104
222
  if (entity != null) {
105
223
  checkPermissionsDelete(nymph, entity);
106
224
  }
107
225
  };
108
226
  checkPermissionsDeleteByID.skipOnClone = true;
227
+ // Filter entities being saved for user permissions, and filter any
228
+ // disallowed changes to AC properties.
109
229
  const checkPermissionsSaveAndFilterAcChanges = async function (nymph, entity) {
110
- const tilmeld = nymph.tilmeld;
230
+ const tilmeld = enforceTilmeld(nymph);
111
231
  if (!entity) {
112
232
  return;
113
233
  }
@@ -116,29 +236,10 @@ class Tilmeld {
116
236
  return;
117
237
  }
118
238
  if (entity.guid != null) {
239
+ // If the entity is not new, check that the user has full access before
240
+ // allowing a change to ac properties.
119
241
  const originalAc = entity.$getOriginalAcValues();
120
- const newAc = {
121
- user: entity.user ?? undefined,
122
- group: entity.group ?? undefined,
123
- acUser: entity.acUser ?? undefined,
124
- acGroup: entity.acGroup ?? undefined,
125
- acOther: entity.acOther ?? undefined,
126
- acRead: entity.acRead ?? undefined,
127
- acWrite: entity.acWrite ?? undefined,
128
- acFull: entity.acFull ?? undefined,
129
- };
130
- const setAcProperties = (acValues) => {
131
- for (let name in acValues) {
132
- const value = acValues[name];
133
- if (value == null) {
134
- delete entity[name];
135
- }
136
- else {
137
- entity[name] = value;
138
- }
139
- }
140
- };
141
- setAcProperties(originalAc);
242
+ const newAc = entity.$getCurrentAcValues();
142
243
  function areAcPropertiesChanged(a, b) {
143
244
  for (const name of ['user', 'group']) {
144
245
  const aVal = a[name];
@@ -149,7 +250,7 @@ class Tilmeld {
149
250
  else if (aVal == null || bVal == null) {
150
251
  return true;
151
252
  }
152
- if (!aVal.$is(bVal)) {
253
+ if (aVal !== bVal) {
153
254
  return true;
154
255
  }
155
256
  }
@@ -178,61 +279,77 @@ class Tilmeld {
178
279
  if (aVal.length !== bVal.length) {
179
280
  return true;
180
281
  }
181
- if ((0, lodash_1.xor)(aVal.map((entity) => entity.guid), bVal.map((entity) => entity.guid)).length) {
282
+ if (xor(aVal, bVal).length) {
182
283
  return true;
183
284
  }
184
285
  }
185
286
  return false;
186
287
  }
187
288
  if (areAcPropertiesChanged(originalAc, newAc)) {
188
- if (!tilmeld.checkPermissions(entity, nymph_1.TilmeldAccessLevels.FULL_ACCESS)) {
189
- throw new errors_1.AccessControlError('No permission to change access control properties.');
289
+ if (!tilmeld.checkPermissions(entity, TilmeldAccessLevels.FULL_ACCESS, undefined, originalAc)) {
290
+ // Only allow changes to AC properties if the user has full access.
291
+ throw new AccessControlError('No permission to change access control properties.');
190
292
  }
191
- if (((originalAc.user && !originalAc.user.$is(newAc.user)) ||
192
- (!originalAc.user &&
193
- newAc.user &&
194
- !newAc.user.$is(tilmeld.currentUser))) &&
195
- !tilmeld.gatekeeper('tilmeld/admin')) {
196
- throw new errors_1.AccessControlError('No permission to assign to another user.');
293
+ if ((originalAc.user != null && originalAc.user !== newAc.user) ||
294
+ (originalAc.user == null &&
295
+ newAc.user != null &&
296
+ newAc.user !== tilmeld.currentUser?.guid)) {
297
+ throw new AccessControlError('No permission to assign to another user.');
197
298
  }
198
- if (newAc.group &&
199
- !newAc.group.$is(originalAc.group) &&
200
- !(newAc.group.$is(tilmeld.currentUser?.group) ||
201
- newAc.group.$inArray(tilmeld.currentUser?.groups ?? [])) &&
202
- !tilmeld.gatekeeper('tilmeld/admin')) {
203
- throw new errors_1.AccessControlError('No permission to assign to another group.');
299
+ if (newAc.group != null &&
300
+ newAc.group !== originalAc.group &&
301
+ !(newAc.group === tilmeld.currentUser?.$getGid() ||
302
+ (tilmeld.currentUser?.$getGids() ?? []).includes(newAc.group))) {
303
+ throw new AccessControlError('No permission to assign to another group.');
204
304
  }
205
- setAcProperties(newAc);
206
305
  }
207
306
  }
208
- if (!tilmeld.checkPermissions(entity, nymph_1.TilmeldAccessLevels.WRITE_ACCESS)) {
209
- throw new errors_1.AccessControlError('No permission to write.');
307
+ // Test for permissions.
308
+ if (!tilmeld.checkPermissions(entity, TilmeldAccessLevels.WRITE_ACCESS)) {
309
+ throw new AccessControlError('No permission to write.');
210
310
  }
211
311
  };
212
312
  checkPermissionsSaveAndFilterAcChanges.skipOnClone = true;
313
+ /*
314
+ * Add the current user's "user", "group", and access control to new entity.
315
+ *
316
+ * This occurs right before an entity is saved. It only alters the entity
317
+ * if:
318
+ *
319
+ * - There is a user logged in.
320
+ * - The entity is new (doesn't have a GUID.)
321
+ * - The entity is not a user or group.
322
+ *
323
+ * Default access control is
324
+ *
325
+ * - acUser = TilmeldAccessLevels.FULL_ACCESS
326
+ * - acGroup = TilmeldAccessLevels.READ_ACCESS
327
+ * - acOther = TilmeldAccessLevels.NO_ACCESS
328
+ */
213
329
  const addAccess = async function (nymph, entity) {
214
- const tilmeld = nymph.tilmeld;
330
+ const tilmeld = enforceTilmeld(nymph);
215
331
  const user = tilmeld.currentUser;
216
332
  if (user != null &&
217
333
  entity.guid == null &&
218
- !(entity instanceof User_1.default) &&
219
- !(entity instanceof Group_1.default)) {
334
+ !(entity instanceof User) &&
335
+ !(entity instanceof Group)) {
220
336
  if (entity.user == null) {
221
337
  entity.user = user;
222
338
  }
223
- if (entity.group == null &&
224
- user.group != null &&
225
- user.group.guid != null) {
226
- entity.group = user.group;
339
+ if (entity.group == null) {
340
+ const group = user.group;
341
+ if (group != null && group.guid != null) {
342
+ entity.group = group;
343
+ }
227
344
  }
228
345
  if (entity.acUser == null) {
229
- entity.acUser = nymph_1.TilmeldAccessLevels.FULL_ACCESS;
346
+ entity.acUser = TilmeldAccessLevels.FULL_ACCESS;
230
347
  }
231
348
  if (entity.acGroup == null) {
232
- entity.acGroup = nymph_1.TilmeldAccessLevels.READ_ACCESS;
349
+ entity.acGroup = TilmeldAccessLevels.READ_ACCESS;
233
350
  }
234
351
  if (entity.acOther == null) {
235
- entity.acOther = nymph_1.TilmeldAccessLevels.NO_ACCESS;
352
+ entity.acOther = TilmeldAccessLevels.NO_ACCESS;
236
353
  }
237
354
  if (entity.acRead == null) {
238
355
  entity.acRead = [];
@@ -247,32 +364,32 @@ class Tilmeld {
247
364
  };
248
365
  addAccess.skipOnClone = true;
249
366
  const validate = async function (_nymph, entity) {
250
- if (!(entity instanceof User_1.default) && !(entity instanceof Group_1.default)) {
367
+ if (!(entity instanceof User) && !(entity instanceof Group)) {
251
368
  const ownershipAcPropertyValidator = (prop) => {
252
369
  if (typeof prop != 'number' ||
253
- prop < nymph_1.TilmeldAccessLevels.NO_ACCESS ||
254
- prop > nymph_1.TilmeldAccessLevels.FULL_ACCESS) {
255
- throw new errors_1.AccessControlError('Invalid access control property: ' + prop);
370
+ prop < TilmeldAccessLevels.NO_ACCESS ||
371
+ prop > TilmeldAccessLevels.FULL_ACCESS) {
372
+ throw new AccessControlError('Invalid access control property: ' + prop);
256
373
  }
257
374
  };
258
375
  const accessAcPropertyValidator = (prop) => {
259
376
  if (!Array.isArray(prop)) {
260
- throw new errors_1.AccessControlError('Invalid access control property: ' + prop);
377
+ throw new AccessControlError('Invalid access control property: ' + prop);
261
378
  }
262
379
  prop.forEach((value) => {
263
- if (!(value instanceof User_1.default || value instanceof Group_1.default)) {
264
- throw new errors_1.AccessControlError('Invalid access control property: ' + prop);
380
+ if (typeof value !== 'string' || !value.match(/^[0-9a-f]{24}$/i)) {
381
+ throw new AccessControlError('Invalid access control property: ' + prop);
265
382
  }
266
383
  });
267
384
  };
268
385
  if ('user' in entity) {
269
- if (!(entity.user instanceof User_1.default)) {
270
- throw new errors_1.AccessControlError('Invalid access control property: user');
386
+ if (!(entity.user instanceof User)) {
387
+ throw new AccessControlError('Invalid access control property: user');
271
388
  }
272
389
  }
273
390
  if ('group' in entity) {
274
- if (!(entity.group instanceof Group_1.default)) {
275
- throw new errors_1.AccessControlError('Invalid access control property: group');
391
+ if (!(entity.group instanceof Group)) {
392
+ throw new AccessControlError('Invalid access control property: group');
276
393
  }
277
394
  }
278
395
  if ('acUser' in entity) {
@@ -303,72 +420,114 @@ class Tilmeld {
303
420
  this.nymph.on('beforeDeleteEntity', checkPermissionsDelete);
304
421
  this.nymph.on('beforeDeleteEntityByID', checkPermissionsDeleteByID);
305
422
  }
423
+ /**
424
+ * Add selectors to a list of options and selectors which will limit results
425
+ * to only entities the current user has access to.
426
+ *
427
+ * @param optionsAndSelectors The options and selectors of the query.
428
+ */
306
429
  addAccessControlSelectors(options, selectors) {
307
430
  const user = this.currentUser;
308
- if (user != null &&
309
- (user.abilities?.indexOf('system/admin') ?? -1) !== -1) {
310
- return;
311
- }
312
431
  if (options == null) {
313
432
  throw new Error('No options in argument.');
314
433
  }
315
434
  else if ('class' in options &&
316
- (options.class?.factorySync() instanceof User_1.default ||
317
- options.class?.factorySync() instanceof Group_1.default)) {
435
+ (options.class?.factorySync() instanceof User ||
436
+ options.class?.factorySync() instanceof Group)) {
437
+ // They are requesting a user/group. Always accessible for reading.
318
438
  return;
319
439
  }
320
440
  if (user == null || user.guid == null) {
321
- selectors.push({
322
- type: '|',
323
- gte: [['acOther', nymph_1.TilmeldAccessLevels.READ_ACCESS]],
324
- selector: [
441
+ // Access requests for only public entities.
442
+ const allAccessRequests = TilmeldAccessRequest.OTHER_ACCESSIBLE | TilmeldAccessRequest.UNOWNED;
443
+ const requestedAccess = (options.acRequest ?? 0) & allAccessRequests;
444
+ const defaultAccess = requestedAccess === TilmeldAccessRequest.ALL_LEVELS;
445
+ const selector = { type: '|' };
446
+ if (defaultAccess ||
447
+ requestedAccess & TilmeldAccessRequest.OTHER_ACCESSIBLE) {
448
+ // Other access control is sufficient.
449
+ selector.gte = [['acOther', TilmeldAccessLevels.READ_ACCESS]];
450
+ }
451
+ if (defaultAccess || requestedAccess & TilmeldAccessRequest.UNOWNED) {
452
+ // The user and group are not set.
453
+ selector.selector = [
325
454
  {
326
455
  type: '&',
327
456
  '!defined': [['user', 'group']],
328
457
  },
329
- ],
330
- });
458
+ ];
459
+ }
460
+ if (Object.keys(selector).length <= 1) {
461
+ this.nymph.config.debugError('tilmeld', 'No access controls were added to the query. This should not be possible.');
462
+ throw new Error('Access control error.');
463
+ }
464
+ selectors.push(selector);
331
465
  }
332
466
  else {
333
- const subSelectors = [
334
- {
467
+ // Access requests for public and private entities.
468
+ const allAccessRequests = TilmeldAccessRequest.USER_OWNED |
469
+ TilmeldAccessRequest.PRIMARY_GROUP_OWNED |
470
+ TilmeldAccessRequest.SECONDARY_GROUP_OWNED |
471
+ TilmeldAccessRequest.USER_ACCESSIBLE |
472
+ TilmeldAccessRequest.PRIMARY_GROUP_ACCESSIBLE |
473
+ TilmeldAccessRequest.SECONDARY_GROUP_ACCESSIBLE |
474
+ TilmeldAccessRequest.OTHER_ACCESSIBLE |
475
+ TilmeldAccessRequest.UNOWNED;
476
+ const requestedAccess = (options.acRequest ?? 0) & allAccessRequests;
477
+ const defaultAccess = requestedAccess === TilmeldAccessRequest.ALL_LEVELS;
478
+ const subSelectors = [];
479
+ if (defaultAccess || requestedAccess & TilmeldAccessRequest.UNOWNED) {
480
+ subSelectors.push({
335
481
  type: '&',
482
+ // The user and group are not set.
336
483
  '!defined': [['user', 'group']],
337
- },
338
- {
339
- type: '&',
340
- ref: [['user', user.guid]],
341
- gte: [['acUser', nymph_1.TilmeldAccessLevels.READ_ACCESS]],
342
- },
343
- ];
484
+ });
485
+ }
486
+ // USER_OWNED is always enforced.
487
+ subSelectors.push(
488
+ // It is owned by the user.
489
+ {
490
+ type: '&',
491
+ ref: [['user', user.guid]],
492
+ gte: [['acUser', TilmeldAccessLevels.READ_ACCESS]],
493
+ });
344
494
  const groupRefs = [];
345
- const acRefs = [];
346
- if (user.group != null && user.group.guid != null) {
347
- groupRefs.push(['group', user.group.guid]);
348
- acRefs.push(['acRead', user.group.guid]);
349
- acRefs.push(['acWrite', user.group.guid]);
350
- acRefs.push(['acFull', user.group.guid]);
351
- }
352
- for (let curSecondaryGroup of user.groups ?? []) {
353
- if (curSecondaryGroup != null && curSecondaryGroup.guid != null) {
354
- groupRefs.push(['group', curSecondaryGroup.guid]);
355
- acRefs.push(['acRead', curSecondaryGroup.guid]);
356
- acRefs.push(['acWrite', curSecondaryGroup.guid]);
357
- acRefs.push(['acFull', curSecondaryGroup.guid]);
495
+ const acContains = [];
496
+ const gid = user.$getGid();
497
+ if (gid != null) {
498
+ if (defaultAccess ||
499
+ requestedAccess & TilmeldAccessRequest.PRIMARY_GROUP_OWNED) {
500
+ // It belongs to the user's primary group.
501
+ groupRefs.push(['group', gid]);
502
+ }
503
+ if (defaultAccess ||
504
+ requestedAccess & TilmeldAccessRequest.PRIMARY_GROUP_ACCESSIBLE) {
505
+ // User's primary group guid is listed in acRead, acWrite, or acFull.
506
+ acContains.push(['acRead', gid]);
507
+ acContains.push(['acWrite', gid]);
508
+ acContains.push(['acFull', gid]);
358
509
  }
359
510
  }
360
- for (let curDescendantGroup of user.$getDescendantGroupsSync()) {
361
- if (curDescendantGroup != null && curDescendantGroup.guid != null) {
362
- groupRefs.push(['group', curDescendantGroup.guid]);
363
- acRefs.push(['acRead', curDescendantGroup.guid]);
364
- acRefs.push(['acWrite', curDescendantGroup.guid]);
365
- acRefs.push(['acFull', curDescendantGroup.guid]);
511
+ const gids = user.$getGids();
512
+ for (let curGid of gids ?? []) {
513
+ if (defaultAccess ||
514
+ requestedAccess & TilmeldAccessRequest.SECONDARY_GROUP_OWNED) {
515
+ // It belongs to the user's secondary group.
516
+ groupRefs.push(['group', curGid]);
517
+ }
518
+ if (defaultAccess ||
519
+ requestedAccess & TilmeldAccessRequest.SECONDARY_GROUP_ACCESSIBLE) {
520
+ // User's secondary group guid is listed in acRead, acWrite, or acFull.
521
+ acContains.push(['acRead', curGid]);
522
+ acContains.push(['acWrite', curGid]);
523
+ acContains.push(['acFull', curGid]);
366
524
  }
367
525
  }
526
+ // All the group refs.
368
527
  if (groupRefs.length) {
369
528
  subSelectors.push({
370
529
  type: '&',
371
- gte: [['acGroup', nymph_1.TilmeldAccessLevels.READ_ACCESS]],
530
+ gte: [['acGroup', TilmeldAccessLevels.READ_ACCESS]],
372
531
  selector: [
373
532
  {
374
533
  type: '|',
@@ -377,31 +536,111 @@ class Tilmeld {
377
536
  ],
378
537
  });
379
538
  }
380
- if (acRefs.length) {
539
+ // All the acRead, acWrite, and acFull contains.
540
+ if (acContains.length) {
381
541
  subSelectors.push({
382
542
  type: '|',
383
- ref: acRefs,
543
+ contain: acContains,
384
544
  });
385
545
  }
386
- const selector = {
387
- type: '|',
388
- gte: [['acOther', nymph_1.TilmeldAccessLevels.READ_ACCESS]],
389
- selector: subSelectors,
390
- ref: [
546
+ const selector = { type: '|' };
547
+ if (defaultAccess ||
548
+ requestedAccess & TilmeldAccessRequest.OTHER_ACCESSIBLE) {
549
+ // Other access control is sufficient.
550
+ selector.gte = [['acOther', TilmeldAccessLevels.READ_ACCESS]];
551
+ }
552
+ if (subSelectors.length) {
553
+ // One of the sub selectors.
554
+ selector.selector = subSelectors;
555
+ }
556
+ if (defaultAccess ||
557
+ requestedAccess & TilmeldAccessRequest.USER_ACCESSIBLE) {
558
+ // The user is listed in acRead, acWrite, or acFull.
559
+ selector.contain = [
391
560
  ['acRead', user.guid],
392
561
  ['acWrite', user.guid],
393
562
  ['acFull', user.guid],
394
- ],
395
- };
563
+ ];
564
+ }
565
+ if (Object.keys(selector).length <= 1) {
566
+ this.nymph.config.debugError('tilmeld', 'No access controls were added to the query. This should not be possible.');
567
+ throw new Error('Access control error.');
568
+ }
396
569
  selectors.push(selector);
397
570
  }
398
571
  }
399
- checkPermissions(entity, type = nymph_1.TilmeldAccessLevels.READ_ACCESS, user) {
400
- if (typeof entity !== 'object' || typeof entity.$is !== 'function') {
401
- return false;
572
+ /**
573
+ * Check an entity's permissions for a user.
574
+ *
575
+ * This will check the AC (Access Control) properties of the entity. These
576
+ * include the following properties:
577
+ *
578
+ * - acUser
579
+ * - acGroup
580
+ * - acOther
581
+ * - acRead
582
+ * - acWrite
583
+ * - acFull
584
+ *
585
+ * "acUser" refers to the entity's owner, "acGroup" refers to all users in the
586
+ * entity's group and all ancestor groups, and "acOther" refers to any user
587
+ * who doesn't fit these descriptions.
588
+ *
589
+ * Each of these properties should be either NO_ACCESS, READ_ACCESS,
590
+ * WRITE_ACCESS, or FULL_ACCESS.
591
+ *
592
+ * - NO_ACCESS - the user has no access to the entity.
593
+ * - READ_ACCESS, the user has read access to the entity.
594
+ * - WRITE_ACCESS, the user has read and write access to the entity, but can't
595
+ * delete it, change its access controls, or change its ownership.
596
+ * - FULL_ACCESS, the user has read, write, and delete access to the entity,
597
+ * as well as being able to manage its access controls and ownership.
598
+ *
599
+ * These properties default to:
600
+ *
601
+ * - acUser = TilmeldAccessLevels.FULL_ACCESS
602
+ * - acGroup = TilmeldAccessLevels.READ_ACCESS
603
+ * - acOther = TilmeldAccessLevels.NO_ACCESS
604
+ *
605
+ * "acRead", "acWrite", and "acFull" are arrays of users and/or groups that
606
+ * also have those permissions.
607
+ *
608
+ * Only users with FULL_ACCESS have the ability to change any of the ac*,
609
+ * user, and group properties.
610
+ *
611
+ * The following conditions will result in different checks, which determine
612
+ * whether the check passes:
613
+ *
614
+ * - It is a user or group. (True for READ_ACCESS or Tilmeld admins.)
615
+ * - It is a user or group that belongs to a domain the current user is an
616
+ * admin for, and domain support is enabled. (Always true.)
617
+ * - No user is logged in. (Check other AC.)
618
+ * - The entity is the user. (Always true.)
619
+ * - It is the user's primary group. (True for READ_ACCESS.)
620
+ * - The user or its groups are listed in "acRead". (True for READ_ACCESS.)
621
+ * - The user or its groups are listed in "acWrite". (True for READ_ACCESS and
622
+ * WRITE_ACCESS.)
623
+ * - The user or its groups are listed in "acFull". (Always true.)
624
+ * - Its "user" is the user. (It is owned by the user.) (Check user AC.)
625
+ * - Its "group" is the user's primary group. (Check group AC.)
626
+ * - Its "group" is one of the user's secondary groups. (Check group AC.)
627
+ * - Its "group" is a descendant of one of the user's groups. (Check group
628
+ * AC.)
629
+ * - None of the above. (Check other AC.)
630
+ *
631
+ * @param entity The entity to check.
632
+ * @param type The lowest level of permission to consider a pass.
633
+ * @param user The user to check permissions for. If null, uses the current user. If false, checks for public access.
634
+ * @param acProperties The acProperties to use instead of getting them from the entity.
635
+ * @returns Whether the current user has at least `type` permission for the entity.
636
+ */
637
+ checkPermissions(entity, type = TilmeldAccessLevels.READ_ACCESS, user, acProperties) {
638
+ if (!acProperties) {
639
+ acProperties = entity.$getCurrentAcValues();
402
640
  }
403
641
  let userOrNull = null;
404
642
  let userOrEmpty = this.User.factorySync();
643
+ // Calculate the user.
405
644
  if (user == null) {
406
645
  userOrNull = this.currentUser;
407
646
  userOrEmpty = this.User.current(true);
@@ -410,131 +649,184 @@ class Tilmeld {
410
649
  userOrNull = user;
411
650
  userOrEmpty = user;
412
651
  }
413
- if (userOrEmpty.$gatekeeper('system/admin')) {
652
+ // Users and groups are always readable. Editable by Tilmeld admins.
653
+ if ((entity instanceof User || entity instanceof Group) &&
654
+ (type === TilmeldAccessLevels.READ_ACCESS ||
655
+ userOrEmpty.abilities?.includes('tilmeld/admin') ||
656
+ userOrEmpty.abilities?.includes('system/admin'))) {
414
657
  return true;
415
658
  }
416
- if ((entity instanceof User_1.default || entity instanceof Group_1.default) &&
417
- (type === nymph_1.TilmeldAccessLevels.READ_ACCESS ||
418
- userOrEmpty.$gatekeeper('tilmeld/admin'))) {
419
- return true;
420
- }
421
- if (entity.user == null && entity.group == null) {
422
- return true;
659
+ // Users and groups that belong to a domain are readable and editable by
660
+ // that domain's admins.
661
+ if (this.config.domainSupport &&
662
+ (entity instanceof User || entity instanceof Group)) {
663
+ const [_local, domain] = splitn((entity instanceof User
664
+ ? entity.username
665
+ : entity.groupname) ?? '', '@', 2);
666
+ if (domain &&
667
+ userOrEmpty.abilities?.includes(`tilmeld/domain/${domain}/admin`)) {
668
+ return true;
669
+ }
423
670
  }
424
- const acUser = entity.acUser ?? nymph_1.TilmeldAccessLevels.FULL_ACCESS;
425
- const acGroup = entity.acGroup ?? nymph_1.TilmeldAccessLevels.READ_ACCESS;
426
- const acOther = entity.acOther ?? nymph_1.TilmeldAccessLevels.NO_ACCESS;
427
- if (userOrNull === null) {
671
+ // Load access control, since we need it now...
672
+ const acUser = acProperties.acUser ?? TilmeldAccessLevels.FULL_ACCESS;
673
+ const acGroup = acProperties.acGroup ?? TilmeldAccessLevels.READ_ACCESS;
674
+ const acOther = acProperties.acOther ?? TilmeldAccessLevels.NO_ACCESS;
675
+ if (userOrNull == null) {
428
676
  return acOther >= type;
429
677
  }
678
+ // Check if the entity is the user.
430
679
  if (userOrEmpty.$is(entity)) {
431
680
  return true;
432
681
  }
433
- if (userOrEmpty.group != null &&
434
- typeof userOrEmpty.group.$is === 'function' &&
435
- userOrEmpty.group.$is(entity) &&
436
- type === nymph_1.TilmeldAccessLevels.READ_ACCESS) {
682
+ // Check if the entity is the user's group. Always readable.
683
+ const gid = userOrEmpty.$getGid();
684
+ if (gid != null &&
685
+ entity.guid === gid &&
686
+ type === TilmeldAccessLevels.READ_ACCESS) {
687
+ return true;
688
+ }
689
+ // Check if the entity is one of the user's secondary groups. Always
690
+ // readable.
691
+ const gids = userOrEmpty.$getGids();
692
+ if (gids != null &&
693
+ entity.guid != null &&
694
+ gids.indexOf(entity.guid) !== -1 &&
695
+ type === TilmeldAccessLevels.READ_ACCESS) {
437
696
  return true;
438
697
  }
439
- let allGroups = userOrEmpty.group == null ? [] : [userOrEmpty.group];
440
- allGroups = allGroups.concat(userOrEmpty.groups ?? []);
441
- allGroups = allGroups.concat(userOrEmpty.$getDescendantGroupsSync());
698
+ // At this point, if the entity is a user or group, it should not be
699
+ // accessible.
700
+ if (entity instanceof User || entity instanceof Group) {
701
+ return false;
702
+ }
703
+ // Calculate all the groups the user belongs to.
704
+ let allGids = gid == null ? [] : [gid];
705
+ allGids = allGids.concat(gids ?? []);
706
+ // Check access ac properties.
442
707
  const checks = [
443
708
  {
444
- type: nymph_1.TilmeldAccessLevels.FULL_ACCESS,
445
- array: [...(entity.acFull ?? [])],
709
+ type: TilmeldAccessLevels.FULL_ACCESS,
710
+ array: [...(acProperties.acFull ?? [])],
446
711
  },
447
712
  {
448
- type: nymph_1.TilmeldAccessLevels.WRITE_ACCESS,
449
- array: [...(entity.acWrite ?? [])],
713
+ type: TilmeldAccessLevels.WRITE_ACCESS,
714
+ array: [...(acProperties.acWrite ?? [])],
450
715
  },
451
716
  {
452
- type: nymph_1.TilmeldAccessLevels.READ_ACCESS,
453
- array: [...(entity.acRead ?? [])],
717
+ type: TilmeldAccessLevels.READ_ACCESS,
718
+ array: [...(acProperties.acRead ?? [])],
454
719
  },
455
720
  ];
456
721
  for (let curCheck of checks) {
457
722
  if (type <= curCheck.type) {
458
- if (userOrEmpty.$inArray(curCheck.array)) {
723
+ if (curCheck.array.includes(userOrEmpty.guid)) {
459
724
  return true;
460
725
  }
461
- for (let curGroup of allGroups) {
462
- if (typeof curGroup.$inArray === 'function' &&
463
- curGroup.$inArray(curCheck.array)) {
726
+ for (let curGid of allGids) {
727
+ if (curCheck.array.includes(curGid)) {
464
728
  return true;
465
729
  }
466
730
  }
467
731
  }
468
732
  }
469
- if (entity.user != null &&
470
- typeof entity.user.$is === 'function' &&
471
- entity.user.$is(userOrNull)) {
733
+ // Check ownership ac properties.
734
+ if (acProperties.user != null && acProperties.user === userOrNull.guid) {
472
735
  return acUser >= type;
473
736
  }
474
- if (entity.group != null &&
475
- typeof entity.group.$inArray === 'function' &&
476
- entity.group.$inArray(allGroups)) {
737
+ if (acProperties.group != null && allGids.includes(acProperties.group)) {
477
738
  return acGroup >= type;
478
739
  }
479
740
  return acOther >= type;
480
741
  }
481
- checkClientUIDPermissions(name, type = nymph_1.TilmeldAccessLevels.READ_ACCESS, user) {
742
+ /**
743
+ * Check a UID's permissions for a user.
744
+ *
745
+ * ## THIS ONLY CHECKS AUTOMATICALLY FOR CLIENT REQUESTS.
746
+ *
747
+ * UID functions on the Node.js side are not checked automatically. This
748
+ * function is only run automatically for UID functions run from the client.
749
+ * You should call this function manually if you're running a UID function on
750
+ * the Node.js side and you want it gated.
751
+ *
752
+ * This will check the Tilmeld config and the user's abilities.
753
+ *
754
+ * - READ_ACCESS, the UID is listed in clientReadableUIDs or the user has the
755
+ * "uid/get/nameofuid" ability.
756
+ * - WRITE_ACCESS, the UID is listed in clientEnabledUIDs or the user has the
757
+ * "uid/new/nameofuid" ability.
758
+ * - FULL_ACCESS, the UID is listed in clientSetabledUIDs or the user has the
759
+ * "uid/set/nameofuid" ability.
760
+ *
761
+ * @param name The UID to check.
762
+ * @param type The lowest level of permission to consider a pass.
763
+ * @param user The user to check permissions for. If null, uses the current user. If false, checks for public access.
764
+ * @returns Whether the current user has at least `type` permission for the UID.
765
+ */
766
+ async checkClientUIDPermissions(name, type = TilmeldAccessLevels.READ_ACCESS, user) {
482
767
  let userOrEmpty = this.User.factorySync();
768
+ // Calculate the user.
483
769
  if (user == null) {
484
770
  userOrEmpty = this.User.current(true);
485
771
  }
486
772
  else if (user !== false) {
487
773
  userOrEmpty = user;
488
774
  }
489
- if (userOrEmpty.$gatekeeper('system/admin')) {
775
+ if (userOrEmpty.abilities?.includes('system/admin')) {
490
776
  return true;
491
777
  }
492
- if (type === nymph_1.TilmeldAccessLevels.FULL_ACCESS) {
493
- return (this.config.clientSetabledUIDs.indexOf(name) !== -1 ||
494
- userOrEmpty.$gatekeeper(`uid/set/${name}`));
778
+ if (type === TilmeldAccessLevels.FULL_ACCESS) {
779
+ return (this.config.clientSetabledUIDs.includes(name) ||
780
+ (await userOrEmpty.$gatekeeper(`uid/set/${name}`)));
495
781
  }
496
- else if (type === nymph_1.TilmeldAccessLevels.WRITE_ACCESS) {
497
- return (this.config.clientEnabledUIDs.indexOf(name) !== -1 ||
498
- this.config.clientSetabledUIDs.indexOf(name) !== -1 ||
499
- userOrEmpty.$gatekeeper(`uid/new/${name}`) ||
500
- userOrEmpty.$gatekeeper(`uid/set/${name}`));
782
+ else if (type === TilmeldAccessLevels.WRITE_ACCESS) {
783
+ return (this.config.clientEnabledUIDs.includes(name) ||
784
+ this.config.clientSetabledUIDs.includes(name) ||
785
+ (await userOrEmpty.$gatekeeper(`uid/new/${name}`)) ||
786
+ (await userOrEmpty.$gatekeeper(`uid/set/${name}`)));
501
787
  }
502
- else if (type === nymph_1.TilmeldAccessLevels.READ_ACCESS) {
503
- return (this.config.clientReadableUIDs.indexOf(name) !== -1 ||
504
- this.config.clientEnabledUIDs.indexOf(name) !== -1 ||
505
- this.config.clientSetabledUIDs.indexOf(name) !== -1 ||
506
- userOrEmpty.$gatekeeper(`uid/get/${name}`) ||
507
- userOrEmpty.$gatekeeper(`uid/new/${name}`) ||
508
- userOrEmpty.$gatekeeper(`uid/set/${name}`));
788
+ else if (type === TilmeldAccessLevels.READ_ACCESS) {
789
+ return (this.config.clientReadableUIDs.includes(name) ||
790
+ this.config.clientEnabledUIDs.includes(name) ||
791
+ this.config.clientSetabledUIDs.includes(name) ||
792
+ (await userOrEmpty.$gatekeeper(`uid/get/${name}`)) ||
793
+ (await userOrEmpty.$gatekeeper(`uid/new/${name}`)) ||
794
+ (await userOrEmpty.$gatekeeper(`uid/set/${name}`)));
509
795
  }
510
796
  return false;
511
797
  }
512
- fillSession(user) {
513
- const _group = user.group;
514
- const _groups = user.groups;
798
+ /**
799
+ * Fill session user data.
800
+ *
801
+ * @param user The user.
802
+ */
803
+ async fillSession(user) {
515
804
  this.currentUser = user;
805
+ this.gatekeeperCache = await user.$getGatekeeperCache();
806
+ // Now update the data protection on the user and all the groups.
516
807
  this.currentUser.$updateDataProtection();
517
- if (this.currentUser.group != null) {
518
- this.currentUser.group.$updateDataProtection();
519
- }
520
- for (let group of this.currentUser.groups ?? []) {
521
- group.$updateDataProtection();
522
- }
808
+ this.currentUser.$updateGroupDataProtection();
523
809
  }
810
+ /**
811
+ * Clear session user data.
812
+ */
524
813
  clearSession() {
525
814
  const user = this.currentUser;
526
815
  this.currentUser = null;
816
+ this.gatekeeperCache = null;
527
817
  if (user) {
528
818
  user.$updateDataProtection();
529
- if (user.group != null) {
530
- user.group.$updateDataProtection();
531
- }
532
- for (let group of user.groups ?? []) {
533
- group.$updateDataProtection();
534
- }
819
+ user.$updateGroupDataProtection();
535
820
  }
536
821
  }
822
+ /**
823
+ * Validate and extract the user from a token.
824
+ *
825
+ * @param token The authentication token.
826
+ * @returns The user on success, null on failure.
827
+ */
537
828
  async extractToken(token) {
829
+ this.nymph.config.debugInfo('tilmeld', 'Extracting and validating token.');
538
830
  const extract = this.config.jwtExtract(this.config, token);
539
831
  if (extract == null) {
540
832
  return null;
@@ -544,91 +836,247 @@ class Tilmeld {
544
836
  type: '&',
545
837
  guid: guid,
546
838
  });
547
- if (!user || !user.guid || !user.enabled) {
839
+ if (!user || !user.guid) {
548
840
  return null;
549
841
  }
550
842
  return user;
551
843
  }
552
- authenticate(skipXsrfToken = false) {
844
+ /**
845
+ * Check for TILMELDAUTH and TILMELDSWITCH tokens, and, if set, authenticate
846
+ * from it/them.
847
+ *
848
+ * You can also call this function after setting `response.locals.user` to the
849
+ * user you want to authenticate. You *should* check for `user.enabled` before
850
+ * setting this variable, unless you explicitly want to log in as a disabled
851
+ * user. (The user must be an instance of the User class for this Tilmeld
852
+ * instance.)
853
+ *
854
+ * This function will set `response.locals.user` to the logged in user on
855
+ * successful authentication.
856
+ *
857
+ * @param skipXsrfToken Skip the XSRF token check.
858
+ * @param skipRenew Skip the token renewal step, even if the token is close to expiration.
859
+ * @returns True if a user was authenticated, false on any failure.
860
+ */
861
+ async authenticate(skipXsrfToken = false, skipRenew = false) {
553
862
  if (this.request == null) {
554
863
  return false;
555
864
  }
865
+ if (this.response &&
866
+ this.response.locals.user &&
867
+ this.response.locals.user instanceof this.User) {
868
+ // The user has already been authenticated through some other means.
869
+ const user = this.response.locals.user;
870
+ await this.fillSession(user);
871
+ return true;
872
+ }
556
873
  const cookies = this.request.cookies ?? {};
874
+ // If a client does't support cookies, they can use the X-TILMELDAUTH header
875
+ // to provide the auth token.
557
876
  let fromAuthHeader = false;
558
877
  let authToken;
878
+ let switchToken;
559
879
  if (this.request.header('x-tilmeldauth') != null) {
560
880
  fromAuthHeader = true;
561
881
  authToken = this.request.header('x-tilmeldauth');
882
+ switchToken =
883
+ this.request.header('x-tilmeldswitch') ||
884
+ 'TILMELDSWITCH' in cookies
885
+ ? cookies.TILMELDSWITCH
886
+ : null;
562
887
  }
563
888
  else if ('TILMELDAUTH' in cookies) {
564
889
  fromAuthHeader = false;
565
890
  authToken = cookies.TILMELDAUTH;
891
+ switchToken = 'TILMELDSWITCH' in cookies ? cookies.TILMELDSWITCH : null;
566
892
  }
567
893
  else {
568
894
  return false;
569
895
  }
570
- let extract;
896
+ let authExtract;
897
+ let switchExtract;
571
898
  if (skipXsrfToken ||
572
899
  this.request.originalUrl.startsWith(this.config.setupPath)) {
573
- extract = this.config.jwtExtract(this.config, authToken);
900
+ // The request is for the setup app, or we were told to skip the XSRF
901
+ // check, so don't check for the XSRF token.
902
+ authExtract = this.config.jwtExtract(this.config, authToken);
903
+ switchExtract = switchToken
904
+ ? this.config.jwtExtract(this.config, switchToken)
905
+ : null;
574
906
  }
575
907
  else {
908
+ // The request is for something else, so check for a valid XSRF token,
909
+ // unless the auth token is provided by a header (instead of a cookie).
576
910
  const xsrfToken = this.request.header('x-xsrf-token');
577
911
  if (xsrfToken == null && !fromAuthHeader) {
578
912
  return false;
579
913
  }
580
- extract = this.config.jwtExtract(this.config, authToken, xsrfToken);
914
+ authExtract = this.config.jwtExtract(this.config, authToken, xsrfToken);
915
+ switchExtract = switchToken
916
+ ? this.config.jwtExtract(this.config, switchToken)
917
+ : null;
581
918
  }
582
- if (extract == null) {
583
- this.logout();
919
+ if (authExtract == null) {
920
+ await this.logout();
584
921
  return false;
585
922
  }
586
- const { guid, expire } = extract;
587
- const user = this.User.factorySync(guid);
588
- if (user.guid == null || !user.enabled) {
589
- this.logout();
923
+ const { guid, issued, expire } = authExtract;
924
+ const { guid: switchGuid, expire: switchExpire } = switchExtract || {
925
+ guid: null,
926
+ expire: null,
927
+ };
928
+ const user = await this.User.factory(guid);
929
+ if (user.guid == null ||
930
+ !user.enabled ||
931
+ expire.getTime() <= Date.now() ||
932
+ issued.getTime() > Date.now() ||
933
+ (user.revokeTokenDate != null && issued.getTime() <= user.revokeTokenDate)) {
934
+ await this.logout();
590
935
  return false;
591
936
  }
592
- if (expire.valueOf() < Date.now() + this.config.jwtRenew * 1000) {
593
- this.login(user, fromAuthHeader);
937
+ if (switchGuid && switchExpire && switchExpire.getTime() > Date.now()) {
938
+ // Load the switch user.
939
+ const switchUser = await this.User.factory(switchGuid);
940
+ if (switchUser.guid == null) {
941
+ await this.logoutSwitch();
942
+ }
943
+ else {
944
+ await this.fillSession(switchUser);
945
+ if (this.response) {
946
+ this.response.locals.user = switchUser;
947
+ }
948
+ return true;
949
+ }
950
+ }
951
+ if (!skipRenew &&
952
+ expire.getTime() < Date.now() + this.config.jwtRenew * 1000) {
953
+ // If the user is less than renew time from needing a new token, give them
954
+ // a new one.
955
+ await this.login(user, fromAuthHeader);
594
956
  }
595
957
  else {
596
- this.fillSession(user);
958
+ await this.fillSession(user);
959
+ }
960
+ if (this.response) {
961
+ this.response.locals.user = user;
597
962
  }
598
963
  return true;
599
964
  }
600
- login(user, sendAuthHeader) {
965
+ /**
966
+ * Logs the given user into the system.
967
+ *
968
+ * @param user The user.
969
+ * @param sendAuthHeader Send the auth token as a custom header.
970
+ * @param sendCookie Send the auth token as a cookie.
971
+ * @returns True on success, false on failure.
972
+ */
973
+ async login(user, sendAuthHeader, sendCookie = true) {
601
974
  if (user.guid != null && user.enabled) {
602
- if (this.response && !this.response.headersSent) {
603
- const token = this.config.jwtBuilder(this.config, user);
604
- const appUrl = new url_1.URL(this.config.appUrl);
605
- this.response.cookie('TILMELDAUTH', token, {
606
- domain: this.config.cookieDomain,
607
- path: this.config.cookiePath,
608
- maxAge: this.config.jwtExpire * 1000,
609
- secure: appUrl.protocol === 'https',
610
- httpOnly: false,
611
- sameSite: appUrl.protocol === 'https' ? 'lax' : 'strict',
612
- });
613
- if (sendAuthHeader) {
614
- this.response.set('X-TILMELDAUTH', token);
975
+ if (this.response) {
976
+ if (!this.response.headersSent) {
977
+ const token = this.config.jwtBuilder(this.config, user);
978
+ if (sendCookie) {
979
+ const appUrl = new URL(this.config.appUrl);
980
+ this.response.cookie('TILMELDAUTH', token, {
981
+ domain: this.config.cookieDomain,
982
+ path: this.config.cookiePath,
983
+ maxAge: this.config.jwtExpire * 1000,
984
+ secure: appUrl.protocol === 'https:',
985
+ httpOnly: false, // Allow JS access (for CSRF protection).
986
+ sameSite: appUrl.protocol === 'https:' ? 'lax' : 'strict',
987
+ });
988
+ }
989
+ if (sendAuthHeader) {
990
+ this.response.set('X-TILMELDAUTH', token);
991
+ }
615
992
  }
993
+ this.response.locals.user = user;
616
994
  }
617
- this.fillSession(user);
995
+ await this.fillSession(user);
618
996
  return true;
619
997
  }
620
998
  return false;
621
999
  }
622
- logout() {
1000
+ /**
1001
+ * Adds a switch auth token for the given user.
1002
+ *
1003
+ * This effectively logs the current user in to the system as the given user.
1004
+ *
1005
+ * @param user The user.
1006
+ * @param sendAuthHeader Send the auth token as a custom header.
1007
+ * @param sendCookie Send the auth token as a cookie.
1008
+ * @returns True on success, false on failure.
1009
+ */
1010
+ async loginSwitch(user, sendAuthHeader, sendCookie = true) {
1011
+ if (user.guid != null) {
1012
+ if (this.response) {
1013
+ if (!this.response.headersSent) {
1014
+ const token = this.config.jwtBuilder(this.config, user, true);
1015
+ if (sendCookie) {
1016
+ const appUrl = new URL(this.config.appUrl);
1017
+ this.response.cookie('TILMELDSWITCH', token, {
1018
+ domain: this.config.cookieDomain,
1019
+ path: this.config.cookiePath,
1020
+ maxAge: this.config.jwtSwitchExpire * 1000,
1021
+ secure: appUrl.protocol === 'https:',
1022
+ httpOnly: false, // Allow JS access (for PubSub auth token).
1023
+ sameSite: appUrl.protocol === 'https:' ? 'lax' : 'strict',
1024
+ });
1025
+ }
1026
+ if (sendAuthHeader) {
1027
+ this.response.set('X-TILMELDSWITCH', token);
1028
+ }
1029
+ }
1030
+ this.response.locals.user = user;
1031
+ }
1032
+ await this.fillSession(user);
1033
+ return true;
1034
+ }
1035
+ return false;
1036
+ }
1037
+ /**
1038
+ * Logs the current user out of the system.
1039
+ *
1040
+ * @param clearCookie Clear the auth cookie. (Also send a header.)
1041
+ */
1042
+ async logout(clearCookie = true) {
1043
+ if (this.request && !this.alreadyLoggedOutSwitch) {
1044
+ const cookies = this.request.cookies ?? {};
1045
+ if ('TILMELDSWITCH' in cookies) {
1046
+ this.alreadyLoggedOutSwitch = true;
1047
+ return await this.logoutSwitch(clearCookie);
1048
+ }
1049
+ }
623
1050
  this.clearSession();
624
- if (this.response && !this.response.headersSent) {
625
- this.response.clearCookie('TILMELDAUTH', {
626
- domain: this.config.cookieDomain,
627
- path: this.config.cookiePath,
628
- });
629
- this.response.set('X-TILMELDAUTH', '');
1051
+ if (this.response) {
1052
+ if (clearCookie && !this.response.headersSent) {
1053
+ this.response.clearCookie('TILMELDAUTH', {
1054
+ domain: this.config.cookieDomain,
1055
+ path: this.config.cookiePath,
1056
+ });
1057
+ this.response.set('X-TILMELDAUTH', '');
1058
+ }
1059
+ this.response.locals.user = null;
1060
+ }
1061
+ }
1062
+ /**
1063
+ * Clears the switch user out of the system.
1064
+ *
1065
+ * @param clearCookie Clear the auth cookie. (Also send a header.)
1066
+ */
1067
+ async logoutSwitch(clearCookie = true) {
1068
+ this.clearSession();
1069
+ if (this.response) {
1070
+ if (clearCookie && !this.response.headersSent) {
1071
+ this.response.clearCookie('TILMELDSWITCH', {
1072
+ domain: this.config.cookieDomain,
1073
+ path: this.config.cookiePath,
1074
+ });
1075
+ this.response.set('X-TILMELDSWITCH', '');
1076
+ }
1077
+ this.response.locals.user = null;
1078
+ await this.authenticate(false, true);
630
1079
  }
631
1080
  }
632
1081
  }
633
- exports.default = Tilmeld;
634
1082
  //# sourceMappingURL=Tilmeld.js.map