@nymphjs/tilmeld 1.0.0-beta.13 → 1.0.0-beta.131

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 (105) hide show
  1. package/CHANGELOG.md +604 -0
  2. package/README.md +21 -5
  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 +183 -19
  7. package/dist/Group.js +814 -440
  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 +725 -286
  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 -26
  18. package/dist/User.js +1955 -1058
  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/decorators/index.d.ts +2 -0
  30. package/dist/decorators/index.js +3 -0
  31. package/dist/decorators/index.js.map +1 -0
  32. package/dist/decorators/requireAbility.d.ts +10 -0
  33. package/dist/decorators/requireAbility.js +21 -0
  34. package/dist/decorators/requireAbility.js.map +1 -0
  35. package/dist/decorators/requireAuthentication.d.ts +8 -0
  36. package/dist/decorators/requireAuthentication.js +16 -0
  37. package/dist/decorators/requireAuthentication.js.map +1 -0
  38. package/dist/enforceTilmeld.d.ts +3 -0
  39. package/dist/enforceTilmeld.js +18 -0
  40. package/dist/enforceTilmeld.js.map +1 -0
  41. package/dist/errors/AccessControlError.d.ts +2 -1
  42. package/dist/errors/AccessControlError.js +3 -6
  43. package/dist/errors/AccessControlError.js.map +1 -1
  44. package/dist/errors/BadDataError.d.ts +2 -1
  45. package/dist/errors/BadDataError.js +3 -6
  46. package/dist/errors/BadDataError.js.map +1 -1
  47. package/dist/errors/BadEmailError.d.ts +2 -1
  48. package/dist/errors/BadEmailError.js +3 -6
  49. package/dist/errors/BadEmailError.js.map +1 -1
  50. package/dist/errors/BadUsernameError.d.ts +2 -1
  51. package/dist/errors/BadUsernameError.js +3 -6
  52. package/dist/errors/BadUsernameError.js.map +1 -1
  53. package/dist/errors/CouldNotChangeDefaultPrimaryGroupError.js +1 -5
  54. package/dist/errors/CouldNotChangeDefaultPrimaryGroupError.js.map +1 -1
  55. package/dist/errors/EmailChangeRateLimitExceededError.js +1 -5
  56. package/dist/errors/EmailChangeRateLimitExceededError.js.map +1 -1
  57. package/dist/errors/index.d.ts +6 -6
  58. package/dist/errors/index.js +6 -22
  59. package/dist/errors/index.js.map +1 -1
  60. package/dist/index.d.ts +12 -10
  61. package/dist/index.js +17 -35
  62. package/dist/index.js.map +1 -1
  63. package/dist/testArtifacts.d.ts +23 -0
  64. package/dist/testArtifacts.js +1317 -0
  65. package/dist/testArtifacts.js.map +1 -0
  66. package/dist/tilmeldJoiProps.d.ts +3 -3
  67. package/dist/tilmeldJoiProps.js +13 -18
  68. package/dist/tilmeldJoiProps.js.map +1 -1
  69. package/jest.config.js +31 -5
  70. package/package.json +49 -36
  71. package/src/AbleObject.ts +2 -2
  72. package/src/Group.testArtifacts.ts +159 -0
  73. package/src/Group.ts +647 -241
  74. package/src/Tilmeld.ts +550 -315
  75. package/src/Tilmeld.types.ts +5 -5
  76. package/src/User.testArtifacts.ts +226 -0
  77. package/src/User.ts +1657 -637
  78. package/src/conf/defaults.ts +172 -109
  79. package/src/conf/index.ts +370 -2
  80. package/src/decorators/index.ts +2 -0
  81. package/src/decorators/requireAbility.ts +26 -0
  82. package/src/decorators/requireAuthentication.ts +19 -0
  83. package/src/enforceTilmeld.ts +20 -0
  84. package/src/errors/AccessControlError.ts +4 -2
  85. package/src/errors/BadDataError.ts +4 -2
  86. package/src/errors/BadEmailError.ts +4 -2
  87. package/src/errors/BadUsernameError.ts +4 -2
  88. package/src/errors/index.ts +6 -6
  89. package/src/index.ts +13 -10
  90. package/src/testArtifacts.ts +2098 -0
  91. package/src/tilmeldJoiProps.ts +8 -23
  92. package/tsconfig.json +6 -3
  93. package/typedoc.json +4 -0
  94. package/dist/Group.test.d.ts +0 -1
  95. package/dist/Group.test.js +0 -48
  96. package/dist/Group.test.js.map +0 -1
  97. package/dist/User.test.d.ts +0 -1
  98. package/dist/User.test.js +0 -51
  99. package/dist/User.test.js.map +0 -1
  100. package/dist/conf/d.d.ts +0 -55
  101. package/dist/conf/d.js +0 -3
  102. package/dist/conf/d.js.map +0 -1
  103. package/src/Group.test.ts +0 -58
  104. package/src/User.test.ts +0 -61
  105. package/src/conf/d.ts +0 -303
package/dist/Group.js CHANGED
@@ -1,38 +1,68 @@
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 md5_1 = __importDefault(require("crypto-js/md5"));
7
- const lodash_1 = require("lodash");
8
- const AbleObject_1 = __importDefault(require("./AbleObject"));
9
- const errors_1 = require("./errors");
10
- class Group extends AbleObject_1.default {
11
- static async factory(guid) {
12
- return (await super.factory(guid));
1
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
2
+ var useValue = arguments.length > 2;
3
+ for (var i = 0; i < initializers.length; i++) {
4
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
13
5
  }
14
- static async factoryGroupname(groupname) {
15
- const entity = new this();
16
- if (groupname != null) {
17
- const entity = await this.nymph.getEntity({
18
- class: this,
19
- }, {
20
- type: '&',
21
- ilike: ['groupname', groupname.replace(/([\\%_])/g, (s) => `\\${s}`)],
22
- });
23
- if (entity != null) {
24
- return entity;
25
- }
6
+ return useValue ? value : void 0;
7
+ };
8
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
9
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
10
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
11
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
12
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
13
+ var _, done = false;
14
+ for (var i = decorators.length - 1; i >= 0; i--) {
15
+ var context = {};
16
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
17
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
18
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
19
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
20
+ if (kind === "accessor") {
21
+ if (result === void 0) continue;
22
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
23
+ if (_ = accept(result.get)) descriptor.get = _;
24
+ if (_ = accept(result.set)) descriptor.set = _;
25
+ if (_ = accept(result.init)) initializers.unshift(_);
26
+ }
27
+ else if (_ = accept(result)) {
28
+ if (kind === "field") initializers.unshift(_);
29
+ else descriptor[key] = _;
26
30
  }
27
- return entity;
28
- }
29
- static factorySync(guid) {
30
- return super.factorySync(guid);
31
31
  }
32
- constructor(guid) {
33
- super(guid);
34
- this.$tags = [];
35
- this.$clientEnabledMethods = [
32
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
+ done = true;
34
+ };
35
+ import crypto from 'node:crypto';
36
+ import { transaction, transactional, } from '@nymphjs/nymph';
37
+ import { nanoid } from '@nymphjs/guid';
38
+ import { difference, xor } from 'lodash-es';
39
+ import { splitn } from '@sciactive/splitn';
40
+ import { enforceTilmeld } from './enforceTilmeld.js';
41
+ import AbleObject from './AbleObject.js';
42
+ import { AccessControlError, BadDataError, BadEmailError, BadUsernameError, CouldNotChangeDefaultPrimaryGroupError, } from './errors/index.js';
43
+ import UserClass from './User.js';
44
+ let Group = (() => {
45
+ let _classSuper = AbleObject;
46
+ let _instanceExtraInitializers = [];
47
+ let _$delete_decorators;
48
+ return class Group extends _classSuper {
49
+ static {
50
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
51
+ _$delete_decorators = [transactional];
52
+ __esDecorate(this, null, _$delete_decorators, { kind: "method", name: "$delete", static: false, private: false, access: { has: obj => "$delete" in obj, get: obj => obj.$delete }, metadata: _metadata }, null, _instanceExtraInitializers);
53
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
54
+ }
55
+ static ETYPE = 'tilmeld_group';
56
+ static class = 'Group';
57
+ static checkGroupnameCallbacks = [];
58
+ static beforeSaveCallbacks = [];
59
+ static afterSaveCallbacks = [];
60
+ static beforeDeleteCallbacks = [];
61
+ static afterDeleteCallbacks = [];
62
+ static DEFAULT_PRIVATE_DATA = ['email', 'phone', 'abilities', 'user'];
63
+ static DEFAULT_ALLOWLIST_DATA = [];
64
+ $tags = (__runInitializers(this, _instanceExtraInitializers), []);
65
+ $clientEnabledMethods = [
36
66
  '$checkGroupname',
37
67
  '$checkEmail',
38
68
  '$getAvatar',
@@ -41,467 +71,811 @@ class Group extends AbleObject_1.default {
41
71
  '$getLevel',
42
72
  '$isDescendant',
43
73
  ];
44
- this.$privateData = [...Group.DEFAULT_PRIVATE_DATA];
45
- this.$allowlistData = [...Group.DEFAULT_ALLOWLIST_DATA];
46
- this.$allowlistTags = [];
47
- this.$skipAcWhenSaving = false;
48
- if (this.guid == null) {
49
- this.$data.enabled = true;
50
- this.$data.abilities = [];
51
- this.$updateDataProtection();
52
- }
53
- }
54
- static async getPrimaryGroups(options, selectors) {
55
- if (!this.tilmeld.gatekeeper('tilmeld/admin')) {
56
- throw new Error("You don't have permission to do that.");
57
- }
58
- return await this.getAssignableGroups(this.tilmeld.config.highestPrimary, { ...options, class: this.tilmeld.Group, return: 'entity' }, [...(selectors ?? [])]);
59
- }
60
- static async getSecondaryGroups(options, selectors) {
61
- if (!this.tilmeld.gatekeeper('tilmeld/admin')) {
62
- throw new Error("You don't have permission to do that.");
63
- }
64
- return await this.getAssignableGroups(this.tilmeld.config.highestSecondary, { ...options, class: this.tilmeld.Group, return: 'entity' }, [...(selectors ?? [])]);
65
- }
66
- static async getAssignableGroups(highestParent, options, selectors) {
67
- let assignableGroups = [];
68
- if (highestParent === false) {
69
- return assignableGroups;
70
- }
71
- assignableGroups = await this.nymph.getEntities({ ...options, class: this.tilmeld.Group }, ...selectors);
72
- if (highestParent !== true) {
73
- assignableGroups = assignableGroups.filter((group) => {
74
- let curGroup = group;
75
- while (curGroup.parent != null && curGroup.parent.cdate != null) {
76
- if (curGroup.parent.guid === highestParent) {
77
- return true;
78
- }
79
- curGroup = curGroup.parent;
74
+ static clientEnabledStaticMethods = [
75
+ 'getPrimaryGroups',
76
+ 'getSecondaryGroups',
77
+ ];
78
+ $privateData = [...Group.DEFAULT_PRIVATE_DATA];
79
+ static searchRestrictedData = [...Group.DEFAULT_PRIVATE_DATA];
80
+ $allowlistData = [...Group.DEFAULT_ALLOWLIST_DATA];
81
+ $allowlistTags = [];
82
+ /**
83
+ * This should only be used by the backend.
84
+ */
85
+ $skipAcWhenSaving = false;
86
+ /**
87
+ * This should only be used by the backend.
88
+ */
89
+ $skipAcWhenDeleting = false;
90
+ /**
91
+ * Used to save the current groupname for domain admin permissions.
92
+ */
93
+ $originalGroupname;
94
+ static getFTSText(name, value) {
95
+ if ([
96
+ 'abilities',
97
+ 'parent',
98
+ 'user',
99
+ 'enabled',
100
+ 'defaultPrimary',
101
+ 'defaultSecondary',
102
+ 'unverifiedSecondary',
103
+ ].indexOf(name) !== -1) {
104
+ return null;
105
+ }
106
+ return super.getFTSText(name, value);
107
+ }
108
+ static async factoryGroupname(groupname) {
109
+ const entity = new this();
110
+ if (groupname != null) {
111
+ const entity = await this.nymph.getEntity({
112
+ class: this,
113
+ }, {
114
+ type: '&',
115
+ ilike: ['groupname', groupname.replace(/([\\%_])/g, (s) => `\\${s}`)],
116
+ });
117
+ if (entity != null) {
118
+ return entity;
80
119
  }
81
- return false;
82
- });
83
- }
84
- return assignableGroups;
85
- }
86
- $getAvatar() {
87
- if (this.$data.avatar != null && this.$data.avatar !== '') {
88
- return this.$data.avatar;
89
- }
90
- if (this.$data.email == null || !this.$data.email.length) {
91
- return 'https://secure.gravatar.com/avatar/?d=mm&s=40';
120
+ }
121
+ return entity;
122
+ }
123
+ /**
124
+ * Get all the groups that can be assigned as primary groups.
125
+ *
126
+ * @param options The options for an optional search query.
127
+ * @param selectors The selectors for an optional search query.
128
+ * @returns An array of the assignable primary groups.
129
+ */
130
+ static async getPrimaryGroups(options, selectors) {
131
+ const tilmeld = enforceTilmeld(this);
132
+ if (!tilmeld.gatekeeper('tilmeld/admin')) {
133
+ throw new Error("You don't have permission to do that.");
134
+ }
135
+ return await this.getAssignableGroups(tilmeld.config.highestPrimary, { ...options, class: tilmeld.Group, return: 'entity' }, [...(selectors ?? [])]);
136
+ }
137
+ /**
138
+ * Get all the groups that can be assigned as secondary groups.
139
+ *
140
+ * @param options The options for an optional search query.
141
+ * @param selectors The selectors for an optional search query.
142
+ * @returns An array of the assignable secondary groups.
143
+ */
144
+ static async getSecondaryGroups(options, selectors) {
145
+ const tilmeld = enforceTilmeld(this);
146
+ if (!tilmeld.gatekeeper('tilmeld/admin')) {
147
+ throw new Error("You don't have permission to do that.");
148
+ }
149
+ return await this.getAssignableGroups(tilmeld.config.highestSecondary, { ...options, class: tilmeld.Group, return: 'entity' }, [...(selectors ?? [])]);
92
150
  }
93
- return ('https://secure.gravatar.com/avatar/' +
94
- (0, md5_1.default)(this.$data.email.trim().toLowerCase()).toString() +
95
- '?d=identicon&s=40');
96
- }
97
- $jsonAcceptData(input, allowConflict = false) {
98
- const tilmeld = this.$nymph.tilmeld;
99
- this.$referenceWake();
100
- if (input.data.abilities?.indexOf('system/admin') !== -1 &&
101
- this.$data.abilities?.indexOf('system/admin') === -1 &&
102
- tilmeld.gatekeeper('tilmeld/admin') &&
103
- !tilmeld.gatekeeper('system/admin')) {
104
- throw new errors_1.BadDataError("You don't have the authority to make this group a system admin.");
151
+ static async getAssignableGroups(highestParent, options, selectors) {
152
+ const tilmeld = enforceTilmeld(this);
153
+ let assignableGroups = [];
154
+ if (highestParent === false) {
155
+ return assignableGroups;
156
+ }
157
+ assignableGroups = await this.nymph.getEntities({ ...options, class: tilmeld.Group }, ...selectors);
158
+ if (highestParent !== true) {
159
+ assignableGroups = (await Promise.all(assignableGroups.map(async (group) => {
160
+ let curGroup = group;
161
+ let parent = curGroup.parent;
162
+ await parent?.$wake();
163
+ while (parent != null && parent?.cdate != null) {
164
+ if (parent?.guid === highestParent) {
165
+ return group;
166
+ }
167
+ curGroup = parent;
168
+ parent = curGroup.parent;
169
+ await parent?.$wake();
170
+ }
171
+ return null;
172
+ }))).filter((group) => group != null);
173
+ }
174
+ return assignableGroups;
105
175
  }
106
- super.$jsonAcceptData(input, allowConflict);
107
- }
108
- $jsonAcceptPatch(patch, allowConflict = false) {
109
- const tilmeld = this.$nymph.tilmeld;
110
- this.$referenceWake();
111
- if (patch.set.abilities?.indexOf('system/admin') !== -1 &&
112
- this.$data.abilities?.indexOf('system/admin') === -1 &&
113
- tilmeld.gatekeeper('tilmeld/admin') &&
114
- !tilmeld.gatekeeper('system/admin')) {
115
- throw new errors_1.BadDataError("You don't have the authority to make this group a system admin.");
176
+ constructor() {
177
+ super();
178
+ // Defaults.
179
+ this.$data.enabled = true;
180
+ this.$data.abilities = [];
181
+ this.$updateDataProtection();
116
182
  }
117
- super.$jsonAcceptPatch(patch, allowConflict);
118
- }
119
- $putData(data, sdata) {
120
- super.$putData(data, sdata);
121
- this.$updateDataProtection();
122
- }
123
- $updateDataProtection(givenUser) {
124
- const tilmeld = this.$nymph.tilmeld;
125
- let user = givenUser ?? tilmeld.User.current();
126
- this.$privateData = [...Group.DEFAULT_PRIVATE_DATA];
127
- this.$allowlistData = [...Group.DEFAULT_ALLOWLIST_DATA];
128
- if (tilmeld.config.emailUsernames) {
129
- this.$privateData.push('groupname');
183
+ async $getUniques() {
184
+ const tilmeld = enforceTilmeld(this);
185
+ const uniques = [`u:${this.$data.groupname}`];
186
+ if (!tilmeld.config.emailUsernames &&
187
+ tilmeld.config.userFields.includes('email')) {
188
+ uniques.push(`e:${this.$data.email}`);
189
+ }
190
+ if (this.$data.defaultPrimary) {
191
+ uniques.push(`o:default-primary`);
192
+ }
193
+ return uniques;
130
194
  }
131
- if (user != null &&
132
- ((user.abilities?.indexOf('tilmeld/admin') ?? -1) !== -1 ||
133
- (user.abilities?.indexOf('system/admin') ?? -1) !== -1)) {
134
- this.$privateData = [];
135
- this.$allowlistData = undefined;
195
+ $getAvatar() {
196
+ if (this.$data.avatar != null && this.$data.avatar !== '') {
197
+ return this.$data.avatar;
198
+ }
199
+ if (this.$data.email == null || !this.$data.email.length) {
200
+ return 'https://secure.gravatar.com/avatar/?d=mm&s=40';
201
+ }
202
+ return ('https://secure.gravatar.com/avatar/' +
203
+ crypto
204
+ .createHash('sha256')
205
+ .update(this.$data.email.trim().toLowerCase())
206
+ .digest('hex')
207
+ .toLowerCase() +
208
+ '?d=identicon&s=40');
209
+ }
210
+ $jsonAcceptData(input, allowConflict = false) {
211
+ this.$check();
212
+ if ('abilities' in input.data) {
213
+ this.$checkIncomingAbilities(input.data.abilities);
214
+ }
215
+ super.$jsonAcceptData(input, allowConflict);
136
216
  }
137
- else if (this.$data.user != null &&
138
- user != null &&
139
- this.$data.user.$is(user)) {
140
- this.$privateData = [];
217
+ $jsonAcceptPatch(patch, allowConflict = false) {
218
+ this.$check();
219
+ if ('abilities' in patch.set) {
220
+ this.$checkIncomingAbilities(patch.set.abilities);
221
+ }
222
+ super.$jsonAcceptPatch(patch, allowConflict);
141
223
  }
142
- }
143
- $isDescendant(givenGroup) {
144
- const tilmeld = this.$nymph.tilmeld;
145
- let group;
146
- if (typeof givenGroup === 'string') {
147
- group = tilmeld.Group.factorySync(givenGroup);
224
+ $checkIncomingAbilities(incoming) {
225
+ const tilmeld = enforceTilmeld(this);
226
+ if (!Array.isArray(incoming) ||
227
+ incoming.find((ability) => typeof ability !== 'string')) {
228
+ throw new BadDataError('Abilities must be an array of strings.');
229
+ }
230
+ if (incoming.includes('system/admin') !==
231
+ this.$data.abilities?.includes('system/admin') &&
232
+ (!tilmeld.currentUser ||
233
+ !tilmeld.currentUser.abilities?.includes('system/admin'))) {
234
+ throw new BadDataError("You don't have the authority to grant or revoke system/admin.");
235
+ }
236
+ if (incoming.includes('tilmeld/admin') !==
237
+ this.$data.abilities?.includes('tilmeld/admin') &&
238
+ (!tilmeld.currentUser ||
239
+ !tilmeld.currentUser.abilities?.includes('system/admin'))) {
240
+ throw new BadDataError("You don't have the authority to grant or revoke tilmeld/admin.");
241
+ }
242
+ if (incoming.includes('tilmeld/switch') !==
243
+ this.$data.abilities?.includes('tilmeld/switch') &&
244
+ (!tilmeld.currentUser ||
245
+ !tilmeld.currentUser.abilities?.includes('system/admin'))) {
246
+ throw new BadDataError("You don't have the authority to grant or revoke tilmeld/switch.");
247
+ }
248
+ if (xor(incoming.filter((ability) => ability.startsWith('tilmeld/')), this.$data.abilities?.filter((ability) => ability.startsWith('tilmeld/')) ?? []).length &&
249
+ (!tilmeld.currentUser ||
250
+ (!tilmeld.currentUser.abilities?.includes('system/admin') &&
251
+ !tilmeld.currentUser.abilities?.includes('tilmeld/admin')))) {
252
+ throw new BadDataError("You don't have the authority to grant or revoke Tilmeld abilities.");
253
+ }
148
254
  }
149
- else {
150
- group = givenGroup;
255
+ $putData(data, sdata, source) {
256
+ super.$putData(data, sdata, source);
257
+ // TODO: Fix these being added by the drivers.
258
+ // @ts-ignore
259
+ delete this.$data.acRead;
260
+ // @ts-ignore
261
+ delete this.$data.acWrite;
262
+ // @ts-ignore
263
+ delete this.$data.acFull;
264
+ if (source === 'server') {
265
+ this.$originalGroupname = this.$data.groupname;
266
+ }
267
+ this.$updateDataProtection();
151
268
  }
152
- if (group.guid == null) {
153
- return false;
269
+ /**
270
+ * Update the data protection arrays for a user.
271
+ *
272
+ * @param givenUser User to update protection for. If undefined, will use the currently logged in user.
273
+ */
274
+ $updateDataProtection(givenUser) {
275
+ const tilmeld = enforceTilmeld(this);
276
+ let user = givenUser ?? tilmeld.User.current();
277
+ let [_groupname, domain] = tilmeld.config.domainSupport
278
+ ? splitn(this.$data.groupname ?? '', '@', 2)
279
+ : [this.$data.groupname, null];
280
+ // Lowercase the domain part.
281
+ if (domain) {
282
+ domain = domain.toLowerCase();
283
+ }
284
+ this.$privateData = [...Group.DEFAULT_PRIVATE_DATA];
285
+ this.$allowlistData = [...Group.DEFAULT_ALLOWLIST_DATA];
286
+ if (tilmeld.config.emailUsernames) {
287
+ this.$privateData.push('groupname');
288
+ }
289
+ if (user != null &&
290
+ (user.abilities?.includes('tilmeld/admin') ||
291
+ user.abilities?.includes('system/admin'))) {
292
+ // Users who can edit groups can see their data.
293
+ this.$privateData = [];
294
+ this.$allowlistData = undefined;
295
+ }
296
+ else if (this.$data.user != null &&
297
+ user != null &&
298
+ this.$data.user.guid === user.guid) {
299
+ // Users can see their group's data.
300
+ this.$privateData = [];
301
+ }
302
+ else if (user != null &&
303
+ tilmeld.config.domainSupport &&
304
+ domain &&
305
+ user.abilities?.includes(`tilmeld/domain/${domain}/admin`)) {
306
+ // Domain admins can see their groups' data.
307
+ this.$privateData = [];
308
+ }
154
309
  }
155
- if (this.$data.parent == null) {
310
+ /**
311
+ * Check whether the group is a descendant of the given group.
312
+ *
313
+ * @param group The group, or the group's GUID.
314
+ * @returns True or false.
315
+ */
316
+ async $isDescendant(givenGroup) {
317
+ const tilmeld = enforceTilmeld(this);
318
+ let group;
319
+ if (typeof givenGroup === 'string') {
320
+ group = await tilmeld.Group.factory(givenGroup);
321
+ }
322
+ else {
323
+ group = givenGroup;
324
+ }
325
+ if (group.guid == null) {
326
+ return false;
327
+ }
328
+ // Check to see if the group is a descendant of the given group.
329
+ const parent = this.$data.parent;
330
+ await parent?.$wake();
331
+ if (parent == null) {
332
+ return false;
333
+ }
334
+ if (parent.$is(group)) {
335
+ return true;
336
+ }
337
+ if (await parent.$isDescendant(group)) {
338
+ return true;
339
+ }
156
340
  return false;
157
341
  }
158
- if (this.$data.parent.$is(group)) {
159
- return true;
160
- }
161
- if (this.$data.parent.$isDescendant(group)) {
162
- return true;
163
- }
164
- return false;
165
- }
166
- async $getChildren() {
167
- const tilmeld = this.$nymph.tilmeld;
168
- return await this.$nymph.getEntities({ class: tilmeld.Group }, {
169
- type: '&',
170
- equal: ['enabled', true],
171
- ref: ['parent', this],
172
- });
173
- }
174
- async $getDescendants(andSelf = false) {
175
- const tilmeld = this.$nymph.tilmeld;
176
- let groups = [];
177
- const entities = await this.$nymph.getEntities({ class: tilmeld.Group }, {
178
- type: '&',
179
- equal: ['enabled', true],
180
- ref: ['parent', this],
181
- });
182
- for (let entity of entities) {
183
- groups = (await entity.$getDescendants(true)).concat(groups);
184
- }
185
- if (andSelf) {
186
- groups.push(this);
187
- }
188
- return groups;
189
- }
190
- $getDescendantsSync(andSelf = false) {
191
- const tilmeld = this.$nymph.tilmeld;
192
- let groups = [];
193
- let entity;
194
- let offset = 0;
195
- do {
196
- entity = this.$nymph.driver.getEntitySync({ class: tilmeld.Group, offset }, {
342
+ /**
343
+ * Gets an array of the group's child groups.
344
+ *
345
+ * @returns An array of groups.
346
+ */
347
+ async $getChildren() {
348
+ const tilmeld = enforceTilmeld(this);
349
+ return await this.$nymph.getEntities({ class: tilmeld.Group }, {
197
350
  type: '&',
198
351
  equal: ['enabled', true],
199
352
  ref: ['parent', this],
200
353
  });
201
- if (entity != null) {
202
- groups = entity.$getDescendantsSync(true).concat(groups);
203
- }
204
- offset++;
205
- } while (entity != null);
206
- if (andSelf) {
207
- groups.push(this);
208
- }
209
- return groups;
210
- }
211
- $getLevel() {
212
- const tilmeld = this.$nymph.tilmeld;
213
- let group = tilmeld.Group.factorySync(this.guid ?? undefined);
214
- let level = 0;
215
- while (group.parent != null && group.parent.cdate != null && level < 1024) {
216
- level++;
217
- group = group.parent;
218
354
  }
219
- return level;
220
- }
221
- async $getUsers(descendants = false, limit, offset) {
222
- const tilmeld = this.$nymph.tilmeld;
223
- let groups = [];
224
- if (descendants) {
225
- groups = await this.$getDescendants();
355
+ /**
356
+ * Gets an array of the group's descendant groups.
357
+ *
358
+ * @param andSelf Include this group in the returned array.
359
+ * @param andDisabled Include disabled groups.
360
+ * @returns An array of groups.
361
+ */
362
+ async $getDescendants(andSelf = false, andDisabled = false) {
363
+ const tilmeld = enforceTilmeld(this);
364
+ let groups = [];
365
+ const entities = await this.$nymph.getEntities({ class: tilmeld.Group }, {
366
+ type: '&',
367
+ ...(andDisabled ? {} : { equal: ['enabled', true] }),
368
+ ref: ['parent', this],
369
+ });
370
+ for (let entity of entities) {
371
+ groups = (await entity.$getDescendants(true)).concat(groups);
372
+ }
373
+ if (andSelf) {
374
+ groups.push(this);
375
+ }
376
+ return groups;
377
+ }
378
+ /**
379
+ * Get the number of parents the group has.
380
+ *
381
+ * If the group is a top level group, this will return 0. If it is a child of
382
+ * a top level group, this will return 1. If it is a grandchild of a top level
383
+ * group, this will return 2, and so on.
384
+ *
385
+ * Levels will max out at 1024 to avoid recursive loops.
386
+ *
387
+ * @returns The level of the group.
388
+ */
389
+ async $getLevel() {
390
+ const tilmeld = enforceTilmeld(this);
391
+ let group = await tilmeld.Group.factory(this.guid ?? undefined);
392
+ let parent = group.parent;
393
+ await parent?.$wake();
394
+ let level = 0;
395
+ while (parent != null && parent.cdate != null && level < 1024) {
396
+ level++;
397
+ group = parent;
398
+ parent = group.parent;
399
+ await parent?.$wake();
400
+ }
401
+ return level;
402
+ }
403
+ /**
404
+ * Gets an array of enabled users in the group.
405
+ *
406
+ * @param descendants Include users in all descendant groups too.
407
+ * @param limit The limit for the query.
408
+ * @param offset The offset for the query.
409
+ * @returns An array of users.
410
+ */
411
+ async $getUsers(descendants = false, limit, offset) {
412
+ const tilmeld = enforceTilmeld(this);
413
+ let groups = [];
414
+ if (descendants) {
415
+ groups = await this.$getDescendants();
416
+ }
417
+ return await this.$nymph.getEntities({
418
+ class: tilmeld.User,
419
+ limit,
420
+ offset,
421
+ }, { type: '&', equal: ['enabled', true] }, {
422
+ type: '|',
423
+ ref: [
424
+ ['group', this],
425
+ ['groups', this],
426
+ ...groups.map((group) => [
427
+ 'group',
428
+ group,
429
+ ]),
430
+ ...groups.map((group) => [
431
+ 'groups',
432
+ group,
433
+ ]),
434
+ ],
435
+ });
226
436
  }
227
- return await this.$nymph.getEntities({
228
- class: tilmeld.User,
229
- limit,
230
- offset,
231
- }, {
232
- type: '&',
233
- equal: ['enabled', true],
234
- }, {
235
- type: '|',
236
- ref: [
237
- ['group', this],
238
- ['groups', this],
239
- ...groups.map((group) => [
240
- 'group',
241
- group,
242
- ]),
243
- ...groups.map((group) => [
244
- 'groups',
245
- group,
246
- ]),
247
- ],
248
- });
249
- }
250
- async $checkGroupname() {
251
- const tilmeld = this.$nymph.tilmeld;
252
- if (!tilmeld.config.emailUsernames) {
253
- if (this.$data.groupname == null || !this.$data.groupname.length) {
254
- return { result: false, message: 'Please specify a groupname.' };
255
- }
256
- if (tilmeld.config.maxUsernameLength > 0 &&
257
- this.$data.groupname.length > tilmeld.config.maxUsernameLength) {
258
- return {
259
- result: false,
260
- message: 'Groupnames must not exceed ' +
261
- tilmeld.config.maxUsernameLength +
262
- ' characters.',
437
+ /**
438
+ * Check that a groupname is valid.
439
+ *
440
+ * @returns An object with a boolean 'result' entry and a 'message' entry.
441
+ */
442
+ async $checkGroupname() {
443
+ const tilmeld = enforceTilmeld(this);
444
+ if (!tilmeld.config.emailUsernames) {
445
+ let [groupname, domain] = tilmeld.config.domainSupport
446
+ ? splitn(this.$data.groupname ?? '', '@', 2)
447
+ : [this.$data.groupname, null];
448
+ // Lowercase the domain part.
449
+ if (domain) {
450
+ domain = domain.toLowerCase();
451
+ this.$data.groupname = `${groupname}@${domain}`;
452
+ }
453
+ if (this.$data.groupname == null ||
454
+ !this.$data.groupname.length ||
455
+ groupname == null ||
456
+ !groupname.length) {
457
+ return { result: false, message: 'Please specify a groupname.' };
458
+ }
459
+ if (groupname.length < tilmeld.config.minUsernameLength) {
460
+ return {
461
+ result: false,
462
+ message: 'Groupnames must be at least ' +
463
+ tilmeld.config.minUsernameLength +
464
+ ' characters.',
465
+ };
466
+ }
467
+ if (groupname.length > tilmeld.config.maxUsernameLength) {
468
+ return {
469
+ result: false,
470
+ message: 'Groupnames must not exceed ' +
471
+ tilmeld.config.maxUsernameLength +
472
+ ' characters.',
473
+ };
474
+ }
475
+ if (difference(groupname.split(''), tilmeld.config.validChars.split(''))
476
+ .length) {
477
+ return {
478
+ result: false,
479
+ message: tilmeld.config.validCharsNotice,
480
+ };
481
+ }
482
+ if (!tilmeld.config.validRegex.test(groupname)) {
483
+ return {
484
+ result: false,
485
+ message: tilmeld.config.validRegexNotice,
486
+ };
487
+ }
488
+ if (domain != null) {
489
+ if (!tilmeld.config.validDomainRegex.test(domain)) {
490
+ return {
491
+ result: false,
492
+ message: tilmeld.config.validDomainRegexNotice,
493
+ };
494
+ }
495
+ if (!this.$is(tilmeld.currentUser?.group) &&
496
+ !tilmeld.gatekeeper(`tilmeld/domain/${domain}/admin`)) {
497
+ return {
498
+ result: false,
499
+ message: "You don't have the authority to manage groups on this domain.",
500
+ };
501
+ }
502
+ }
503
+ const selector = {
504
+ type: '&',
505
+ ilike: [
506
+ 'groupname',
507
+ this.$data.groupname.replace(/([\\%_])/g, (s) => `\\${s}`),
508
+ ],
263
509
  };
264
- }
265
- if ((0, lodash_1.difference)(this.$data.groupname.split(''), tilmeld.config.validChars.split('')).length) {
510
+ if (this.guid != null) {
511
+ selector['!guid'] = this.guid;
512
+ }
513
+ const test = await this.$nymph.getEntity({ class: tilmeld.Group, skipAc: true }, selector);
514
+ if (test != null) {
515
+ return { result: false, message: 'That groupname is taken.' };
516
+ }
517
+ for (let callback of this.constructor
518
+ .checkGroupnameCallbacks) {
519
+ if (callback) {
520
+ const result = await callback(this, {
521
+ groupname: this.$data.groupname,
522
+ });
523
+ if (!result.result) {
524
+ return { message: 'Groupname is not available.', ...result };
525
+ }
526
+ }
527
+ }
266
528
  return {
267
- result: false,
268
- message: tilmeld.config.validCharsNotice,
529
+ result: true,
530
+ message: this.guid != null ? 'Groupname is valid.' : 'Groupname is available!',
269
531
  };
270
532
  }
271
- if (!tilmeld.config.validRegex.test(this.$data.groupname)) {
533
+ else {
534
+ this.$data.email = this.$data.groupname;
535
+ if (this.$data.groupname == null || !this.$data.groupname.length) {
536
+ return { result: false, message: 'Please specify an email.' };
537
+ }
538
+ if (this.$data.groupname.length < tilmeld.config.minUsernameLength) {
539
+ return {
540
+ result: false,
541
+ message: 'Emails must be at least ' +
542
+ tilmeld.config.minUsernameLength +
543
+ ' characters.',
544
+ };
545
+ }
546
+ if (this.$data.groupname.length > tilmeld.config.maxUsernameLength) {
547
+ return {
548
+ result: false,
549
+ message: 'Emails must not exceed ' +
550
+ tilmeld.config.maxUsernameLength +
551
+ ' characters.',
552
+ };
553
+ }
554
+ return await this.$checkEmail();
555
+ }
556
+ }
557
+ /**
558
+ * Check that an email is unique.
559
+ *
560
+ * @returns An object with a boolean 'result' entry and a 'message' entry.
561
+ */
562
+ async $checkEmail() {
563
+ const tilmeld = enforceTilmeld(this);
564
+ if (this.$data.email === '') {
565
+ return { result: true, message: '' };
566
+ }
567
+ if (this.$data.email == null) {
568
+ return { result: false, message: 'Please specify a valid email.' };
569
+ }
570
+ if (!tilmeld.config.validEmailRegex.test(this.$data.email)) {
272
571
  return {
273
572
  result: false,
274
- message: tilmeld.config.validRegexNotice,
573
+ message: tilmeld.config.validEmailRegexNotice,
275
574
  };
276
575
  }
277
576
  const selector = {
278
577
  type: '&',
279
- ilike: [
280
- 'groupname',
281
- this.$data.groupname.replace(/([\\%_])/g, (s) => `\\${s}`),
282
- ],
578
+ ilike: ['email', this.$data.email.replace(/([\\%_])/g, (s) => `\\${s}`)],
283
579
  };
284
580
  if (this.guid != null) {
285
581
  selector['!guid'] = this.guid;
286
582
  }
287
583
  const test = await this.$nymph.getEntity({ class: tilmeld.Group, skipAc: true }, selector);
288
584
  if (test != null) {
289
- return { result: false, message: 'That groupname is taken.' };
290
- }
291
- return {
292
- result: true,
293
- message: this.guid != null ? 'Groupname is valid.' : 'Groupname is available!',
294
- };
295
- }
296
- else {
297
- this.$data.email = this.$data.groupname;
298
- if (this.$data.groupname == null || !this.$data.groupname.length) {
299
- return { result: false, message: 'Please specify an email.' };
300
- }
301
- if (tilmeld.config.maxUsernameLength > 0 &&
302
- this.$data.groupname.length > tilmeld.config.maxUsernameLength) {
303
585
  return {
304
586
  result: false,
305
- message: 'Emails must not exceed ' +
306
- tilmeld.config.maxUsernameLength +
307
- ' characters.',
587
+ message: 'That email address is already registered.',
308
588
  };
309
589
  }
310
- return await this.$checkEmail();
311
- }
312
- }
313
- async $checkEmail() {
314
- const tilmeld = this.$nymph.tilmeld;
315
- if (this.$data.email === '') {
316
- return { result: true, message: '' };
317
- }
318
- if (this.$data.email == null) {
319
- return { result: false, message: 'Please specify a valid email.' };
320
- }
321
- if (!tilmeld.config.validEmailRegex.test(this.$data.email)) {
322
590
  return {
323
- result: false,
324
- message: tilmeld.config.validEmailRegexNotice,
591
+ result: true,
592
+ message: this.guid != null ? 'Email is valid.' : 'Email address is valid!',
325
593
  };
326
594
  }
327
- const selector = {
328
- type: '&',
329
- ilike: ['email', this.$data.email.replace(/([\\%_])/g, (s) => `\\${s}`)],
330
- };
331
- if (this.guid != null) {
332
- selector['!guid'] = this.guid;
333
- }
334
- const test = await this.$nymph.getEntity({ class: tilmeld.Group, skipAc: true }, selector);
335
- if (test != null) {
336
- return {
337
- result: false,
338
- message: 'That email address is already registered.',
339
- };
595
+ async $save() {
596
+ let tilmeld = enforceTilmeld(this);
597
+ if (this.$data.groupname == null || !this.$data.groupname.trim().length) {
598
+ throw new BadUsernameError('Groupname must not be empty.');
599
+ }
600
+ // Lowercase the domain part.
601
+ if (tilmeld.config.domainSupport) {
602
+ const [groupname, domain] = splitn(this.$data.groupname ?? '', '@', 2);
603
+ if (domain) {
604
+ this.$data.groupname = `${groupname}@${domain.toLowerCase()}`;
605
+ }
606
+ }
607
+ if (tilmeld.config.domainSupport) {
608
+ const [_groupname, domain] = splitn(this.$data.groupname ?? '', '@', 2);
609
+ const [_originalGroupname, originalDomain] = splitn(this.$originalGroupname ?? '', '@', 2);
610
+ if (this.guid != null &&
611
+ ((originalDomain == null && domain != null) ||
612
+ (domain == null && originalDomain != null))) {
613
+ throw new AccessControlError("Groups can't switch to or from having a domain once created.");
614
+ }
615
+ if (!this.$skipAcWhenSaving &&
616
+ !tilmeld.gatekeeper('tilmeld/admin') &&
617
+ !tilmeld.gatekeeper('system/admin')) {
618
+ if (domain != null &&
619
+ !this.$is(tilmeld.currentUser) &&
620
+ !tilmeld.gatekeeper(`tilmeld/domain/${domain}/admin`)) {
621
+ throw new AccessControlError("You don't have the authority to modify groups on this domain.");
622
+ }
623
+ if (originalDomain != null &&
624
+ originalDomain !== domain &&
625
+ (!tilmeld.gatekeeper(`tilmeld/domain/${domain}/admin`) ||
626
+ !tilmeld.gatekeeper(`tilmeld/domain/${originalDomain}/admin`))) {
627
+ throw new AccessControlError("You don't have the authority to modify groups on this domain.");
628
+ }
629
+ }
630
+ }
631
+ // Formatting.
632
+ this.$data.groupname = this.$data.groupname.trim();
633
+ if (tilmeld.config.emailUsernames) {
634
+ this.$data.email = this.$data.groupname;
635
+ }
636
+ this.$data.email = (this.$data.email ?? '').trim();
637
+ this.$data.name = (this.$data.name ?? '').trim();
638
+ this.$data.phone = (this.$data.phone ?? '').trim();
639
+ this.$data.enabled = !!this.$data.enabled;
640
+ // Clear empty values.
641
+ if (this.$data.name === '' || !tilmeld.config.userFields.includes('name')) {
642
+ delete this.$data.name;
643
+ }
644
+ if (this.$data.email === '' ||
645
+ !tilmeld.config.userFields.includes('email')) {
646
+ delete this.$data.email;
647
+ }
648
+ if (this.$data.avatar === '') {
649
+ delete this.$data.avatar;
650
+ }
651
+ if (this.$data.phone === '' ||
652
+ !tilmeld.config.userFields.includes('phone')) {
653
+ delete this.$data.phone;
654
+ }
655
+ if (this.$data.parent == null) {
656
+ delete this.$data.parent;
657
+ }
658
+ if (this.$data.user == null) {
659
+ delete this.$data.user;
660
+ }
661
+ if (!this.$data.defaultPrimary) {
662
+ delete this.$data.defaultPrimary;
663
+ }
664
+ if (!this.$data.defaultSecondary) {
665
+ delete this.$data.defaultSecondary;
666
+ }
667
+ if (!this.$data.unverifiedSecondary) {
668
+ delete this.$data.unverifiedSecondary;
669
+ }
670
+ // Groups should never have 'system/admin', 'tilmeld/admin',
671
+ // 'tilmeld/switch', or domain admin abilities.
672
+ this.$data.abilities = (this.$data.abilities ?? []).filter((ability) => {
673
+ if (['system/admin', 'tilmeld/admin', 'tilmeld/switch'].indexOf(ability) !==
674
+ -1) {
675
+ return false;
676
+ }
677
+ if (ability == null) {
678
+ return false;
679
+ }
680
+ if (ability.startsWith('tilmeld/domain/') && ability.endsWith('/admin')) {
681
+ return false;
682
+ }
683
+ return true;
684
+ });
685
+ // Verification.
686
+ const unCheck = await this.$checkGroupname();
687
+ if (!unCheck.result) {
688
+ throw new BadUsernameError(unCheck.message);
689
+ }
690
+ if (!tilmeld.config.emailUsernames &&
691
+ tilmeld.config.userFields.includes('email')) {
692
+ const emCheck = await this.$checkEmail();
693
+ if (!emCheck.result) {
694
+ throw new BadEmailError(emCheck.message);
695
+ }
696
+ }
697
+ // Validate group parent. Make sure it's not a descendant of this group.
698
+ const parent = this.$data.parent;
699
+ await parent?.$wake();
700
+ if (parent &&
701
+ (parent.cdate == null ||
702
+ this.$is(parent) ||
703
+ (await parent.$isDescendant(this)))) {
704
+ throw new BadDataError("Group parent can't be itself or descendant of itself.");
705
+ }
706
+ try {
707
+ tilmeld.config.validatorGroup(tilmeld, this);
708
+ }
709
+ catch (e) {
710
+ throw new BadDataError(e?.message);
711
+ }
712
+ // Only one default primary group is allowed.
713
+ if (this.$data.defaultPrimary) {
714
+ const currentPrimary = await this.$nymph.getEntity({ class: tilmeld.Group }, { type: '&', truthy: 'defaultPrimary' });
715
+ if (currentPrimary != null && !this.$is(currentPrimary)) {
716
+ currentPrimary.defaultPrimary = false;
717
+ try {
718
+ if (this.$skipAcWhenSaving) {
719
+ await currentPrimary.$saveSkipAC();
720
+ }
721
+ else {
722
+ await currentPrimary.$save();
723
+ }
724
+ }
725
+ catch (e) {
726
+ throw new CouldNotChangeDefaultPrimaryGroupError('Could not change new user primary group from ' +
727
+ `${currentPrimary.groupname}.`);
728
+ }
729
+ }
730
+ }
731
+ let preGuid = this.guid;
732
+ let preCdate = this.cdate;
733
+ let preMdate = this.mdate;
734
+ return await transaction(this.$nymph, 'tilmeld-save-group-' + (this.guid || nanoid()), async (nymph) => {
735
+ this.$setNymph(nymph);
736
+ for (let callback of this.constructor
737
+ .beforeSaveCallbacks) {
738
+ if (callback) {
739
+ await callback(this.$proxy());
740
+ }
741
+ }
742
+ await super.$save();
743
+ for (let callback of this.constructor
744
+ .afterSaveCallbacks) {
745
+ if (callback) {
746
+ await callback(this.$proxy());
747
+ }
748
+ }
749
+ }, async (nymph, committed) => {
750
+ this.$setNymph(nymph);
751
+ if (committed) {
752
+ this.$originalGroupname = this.$data.groupname;
753
+ }
754
+ else {
755
+ this.guid = preGuid;
756
+ this.cdate = preCdate;
757
+ this.mdate = preMdate;
758
+ }
759
+ });
340
760
  }
341
- return {
342
- result: true,
343
- message: this.guid != null ? 'Email is valid.' : 'Email address is valid!',
344
- };
345
- }
346
- async $save() {
347
- const tilmeld = this.$nymph.tilmeld;
348
- if (this.$data.groupname == null || !this.$data.groupname.trim().length) {
761
+ /*
762
+ * This should *never* be accessible on the client.
763
+ */
764
+ async $saveSkipAC() {
765
+ this.$skipAcWhenSaving = true;
766
+ await this.$save();
767
+ }
768
+ $tilmeldSaveSkipAC() {
769
+ if (this.$skipAcWhenSaving) {
770
+ this.$skipAcWhenSaving = false;
771
+ return true;
772
+ }
349
773
  return false;
350
774
  }
351
- this.$data.groupname = this.$data.groupname.trim();
352
- if (tilmeld.config.emailUsernames) {
353
- this.$data.email = this.$data.groupname;
354
- }
355
- this.$data.email = (this.$data.email ?? '').trim();
356
- this.$data.name = (this.$data.name ?? '').trim();
357
- this.$data.phone = (this.$data.phone ?? '').trim();
358
- this.$data.enabled = !!this.$data.enabled;
359
- if (this.$data.name === '') {
360
- delete this.$data.name;
361
- }
362
- if (this.$data.email === '') {
363
- delete this.$data.email;
364
- }
365
- if (this.$data.avatar === '') {
366
- delete this.$data.avatar;
367
- }
368
- if (this.$data.phone === '') {
369
- delete this.$data.phone;
370
- }
371
- if (this.$data.parent == null) {
372
- delete this.$data.parent;
373
- }
374
- if (this.$data.user == null) {
375
- delete this.$data.user;
376
- }
377
- if (!this.$data.defaultPrimary) {
378
- delete this.$data.defaultPrimary;
379
- }
380
- if (!this.$data.defaultSecondary) {
381
- delete this.$data.defaultSecondary;
382
- }
383
- if (!this.$data.unverifiedSecondary) {
384
- delete this.$data.unverifiedSecondary;
385
- }
386
- this.$data.abilities = (0, lodash_1.difference)(this.$data.abilities ?? [], [
387
- 'system/admin',
388
- 'tilmeld/admin',
389
- null,
390
- undefined,
391
- ]);
392
- const unCheck = await this.$checkGroupname();
393
- if (!unCheck.result) {
394
- throw new errors_1.BadUsernameError(unCheck.message);
395
- }
396
- if (!tilmeld.config.emailUsernames) {
397
- const emCheck = await this.$checkEmail();
398
- if (!emCheck.result) {
399
- throw new errors_1.BadEmailError(emCheck.message);
775
+ async $delete() {
776
+ let tilmeld = enforceTilmeld(this);
777
+ const User = this.$nymph.getEntityClass(UserClass);
778
+ if (!this.$skipAcWhenDeleting && !tilmeld.gatekeeper('tilmeld/admin')) {
779
+ throw new AccessControlError("You don't have the authority to delete groups.");
400
780
  }
401
- }
402
- if (this.$data.parent &&
403
- (this.$data.parent.cdate == null ||
404
- this.$is(this.$data.parent) ||
405
- this.$data.parent.$isDescendant(this))) {
406
- throw new errors_1.BadDataError("Group parent can't be itself or descendant of itself.");
407
- }
408
- try {
409
- tilmeld.config.validatorGroup(this);
410
- }
411
- catch (e) {
412
- throw new errors_1.BadDataError(e?.message);
413
- }
414
- if (this.$data.defaultPrimary) {
415
- const currentPrimary = await this.$nymph.getEntity({ class: tilmeld.Group }, { type: '&', truthy: 'defaultPrimary' });
416
- if (currentPrimary != null && !this.$is(currentPrimary)) {
417
- currentPrimary.defaultPrimary = false;
418
- if (!(await currentPrimary.$save())) {
419
- throw new errors_1.CouldNotChangeDefaultPrimaryGroupError('Could not change new user primary group from ' +
420
- `${currentPrimary.groupname}.`);
781
+ if (this.$data.groupname !== this.$originalGroupname) {
782
+ throw new AccessControlError("You can't delete a group while switching its groupname.");
783
+ }
784
+ for (let callback of this.constructor
785
+ .beforeDeleteCallbacks) {
786
+ if (callback) {
787
+ await callback(this.$proxy());
421
788
  }
422
789
  }
423
- }
424
- return await super.$save();
425
- }
426
- async $saveSkipAC() {
427
- this.$skipAcWhenSaving = true;
428
- return await this.$save();
429
- }
430
- $tilmeldSaveSkipAC() {
431
- if (this.$skipAcWhenSaving) {
432
- this.$skipAcWhenSaving = false;
433
- return true;
434
- }
435
- return false;
436
- }
437
- async $delete() {
438
- let tilmeld = this.$nymph.tilmeld;
439
- if (!tilmeld.gatekeeper('tilmeld/admin')) {
440
- throw new errors_1.BadDataError("You don't have the authority to delete groups.");
441
- }
442
- const transaction = 'tilmeld-delete-' + this.guid;
443
- const nymph = this.$nymph;
444
- const tnymph = await nymph.startTransaction(transaction);
445
- this.$nymph = tnymph;
446
- tilmeld = this.$nymph.tilmeld;
447
- const descendants = await this.$getDescendants();
448
- if (descendants.length) {
449
- for (let curGroup of descendants) {
450
- if (!(await curGroup.$delete())) {
451
- await tnymph.rollback(transaction);
452
- this.$nymph = nymph;
453
- return false;
790
+ // Delete children.
791
+ const children = await this.$nymph.getEntities({ class: tilmeld.Group, skipAc: true }, { type: '&', ref: ['parent', this] });
792
+ if (children.length) {
793
+ for (let curGroup of children) {
794
+ if (this.$skipAcWhenDeleting) {
795
+ await curGroup.$deleteSkipAC();
796
+ }
797
+ else {
798
+ await curGroup.$delete();
799
+ }
454
800
  }
455
801
  }
456
- }
457
- const primaryUsers = await tnymph.getEntities({
458
- class: tilmeld.User,
459
- skipAc: true,
460
- }, {
461
- type: '&',
462
- ref: ['group', this],
463
- });
464
- for (let user of primaryUsers) {
465
- delete user.group;
466
- if (!(await user.$save())) {
467
- await tnymph.rollback(transaction);
468
- this.$nymph = nymph;
469
- return false;
802
+ // Remove users from this primary group.
803
+ const primaryUsers = await this.$nymph.getEntities({ class: User, skipAc: true }, { type: '&', ref: ['group', this] });
804
+ for (let user of primaryUsers) {
805
+ delete user.group;
806
+ if (this.$skipAcWhenDeleting) {
807
+ await user.$saveSkipAC();
808
+ }
809
+ else {
810
+ await user.$save();
811
+ }
812
+ }
813
+ // Remove users from this secondary group.
814
+ const secondaryUsers = await this.$nymph.getEntities({ class: User, skipAc: true }, { type: '&', ref: ['groups', this] });
815
+ for (let user of secondaryUsers) {
816
+ user.$delGroup(this);
817
+ if (this.$skipAcWhenDeleting) {
818
+ await user.$saveSkipAC();
819
+ }
820
+ else {
821
+ await user.$save();
822
+ }
823
+ }
824
+ // Delete the group.
825
+ await super.$delete();
826
+ for (let callback of this.constructor
827
+ .afterDeleteCallbacks) {
828
+ if (callback) {
829
+ await callback(this.$proxy());
830
+ }
470
831
  }
471
832
  }
472
- const secondaryUsers = await tnymph.getEntities({
473
- class: tilmeld.User,
474
- skipAc: true,
475
- }, {
476
- type: '&',
477
- ref: ['groups', this],
478
- });
479
- for (let user of secondaryUsers) {
480
- user.$delGroup(this);
481
- if (!(await user.$save())) {
482
- await tnymph.rollback(transaction);
483
- return false;
833
+ /*
834
+ * This should *never* be accessible on the client.
835
+ */
836
+ async $deleteSkipAC() {
837
+ this.$skipAcWhenDeleting = true;
838
+ await this.$delete();
839
+ }
840
+ $tilmeldDeleteSkipAC() {
841
+ if (this.$skipAcWhenDeleting) {
842
+ this.$skipAcWhenDeleting = false;
843
+ return true;
484
844
  }
845
+ return false;
485
846
  }
486
- const success = await super.$delete();
487
- if (success) {
488
- await tnymph.commit(transaction);
847
+ static on(event, callback) {
848
+ const prop = (event + 'Callbacks');
849
+ if (!(prop in this)) {
850
+ throw new Error('Invalid event type.');
851
+ }
852
+ // @ts-ignore: The callback should always be the right type here.
853
+ this[prop].push(callback);
854
+ return () => this.off(event, callback);
489
855
  }
490
- else {
491
- await tnymph.rollback(transaction);
856
+ static off(event, callback) {
857
+ const prop = (event + 'Callbacks');
858
+ if (!(prop in this)) {
859
+ return false;
860
+ }
861
+ // @ts-ignore: The callback should always be the right type here.
862
+ const i = this[prop].indexOf(callback);
863
+ if (i > -1) {
864
+ // @ts-ignore: The callback should always be the right type here.
865
+ this[prop].splice(i, 1);
866
+ }
867
+ return true;
492
868
  }
493
- this.$nymph = nymph;
494
- return success;
495
- }
496
- }
497
- exports.default = Group;
498
- Group.ETYPE = 'tilmeld_group';
499
- Group.class = 'Group';
500
- Group.DEFAULT_PRIVATE_DATA = ['email', 'phone', 'abilities', 'user'];
501
- Group.DEFAULT_ALLOWLIST_DATA = [];
502
- Group.clientEnabledStaticMethods = [
503
- 'getPrimaryGroups',
504
- 'getSecondaryGroups',
505
- ];
506
- Group.searchRestrictedData = [...Group.DEFAULT_PRIVATE_DATA];
869
+ };
870
+ })();
871
+ /**
872
+ * A user group data model.
873
+ *
874
+ * Written by Hunter Perrin for SciActive.
875
+ *
876
+ * @author Hunter Perrin <hperrin@port87.com>
877
+ * @copyright SciActive Inc
878
+ * @see http://nymph.io/
879
+ */
880
+ export default Group;
507
881
  //# sourceMappingURL=Group.js.map