-
-
Notifications
You must be signed in to change notification settings - Fork 768
/
Copy pathgroup-service.ts
358 lines (313 loc) · 11.1 KB
/
group-service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import type {
ICreateGroupModel,
IGroup,
IGroupModel,
IGroupProject,
IGroupRole,
IGroupUser,
} from '../types/group';
import {
GroupDeletedEvent,
GroupUpdatedEvent,
SYSTEM_USER_AUDIT,
type IAuditUser,
type IUnleashConfig,
type IUnleashStores,
} from '../types';
import type { IGroupStore } from '../types/stores/group-store';
import type { Logger } from '../logger';
import BadDataError from '../error/bad-data-error';
import {
GROUP_CREATED,
GroupUserAdded,
GroupUserRemoved,
ScimGroupsDeleted,
type IBaseEvent,
} from '../types/events';
import NameExistsError from '../error/name-exists-error';
import type { IAccountStore } from '../types/stores/account-store';
import type { IUser } from '../types/user';
import type EventService from '../features/events/event-service';
import { SSO_SYNC_USER } from '../db/group-store';
import type { IGroupWithProjectRoles } from '../types/stores/access-store';
import { NotFoundError } from '../error';
const setsAreEqual = (firstSet, secondSet) =>
firstSet.size === secondSet.size &&
[...firstSet].every((x) => secondSet.has(x));
export class GroupService {
private groupStore: IGroupStore;
private eventService: EventService;
private accountStore: IAccountStore;
private logger: Logger;
constructor(
stores: Pick<IUnleashStores, 'groupStore' | 'accountStore'>,
{ getLogger }: Pick<IUnleashConfig, 'getLogger'>,
eventService: EventService,
) {
this.logger = getLogger('service/group-service.js');
this.groupStore = stores.groupStore;
this.eventService = eventService;
this.accountStore = stores.accountStore;
}
async getAll(): Promise<IGroupModel[]> {
const groups = await this.groupStore.getAll();
const allGroupUsers = await this.groupStore.getAllUsersByGroups(
groups.map((g) => g.id),
);
const users = await this.accountStore.getAllWithId(
allGroupUsers.map((u) => u.userId),
);
const groupProjects = await this.groupStore.getGroupProjects(
groups.map((g) => g.id),
);
return groups.map((group) => {
const mappedGroup = this.mapGroupWithUsers(
group,
allGroupUsers,
users,
);
return this.mapGroupWithProjects(groupProjects, mappedGroup);
});
}
async getAllWithId(ids: number[]) {
return this.groupStore.getAllWithId(ids);
}
mapGroupWithProjects(
groupProjects: IGroupProject[],
group: IGroupModel,
): IGroupModel {
return {
...group,
projects: groupProjects
.filter((project) => project.groupId === group.id)
.map((project) => project.project),
};
}
async getGroup(id: number): Promise<IGroupModel> {
const group = await this.groupStore.get(id);
if (group === undefined) {
throw new NotFoundError(`Could not find group with id ${id}`);
}
const groupUsers = await this.groupStore.getAllUsersByGroups([id]);
const users = await this.accountStore.getAllWithId(
groupUsers.map((u) => u.userId),
);
return this.mapGroupWithUsers(group, groupUsers, users);
}
async isScimGroup(id: number): Promise<boolean> {
const group = await this.groupStore.get(id);
return Boolean(group?.scimId);
}
async createGroup(
group: ICreateGroupModel,
auditUser: IAuditUser,
): Promise<IGroup> {
await this.validateGroup(group);
const newGroup = await this.groupStore.create(group);
if (group.users) {
await this.groupStore.addUsersToGroup(
newGroup.id,
group.users,
auditUser.username,
);
}
const newUserIds = group.users?.map((g) => g.user.id);
await this.eventService.storeEvent({
type: GROUP_CREATED,
createdBy: auditUser.username,
createdByUserId: auditUser.id,
ip: auditUser.ip,
data: { ...group, users: newUserIds },
});
return newGroup;
}
async updateGroup(
group: IGroupModel,
auditUser: IAuditUser,
): Promise<IGroup> {
const existingGroup = await this.groupStore.get(group.id);
await this.validateGroup(group, existingGroup);
const newGroup = await this.groupStore.update(group);
const existingUsers = await this.groupStore.getAllUsersByGroups([
group.id,
]);
const existingUserIds = existingUsers.map((g) => g.userId);
const deletableUsers = existingUsers.filter(
(existingUser) =>
!group.users.some(
(groupUser) => groupUser.user.id === existingUser.userId,
),
);
await this.groupStore.updateGroupUsers(
newGroup.id,
group.users.filter(
(user) => !existingUserIds.includes(user.user.id),
),
deletableUsers,
auditUser.username,
);
const newUserIds = group.users.map((g) => g.user.id);
await this.eventService.storeEvent(
new GroupUpdatedEvent({
data: { ...newGroup, users: newUserIds },
preData: { ...existingGroup, users: existingUserIds },
auditUser,
}),
);
return newGroup;
}
async getProjectGroups(
projectId: string,
): Promise<IGroupWithProjectRoles[]> {
const projectGroups = await this.groupStore.getProjectGroups(projectId);
if (projectGroups.length > 0) {
const groups = await this.groupStore.getAllWithId(
projectGroups.map((g) => g.id),
);
const groupUsers = await this.groupStore.getAllUsersByGroups(
groups.map((g) => g.id),
);
const users = await this.accountStore.getAllWithId(
groupUsers.map((u) => u.userId),
);
return groups.flatMap((group) => {
return projectGroups
.filter((gr) => gr.id === group.id)
.map((groupRole) => ({
...this.mapGroupWithUsers(group, groupUsers, users),
...groupRole,
}));
});
}
return [];
}
async deleteGroup(id: number, auditUser: IAuditUser): Promise<void> {
const group = await this.groupStore.get(id);
if (group === undefined) {
/// Group was already deleted, or never existed, do nothing
return;
}
const existingUsers = await this.groupStore.getAllUsersByGroups([
group.id,
]);
const existingUserIds = existingUsers.map((g) => g.userId);
await this.groupStore.delete(id);
await this.eventService.storeEvent(
new GroupDeletedEvent({
preData: { ...group, users: existingUserIds },
auditUser,
}),
);
}
async validateGroup(
group: IGroupModel | ICreateGroupModel,
existingGroup?: IGroup,
): Promise<void> {
if (!group.name) {
throw new BadDataError('Group name cannot be empty');
}
if (!existingGroup || existingGroup.name !== group.name) {
if (await this.groupStore.existsWithName(group.name)) {
throw new NameExistsError('Group name already exists');
}
}
if (existingGroup && Boolean(existingGroup.scimId)) {
if (existingGroup.name !== group.name) {
throw new BadDataError(
'Cannot update the name of a SCIM group',
);
}
const existingUsers = new Set(
(
await this.groupStore.getAllUsersByGroups([
existingGroup.id,
])
).map((g) => g.userId),
);
const newUsers = new Set(group.users?.map((g) => g.user.id) || []);
if (!setsAreEqual(existingUsers, newUsers)) {
throw new BadDataError('Cannot update users of a SCIM group');
}
}
}
async getRolesForProject(projectId: string): Promise<IGroupRole[]> {
return this.groupStore.getProjectGroupRoles(projectId);
}
async syncExternalGroups(
userId: number,
externalGroups: string[],
createdBy?: string, // deprecated
createdByUserId?: number, // deprecated
): Promise<void> {
if (Array.isArray(externalGroups)) {
const newGroups = await this.groupStore.getNewGroupsForExternalUser(
userId,
externalGroups,
);
await this.groupStore.addUserToGroups(
userId,
newGroups.map((g) => g.id),
SSO_SYNC_USER,
);
const oldGroups = await this.groupStore.getOldGroupsForExternalUser(
userId,
externalGroups,
);
await this.groupStore.deleteUsersFromGroup(oldGroups);
const events: IBaseEvent[] = [];
for (const group of newGroups) {
events.push(
new GroupUserAdded({
userId,
groupId: group.id,
auditUser: SYSTEM_USER_AUDIT,
}),
);
}
for (const group of oldGroups) {
events.push(
new GroupUserRemoved({
userId,
groupId: group.groupId,
auditUser: SYSTEM_USER_AUDIT,
}),
);
}
await this.eventService.storeEvents(events);
}
}
async deleteScimGroups(auditUser: IAuditUser): Promise<void> {
await this.groupStore.deleteScimGroups();
await this.eventService.storeEvent(
new ScimGroupsDeleted({
data: null,
auditUser,
}),
);
}
private mapGroupWithUsers(
group: IGroup,
allGroupUsers: IGroupUser[],
allUsers: IUser[],
): IGroupModel {
const groupUsers = allGroupUsers.filter(
(user) => user.groupId === group.id,
);
const groupUsersId = groupUsers.map((user) => user.userId);
const selectedUsers = allUsers.filter((user) =>
groupUsersId.includes(user.id),
);
const finalUsers = selectedUsers.map((user) => {
const roleUser = groupUsers.find((gu) => gu.userId === user.id);
return {
user: user,
joinedAt: roleUser?.joinedAt,
createdBy: roleUser?.createdBy,
};
});
return { ...group, users: finalUsers };
}
async getGroupsForUser(userId: number): Promise<IGroup[]> {
return this.groupStore.getGroupsForUser(userId);
}
}