-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgroup.service.ts
More file actions
550 lines (484 loc) · 15.1 KB
/
group.service.ts
File metadata and controls
550 lines (484 loc) · 15.1 KB
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
import {
BadRequestException,
Injectable,
Logger,
NotFoundException,
NotAcceptableException,
} from '@nestjs/common';
import { pick, uniq } from 'lodash';
import { HttpService } from '@nestjs/axios';
import { lastValueFrom } from 'rxjs';
import {
CreateGroupDto,
GroupCriteria,
GetGroupCriteria,
GroupResponseDto,
UpdateGroupDto,
PatchGroupDto,
GetGroupResponseDto,
} from 'src/dto/group.dto';
import { PaginatedResponse } from 'src/dto/pagination.dto';
import { CommonConfig } from 'src/shared/config/common.config';
import { GroupStatus } from 'src/shared/enums/groupStatus.enum';
import {
JwtUser,
isAdmin as checkIsAdmin,
} from 'src/shared/modules/global/jwt.service';
import { PrismaService } from 'src/shared/modules/global/prisma.service';
import {
omitAdminFields,
checkGroupName,
deleteGroupCascade,
ensureGroupMember,
parseCommaSeparatedString,
postBusEvent,
} from 'src/shared/helper';
import { M2MService } from 'src/shared/modules/global/m2m.service';
const ADMIN_GROUP_FIELDS: string[] = [];
export const ALLOWED_FIELD_NAMES = [
'id',
'createdAt',
'createdBy',
'updatedAt',
'updatedBy',
'name',
'description',
'privateGroup',
'selfRegister',
'domain',
'organizationId',
'oldId',
'status',
];
@Injectable()
export class GroupService {
private readonly logger: Logger = new Logger(GroupService.name);
constructor(
private readonly prisma: PrismaService,
private readonly m2mService: M2MService,
private readonly httpService: HttpService,
) {}
/**
* Search groups
* @param criteria query criteria
*/
async search(
criteria: GroupCriteria,
isAdmin: boolean,
): Promise<PaginatedResponse<GroupResponseDto>> {
this.logger.debug(`Search Group - Criteria - ${JSON.stringify(criteria)}`);
if (
(criteria.memberId || criteria.universalUID) &&
!criteria.membershipType
) {
throw new BadRequestException(
'The membershipType parameter should be provided if memberId or universalUID is provided.',
);
}
if (
!(criteria.memberId || criteria.universalUID) &&
criteria.membershipType
) {
throw new BadRequestException(
'The memberId or universalUID parameter should be provided if membershipType is provided.',
);
}
const prismaFilter = {
where: {},
} as any;
if (criteria.memberId || criteria.universalUID) {
prismaFilter.where.members = {
some: {
membershipType: criteria.membershipType,
},
};
if (criteria.universalUID) {
const membersFound = await this.prisma.user.findMany({
distinct: ['id'],
where: {
universalUID: criteria.universalUID,
},
select: {
id: true,
},
});
if (membersFound && membersFound.length > 0) {
const memberIds = membersFound.map((item) => item.id);
prismaFilter.where.members.some.memberId = {
in: memberIds,
};
}
}
if (criteria.memberId) {
prismaFilter.where.members.some.memberId = criteria.memberId;
}
}
if (criteria.oldId) {
prismaFilter.where.oldId = criteria.oldId;
}
if (criteria.name) {
prismaFilter.where.name = {
contains: criteria.name,
mode: 'insensitive',
};
}
if (criteria.ssoId) {
prismaFilter.where.ssoId = {
equals: criteria.ssoId,
mode: 'insensitive',
};
}
if (criteria.organizationId) {
prismaFilter.where.organizationId = {
equals: criteria.organizationId,
mode: 'insensitive',
};
}
if (criteria.selfRegister != undefined) {
prismaFilter.where.selfRegister = criteria.selfRegister;
}
if (criteria.privateGroup != undefined) {
prismaFilter.where.privateGroup = criteria.privateGroup;
}
if (!isAdmin) {
prismaFilter.where.status = GroupStatus.ACTIVE;
}
const total = await this.prisma.group.count(prismaFilter);
// prepare pagination
const take = criteria.perPage;
const skip = take * (criteria.page - 1);
prismaFilter.take = take;
prismaFilter.skip = skip;
prismaFilter.orderBy = { oldId: 'desc' };
// populate parent/sub groups
if (criteria.includeParentGroup || criteria.includeSubGroups) {
prismaFilter.include = {};
if (criteria.includeParentGroup) {
prismaFilter.include.parentGroups = true;
}
if (criteria.includeSubGroups) {
prismaFilter.include.subGroups = true;
}
}
this.logger.debug(`The prisma filter is: ${JSON.stringify(prismaFilter)}`);
let groups = await this.prisma.group.findMany(prismaFilter);
if (!isAdmin) {
groups = groups.map((item) => {
return omitAdminFields(item, ADMIN_GROUP_FIELDS);
});
}
return {
data: groups as any,
page: criteria.page,
perPage: criteria.perPage,
total: total,
};
}
/**
* Get group by id
* @param authUser the user
* @param groupId group id
* @param criteria the search criteria
* @param oldId old id
* @returns response dto
*/
async getGroup(
authUser: JwtUser,
groupId: string,
criteria: GetGroupCriteria,
oldId?: string,
): Promise<GetGroupResponseDto> {
const isAdmin = checkIsAdmin(authUser);
this.logger.debug(
//eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-base-to-string
`Get Group - admin - ${isAdmin} - user - ${authUser} , groupId - ${groupId} , criteria - ${JSON.stringify(criteria)}`,
);
if (criteria.includeSubGroups && criteria.includeParentGroup) {
throw new BadRequestException(
'includeSubGroups and includeParentGroup can not be both true',
);
}
const selectFields =
parseCommaSeparatedString(criteria.fields, ALLOWED_FIELD_NAMES) ||
ALLOWED_FIELD_NAMES;
const buildPrismaFilter = (whereClause: Record<string, string>) => {
const prismaFilter: any = {
where: {
...whereClause,
},
};
if (
criteria.includeSubGroups ||
criteria.includeParentGroup ||
criteria.flattenGroupIdTree
) {
prismaFilter.include = {};
if (criteria.includeSubGroups || criteria.flattenGroupIdTree) {
if (criteria.oneLevel) {
prismaFilter.include.subGroups = true;
} else {
// max 3 level subGroups
prismaFilter.include.subGroups = {
include: {
subGroups: {
include: {
subGroups: true,
},
},
},
};
}
}
if (criteria.includeParentGroup) {
if (criteria.oneLevel) {
prismaFilter.include.parentGroups = true;
} else {
// max 3 level parentGroups
prismaFilter.include.parentGroups = {
include: {
parentGroups: {
include: {
parentGroups: true,
},
},
},
};
}
}
}
return prismaFilter;
};
const lookupOrder: Array<{ field: 'id' | 'oldId'; value: string }> = [];
if (groupId) {
lookupOrder.push({ field: 'id', value: groupId });
}
if (oldId) {
lookupOrder.push({ field: 'oldId', value: oldId });
} else if (groupId) {
lookupOrder.push({ field: 'oldId', value: groupId });
}
if (!lookupOrder.length) {
lookupOrder.push({ field: 'id', value: groupId });
}
let entity;
let resolvedGroupId: string | undefined;
for (const lookup of lookupOrder) {
const prismaFilter = buildPrismaFilter({ [lookup.field]: lookup.value });
// eslint-disable-next-line no-await-in-loop
entity = await this.prisma.group.findFirst(prismaFilter);
if (entity) {
resolvedGroupId = entity.id;
break;
}
}
if (!entity) {
const identifier = oldId ?? groupId ?? '';
throw new NotFoundException(`Not group found with id or oldId: ${identifier}`);
}
const groupIdentifier = resolvedGroupId ?? entity.id;
// if the group is private, the user needs to be a member of the group, or an admin
if (entity.privateGroup && !isAdmin) {
await ensureGroupMember(
this.prisma,
groupIdentifier,
authUser.userId || '',
);
}
if (criteria.flattenGroupIdTree) {
const groupIdTree: string[] = [];
const groupEntity = entity as any;
// max 3 level subGroups
if (groupEntity.subGroups) {
groupEntity.subGroups.forEach((subGroupL1: any) => {
groupIdTree.push(subGroupL1.id);
if (subGroupL1.subGroups) {
subGroupL1.subGroups.forEach((subGroupL2: any) => {
groupIdTree.push(subGroupL2.id);
if (subGroupL2.subGroups) {
subGroupL2.subGroups.forEach((subGroupL3: any) => {
groupIdTree.push(subGroupL3.id);
});
}
});
}
});
}
(entity as GetGroupResponseDto).flattenGroupIdTree = uniq(groupIdTree);
}
if (criteria.includeSubGroups) {
selectFields.push('subGroups');
}
if (criteria.includeParentGroup) {
selectFields.push('parentGroups');
}
if (criteria.flattenGroupIdTree) {
selectFields.push('flattenGroupIdTree');
}
entity = pick(entity, selectFields) as any;
if (!isAdmin) {
entity = omitAdminFields(entity, ADMIN_GROUP_FIELDS);
}
return entity as GetGroupResponseDto;
}
/**
* Create group.
* @param authUser auth user
* @param dto dto
* @returns response
*/
async createGroup(
authUser: JwtUser,
dto: CreateGroupDto,
): Promise<GroupResponseDto> {
this.logger.debug(
//eslint-disable-next-line @typescript-eslint/no-base-to-string, @typescript-eslint/restrict-template-expressions
`Create Group - user - ${authUser} , data - ${JSON.stringify(dto)}`,
);
return this.prisma.$transaction(async (tx) => {
await checkGroupName(dto.name, '', tx);
// create group
const createdBy = authUser.userId ? authUser.userId : '00000000';
const createdAt = new Date().toISOString();
const groupData = {
...dto,
domain: dto.domain || '',
ssoId: dto.ssoId || '',
organizationId: dto.organizationId || '',
createdBy,
createdAt,
// Initialize updated fields to match created fields on creation
updatedBy: createdBy,
updatedAt: createdAt,
};
const result = await tx.group.create({ data: groupData });
await postBusEvent(CommonConfig.KAFKA_GROUP_CREATE_TOPIC, result);
return result as GroupResponseDto;
});
}
/**
* Check the group whether exists
* @param groupId the group id
* @param isAdmin the flag whether user is admin
* @param prismaTx the prisma transaction
*/
private async checkGroupExists(
groupId: string,
isAdmin: boolean,
prismaTx?: any,
) {
const prismaFilter = {
where: {
id: groupId,
status: isAdmin ? undefined : GroupStatus.ACTIVE,
},
};
const prismaIns = prismaTx ? prismaTx : this.prisma;
const existing = await prismaIns.group.findUnique(prismaFilter);
if (!existing) {
throw new NotFoundException(`Not found group of id ${groupId}`);
}
//eslint-disable-next-line @typescript-eslint/no-unsafe-return
return existing;
}
/**
* Update group by id
* @param authUser auth user
* @param groupId group id
* @param dto update dto
*/
async updateGroup(authUser: JwtUser, groupId: string, dto: UpdateGroupDto) {
this.logger.debug(
//eslint-disable-next-line @typescript-eslint/no-base-to-string, @typescript-eslint/restrict-template-expressions
`Update Group - user - ${authUser} , data - ${JSON.stringify(dto)}`,
);
return this.prisma.$transaction(async (tx) => {
const isAdmin = checkIsAdmin(authUser);
const oldGroup = await this.checkGroupExists(groupId, isAdmin, tx);
if (dto.name) {
await checkGroupName(dto.name, groupId, tx);
}
const updatedBy = authUser.userId ?? '00000000';
const entity = await tx.group.update({
where: { id: groupId },
data: {
...dto,
domain: dto.domain || '',
ssoId: dto.ssoId || '',
organizationId: dto.organizationId || '',
oldId: dto.oldId || '',
updatedBy,
updatedAt: new Date().toISOString(),
},
});
await postBusEvent(CommonConfig.KAFKA_GROUP_UPDATE_TOPIC, {
...entity,
oldName: oldGroup.name,
});
return entity;
});
}
/**
* Patch group by id
* @param authUser auth user
* @param groupId group id
* @param dto patch dto
*/
async patchGroup(authUser: JwtUser, groupId: string, dto: PatchGroupDto) {
this.logger.debug(
//eslint-disable-next-line @typescript-eslint/no-base-to-string, @typescript-eslint/restrict-template-expressions
`Patch Group - user - ${authUser} , data - ${JSON.stringify(dto)}`,
);
return this.prisma.$transaction(async (tx) => {
const updatedBy = authUser.userId ?? '00000000';
const isAdmin = checkIsAdmin(authUser);
await this.checkGroupExists(groupId, isAdmin, tx);
const entity = await tx.group.update({
where: { id: groupId },
data: {
oldId: dto.oldId,
updatedBy,
updatedAt: new Date().toISOString(),
},
});
return entity;
});
}
/**
* Delete group by id
* @param groupId group id
* @param isAdmin the flag whether user is admin
* @returns deleted group
*/
async deleteGroup(groupId: string, isAdmin: boolean) {
this.logger.debug(`Delete Group - ${groupId}`);
//eslint-disable-next-line @typescript-eslint/no-unsafe-return
return this.prisma.$transaction(async (tx) => {
const group = await this.checkGroupExists(groupId, isAdmin, tx);
//check if group is associated with challenges or not; if yes, don't delete the group else delete
const token = await this.m2mService.getM2MToken();
const challengeFilterURL =
CommonConfig.CHALLENGE_API_URL + `?groups=["${groupId}"]`;
const challenges = (await lastValueFrom(
this.httpService.get<object[]>(challengeFilterURL, {
headers: {
'User-Agent': 'Request-Promise',
'Content-Type': 'application/json',
Authorization: 'Bearer ' + token,
},
}),
)) as any;
if (challenges && challenges.data && challenges.data.length > 0) {
throw new NotAcceptableException(
`group ${groupId} is associated with challenges and can not be deleted`,
);
}
const deletedGroups = deleteGroupCascade(tx, groupId);
const kafkaPayload = {
groups: deletedGroups,
};
await postBusEvent(CommonConfig.KAFKA_GROUP_DELETE_TOPIC, kafkaPayload);
//eslint-disable-next-line @typescript-eslint/no-unsafe-return
return group;
});
}
}