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

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