@tomei/sso 0.47.0 → 0.48.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (22) hide show
  1. package/dist/src/components/user-group/user-group.d.ts +5 -0
  2. package/dist/src/components/user-group/user-group.js +73 -0
  3. package/dist/src/components/user-group/user-group.js.map +1 -1
  4. package/dist/src/components/user-privilege/user-privilege.d.ts +42 -0
  5. package/dist/src/components/user-privilege/user-privilege.js +338 -0
  6. package/dist/src/components/user-privilege/user-privilege.js.map +1 -1
  7. package/dist/src/components/user-privilege/user-privilege.repository.d.ts +1 -0
  8. package/dist/src/components/user-privilege/user-privilege.repository.js +25 -0
  9. package/dist/src/components/user-privilege/user-privilege.repository.js.map +1 -1
  10. package/dist/src/components/user-system-access/user-system-access.d.ts +12 -0
  11. package/dist/src/components/user-system-access/user-system-access.js +148 -0
  12. package/dist/src/components/user-system-access/user-system-access.js.map +1 -1
  13. package/dist/src/components/user-system-access/user-system-access.repository.d.ts +1 -0
  14. package/dist/src/components/user-system-access/user-system-access.repository.js +25 -0
  15. package/dist/src/components/user-system-access/user-system-access.repository.js.map +1 -1
  16. package/dist/tsconfig.tsbuildinfo +1 -1
  17. package/package.json +1 -1
  18. package/src/components/user-group/user-group.ts +134 -0
  19. package/src/components/user-privilege/user-privilege.repository.ts +14 -0
  20. package/src/components/user-privilege/user-privilege.ts +588 -0
  21. package/src/components/user-system-access/user-system-access.repository.ts +14 -0
  22. package/src/components/user-system-access/user-system-access.ts +298 -0
@@ -1,6 +1,19 @@
1
1
  import { ClassError, ObjectBase } from '@tomei/general';
2
2
  import { IUserPrivilegeAttr } from '../../interfaces/user-privilege.interface';
3
3
  import { UserPrivilegeRepository } from './user-privilege.repository';
4
+ import { User as UserClass } from '../login-user/user';
5
+ import { ApplicationConfig } from '@tomei/config';
6
+ import SystemPrivilegeModel from '../../models/system-privilege.entity';
7
+ import SystemModel from '../../models/system.entity';
8
+ import { UserGroupRepository } from '../user-group/user-group.repository';
9
+ import GroupModel from '../../models/group.entity';
10
+ import User from '../../models/user.entity';
11
+ import { GroupPrivilegeRepository } from '../group-privilege/group-privilege.repository';
12
+ import { User as UserLogin } from '../login-user/user';
13
+ import { SystemPrivilegeRepository } from '../system-privilege/system-privilege.repository';
14
+ import { Op } from 'sequelize';
15
+ import { ActionEnum, Activity } from '@tomei/activity-history';
16
+ import { UserGroup } from 'components/user-group';
4
17
 
5
18
  export class UserPrivilege extends ObjectBase {
6
19
  TableName = 'sso_UserPrivilege';
@@ -33,6 +46,9 @@ export class UserPrivilege extends ObjectBase {
33
46
  }
34
47
 
35
48
  private static _Repository = new UserPrivilegeRepository();
49
+ private static _UserGroupRepository = new UserGroupRepository();
50
+ private static _GroupPrivilegeRepository = new GroupPrivilegeRepository();
51
+ private static _SystemPrivilegeRepository = new SystemPrivilegeRepository();
36
52
 
37
53
  private constructor(userPrivilegeAttr?: IUserPrivilegeAttr) {
38
54
  super();
@@ -71,4 +87,576 @@ export class UserPrivilege extends ObjectBase {
71
87
  throw error;
72
88
  }
73
89
  }
90
+
91
+ public static async findAll(
92
+ loginUser: UserClass, //The currently logged-in user initiating the request.
93
+ dbTransaction: any, //The active database transaction to ensure consistency during the query.
94
+ whereOption: {
95
+ //An object containing filter criteria, specifically:
96
+ UserId: number; //The ID of the user whose system access records are to be retrieved.
97
+ SystemCode?: string;
98
+ },
99
+ pagination: {
100
+ //An object containing pagination parameters:
101
+ page: number; //The current page number to retrieve.
102
+ limit: number; //The number of records to retrieve per page.
103
+ },
104
+ ): Promise<{
105
+ records: {
106
+ UserPrivilegeId: number;
107
+ SystemPrivilegeId: string;
108
+ PrivilegeCode: string;
109
+ SystemName: string;
110
+ Status: string;
111
+ CreatedBy: string;
112
+ CreatedAt: Date;
113
+ UpdatedBy: string;
114
+ UpdatedAt: Date;
115
+ }[];
116
+ pagination: {
117
+ currentPage: number;
118
+ pageSize: number;
119
+ totalRecords: number;
120
+ };
121
+ }> {
122
+ try {
123
+ // Privilege Checking:
124
+ // Call loginUser.checkPrivileges() method by passing:
125
+ // SystemCode: Retrieve from app config.
126
+ // PrivilegeCode: 'USER_PRIVILEGE_LIST'.
127
+ const systemCode =
128
+ ApplicationConfig.getComponentConfigValue('system-code');
129
+ const privilegeCode = 'USER_PRIVILEGE_LIST';
130
+ const isPrivileged = await loginUser.checkPrivileges(
131
+ systemCode,
132
+ privilegeCode,
133
+ );
134
+ if (!isPrivileged) {
135
+ throw new ClassError(
136
+ 'UserPrivilege',
137
+ 'UserPrivilegeErrMsg01',
138
+ 'You do not have permission to access this resource.',
139
+ );
140
+ }
141
+
142
+ const options: any = {
143
+ where: {
144
+ UserId: whereOption.UserId,
145
+ },
146
+ offset: (pagination.page - 1) * pagination.limit,
147
+ limit: pagination.limit,
148
+ transaction: dbTransaction,
149
+ include: [
150
+ {
151
+ model: SystemPrivilegeModel,
152
+ attributes: ['PrivilegeCode'],
153
+ include: [
154
+ {
155
+ model: SystemModel,
156
+ attributes: ['Name'],
157
+ },
158
+ ],
159
+ },
160
+ {
161
+ model: User,
162
+ as: 'CreatedByUser',
163
+ attributes: ['FullName'],
164
+ },
165
+ {
166
+ model: User,
167
+ as: 'UpdatedByUser',
168
+ attributes: ['FullName'],
169
+ },
170
+ ],
171
+ };
172
+ const { count, rows } = await this._Repository.findAllWithPagination(
173
+ options,
174
+ );
175
+ return {
176
+ records: rows.map((record) => {
177
+ return {
178
+ UserPrivilegeId: record.UserPrivilegeId,
179
+ SystemPrivilegeId: record.SystemPrivilegeId,
180
+ PrivilegeCode: record.Privilege.PrivilegeCode,
181
+ SystemName: record.Privilege.System.Name,
182
+ Status: record.Status,
183
+ CreatedBy: record.CreatedByUser.FullName,
184
+ CreatedAt: record.CreatedAt,
185
+ UpdatedBy: record.UpdatedByUser.FullName,
186
+ UpdatedAt: record.UpdatedAt,
187
+ };
188
+ }),
189
+ pagination: {
190
+ currentPage: pagination.page,
191
+ pageSize: pagination.limit,
192
+ totalRecords: count,
193
+ },
194
+ };
195
+ } catch (error) {
196
+ throw error;
197
+ }
198
+ }
199
+
200
+ public static async findAllInheritedPrivileges(
201
+ UserId: number, //The ID of the user for whom privileges are being retrieved.
202
+ loginUser: UserClass, //The currently logged-in user initiating the request.
203
+ dbTransaction: any, //The active database transaction to ensure consistency during the query.
204
+ ) {
205
+ try {
206
+ // Part 1: Privilege Checking
207
+ // Call loginUser.checkPrivileges() to ensure the user has permission to retrieve system access information.
208
+ // SystemCode: Retrieve from app config.
209
+ // PrivilegeCode: 'USER_PRIVILEGE_LIST'.
210
+ // If the privilege check fails, throw an error with a 403 Forbidden status.
211
+ const systemCode =
212
+ ApplicationConfig.getComponentConfigValue('system-code');
213
+ const privilegeCode = 'USER_PRIVILEGE_LIST';
214
+ const isPrivileged = await loginUser.checkPrivileges(
215
+ systemCode,
216
+ privilegeCode,
217
+ );
218
+ if (!isPrivileged) {
219
+ throw new ClassError(
220
+ 'UserPrivilege',
221
+ 'UserPrivilegeErrMsg01',
222
+ 'You do not have permission to access this resource.',
223
+ );
224
+ }
225
+
226
+ // Part 2: Retrieve User Groups
227
+ // Query the sso_UserGroup table to find all active groups the user belongs to.
228
+ // Join with the sso_Group table to retrieve the GroupCode, GroupName, and InheritGroupPrivilegeYNfields.
229
+ // Ensure that the value of InheritGroupPrivilegeYN is explicitly 'Y' or 'N' for each group.
230
+ // If InheritGroupPrivilegeYN is not set, default it to 'N'.
231
+ // Return only active groups (based on Status field).
232
+ // The query should return the following fields for each group:
233
+ // - GroupCode
234
+ // - GroupName
235
+ // - InheritPrivilegeYN
236
+
237
+ const userGroups = await UserPrivilege._UserGroupRepository.findAll({
238
+ where: {
239
+ UserId,
240
+ },
241
+ include: [
242
+ {
243
+ model: GroupModel,
244
+ attributes: ['GroupCode', 'Name', 'InheritParentPrivilegeYN'],
245
+ },
246
+ ],
247
+ transaction: dbTransaction,
248
+ });
249
+
250
+ const listOfGroups = userGroups.map((groups) => {
251
+ let inheritPrivilegeYN = groups.InheritGroupPrivilegeYN;
252
+ if (inheritPrivilegeYN !== 'Y') {
253
+ inheritPrivilegeYN = 'N';
254
+ }
255
+ return {
256
+ UserGroupId: groups.UserGroupId,
257
+ GroupCode: groups.GroupCode,
258
+ GroupName: groups.Group.Name,
259
+ InheritPrivilegeYN: inheritPrivilegeYN,
260
+ Status: groups.Status,
261
+ };
262
+ });
263
+
264
+ // Part 3: Retrieve System Privilege for Groups with Inheritance
265
+ // For each group where InheritGroupPrivilegeYN = 'Y', query the sso_GroupPrivilege table to retrieve system privilege details.
266
+ // Join with the sso_SystemPrivilege table to fetch system details (PrivilegeCode).
267
+ // Ensure only active group privilege (Status = 'Active') are included.
268
+ // For each privilege, retrieve the following fields:
269
+ // - GroupPrivilegeId (from sso_GroupPrivilege.GroupPrivilegeId)
270
+ // - SystemPrivilegeId (from sso_GroupPrivilege.SystemPrivilegeId)
271
+ // - PrivilegeCode (from sso_SystemPrivilege.SystemCode)
272
+ // - Status (from sso_GroupPrivilege.Status)
273
+ // - CreatedAt (from sso_GroupPrivilege.CreatedAt)
274
+ // - UpdatedAt (from sso_GroupPrivilege.UpdatedAt)
275
+
276
+ const userGroupPrivilege = [];
277
+ for (let i = 0; i < listOfGroups.length; i++) {
278
+ const group = await listOfGroups[i];
279
+ const data = {
280
+ UserGroupId: group.UserGroupId,
281
+ GroupCode: group.GroupCode,
282
+ GroupName: group.GroupName,
283
+ InheritPrivilegeYN: group.InheritPrivilegeYN,
284
+ systems: [],
285
+ };
286
+
287
+ // Part 4: Handling Non-Inherited Groups
288
+ // For groups where InheritGroupSPrivilegeYN = 'N', return the group details without group privilege records.
289
+ // Set the Privileges field to an empty array or null to indicate no inherited privilege for those groups.
290
+ if (group.InheritPrivilegeYN === 'Y') {
291
+ if (group.Status === 'Active') {
292
+ const options: any = {
293
+ where: {
294
+ GroupCode: group.GroupCode,
295
+ Status: 'Active',
296
+ },
297
+ transaction: dbTransaction,
298
+ include: [
299
+ {
300
+ model: SystemPrivilegeModel,
301
+ attributes: ['PrivilegeCode'],
302
+ include: [
303
+ {
304
+ model: SystemModel,
305
+ attributes: ['Name'],
306
+ },
307
+ ],
308
+ },
309
+ {
310
+ model: User,
311
+ as: 'CreatedByUser',
312
+ attributes: ['FullName'],
313
+ },
314
+ {
315
+ model: User,
316
+ as: 'UpdatedByUser',
317
+ attributes: ['FullName'],
318
+ },
319
+ ],
320
+ };
321
+ const systemPrivilege =
322
+ await this._GroupPrivilegeRepository.findAll(options);
323
+
324
+ const privilegeDetails = systemPrivilege.map((record) => {
325
+ return {
326
+ GroupPrivilegeId: record.GroupPrivilegeId,
327
+ SystemPrivilegeId: record.SystemPrivilegeId,
328
+ PrivilegeCode: record.Privilege.PrivilegeCode,
329
+ Status: record.Status,
330
+ CreatedBy: record.CreatedByUser.FullName,
331
+ CreatedAt: record.CreatedAt,
332
+ UpdatedBy: record.UpdatedByUser.FullName,
333
+ UpdatedAt: record.UpdatedAt,
334
+ };
335
+ });
336
+
337
+ data.systems = privilegeDetails;
338
+ }
339
+ }
340
+ userGroupPrivilege.push(data);
341
+ }
342
+ return userGroupPrivilege;
343
+ } catch (error) {
344
+ throw error;
345
+ }
346
+ }
347
+
348
+ public static async assignPrivileges(
349
+ loginUser: UserLogin, //The currently logged-in user initiating the request.
350
+ dbTransaction: any, //The active database transaction to ensure consistency during the query.
351
+ UserId: string, //The user ID for whom system access is being created.
352
+ SystemPrivilegeId: string, //The system code for which access is being granted.
353
+ Status: string, //The status of access ('Active' or 'Inactive').
354
+ ) {
355
+ try {
356
+ // Part 1: Privilege Check
357
+ // Call the LoginUser.checkPrivileges() method to validate if the loginUser has the privilege to create system privilege:
358
+ // SystemCode: retrieve from the application configuration.
359
+ // PrivilegeCode: set to "USER_PRIVILEGE_CREATE".
360
+ // If the user does not have the required privilege, throw an appropriate error.
361
+ const systemCode =
362
+ ApplicationConfig.getComponentConfigValue('system-code');
363
+ const privilegeCode = 'USER_PRIVILEGE_CREATE';
364
+ const isPrivileged = await loginUser.checkPrivileges(
365
+ systemCode,
366
+ privilegeCode,
367
+ );
368
+ if (!isPrivileged) {
369
+ throw new ClassError(
370
+ 'UserSystemPrivilege',
371
+ 'UserSystemPrivilegeErrMsg01',
372
+ 'You do not have permission to access this resource.',
373
+ );
374
+ }
375
+
376
+ // Part 2: Validation
377
+ // Use UserPrivilege._SystemPrivilegeRepo.findOne method to check if the privileges exist:
378
+ // Pass the following parameters:
379
+ // - SystemPrivilegeId
380
+ // - dbTransaction
381
+ // If the record is not found, throw an error indicating that privileges don't exist.
382
+ // Use the UserPrivilege.findAll() method to check if the privileges has been assigned to the user:
383
+ // Pass the following parameters:
384
+ // - loginUser
385
+ // - dbTransaction
386
+ // - whereOption: set to UserId = UserId and SystemPrivilegeId = SystemPrivilegeId.
387
+ // If a record is found, throw an error indicating that access for this user and system already exists.
388
+
389
+ const isExist = await UserPrivilege._SystemPrivilegeRepository.findAll({
390
+ where: { SystemPrivilegeId: SystemPrivilegeId },
391
+ transaction: dbTransaction,
392
+ });
393
+
394
+ if (isExist?.length < 1) {
395
+ throw new ClassError(
396
+ 'UserSystemPrivilege',
397
+ 'UserSystemPrivilegeErrMsg02',
398
+ "system privileges don't exist",
399
+ );
400
+ }
401
+
402
+ const isUserAlreadyAssign = await UserPrivilege._Repository.findAll({
403
+ where: {
404
+ [Op.and]: [
405
+ { UserId: UserId },
406
+ { SystemPrivilegeId: SystemPrivilegeId },
407
+ ],
408
+ },
409
+ transaction: dbTransaction,
410
+ });
411
+
412
+ if (isUserAlreadyAssign?.length > 0) {
413
+ throw new ClassError(
414
+ 'UserSystemPrivilege',
415
+ 'UserSystemPrivilegeErrMsg03',
416
+ 'User already have access to this privilege',
417
+ );
418
+ }
419
+
420
+ // Part 3: Insert User Privilege Record
421
+ // After successful validation, create a new instance of UserPrivilege with the following fields:
422
+ // - UserPrivilegeId: set to the result of createId
423
+ // - SystemPrivilegeId: set to payload.SystemPrivilegeId
424
+ // - Status: set to payload.Status
425
+ // - CreatedBy: set to LoginUser.UserId
426
+ // - CreatedAt: set to the current timestamps
427
+ // - UpdatedBy: set to LoginUser.UserId
428
+ // - UpdatedAt: set to the current timestamps
429
+ // Save the new UserPrivilege instance in the database within the dbTransaction.
430
+
431
+ const newUserPrivilege = new UserPrivilege();
432
+ newUserPrivilege.UserId = parseInt(UserId);
433
+ newUserPrivilege.SystemPrivilegeId = SystemPrivilegeId;
434
+ newUserPrivilege.Status = Status;
435
+ newUserPrivilege._CreatedById = loginUser.UserId;
436
+ newUserPrivilege._CreatedAt = new Date();
437
+ newUserPrivilege._UpdatedById = loginUser.UserId;
438
+ newUserPrivilege._UpdatedAt = new Date();
439
+
440
+ const payload = {
441
+ UserId: newUserPrivilege.UserId,
442
+ SystemPrivilegeId: newUserPrivilege.SystemPrivilegeId,
443
+ Status: newUserPrivilege.Status,
444
+ CreatedById: newUserPrivilege.CreatedById,
445
+ CreatedAt: newUserPrivilege.CreatedAt,
446
+ UpdatedById: newUserPrivilege.UpdatedById,
447
+ UpdatedAt: newUserPrivilege.UpdatedAt,
448
+ };
449
+
450
+ const userPrivilege = await UserPrivilege._Repository.create(payload, {
451
+ transaction: dbTransaction,
452
+ });
453
+
454
+ // Part 4: Record Activity History
455
+ // Initialize an empty object ({}) as EntityValueBefore.
456
+ // Set EntityValueAfter to the stringified version of the newly created UserPrivilege instance.
457
+ // Create a new activity log entry:
458
+ // - ActivityId: auto-generated by calling activity.createId().
459
+ // - Action: set to ActionEnum.Create.
460
+ // - Description: set to "Create User Privilege".
461
+ // - EntityType: set to UserPrivilege.
462
+ // - EntityId: set to the newly created UserPrivilege.UserPrivilegeId.
463
+ // - EntityValueBefore: set to {} (empty).
464
+ // - EntityValueAfter: set to the stringified version of the new record.
465
+ // Call the activity.create() method, passing:
466
+ // - dbTransaction
467
+ // - userId: set to loginUser.UserId.
468
+
469
+ const entityValueBefore = {};
470
+
471
+ //Instantiate new activity
472
+ const activity = new Activity();
473
+ activity.ActivityId = activity.createId();
474
+ activity.Action = ActionEnum.CREATE;
475
+ activity.Description = 'Create User Privilege';
476
+ activity.EntityType = 'UserPrivilege';
477
+ activity.EntityId = userPrivilege.UserPrivilegeId?.toString();
478
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
479
+ activity.EntityValueAfter = JSON.stringify(payload);
480
+
481
+ //Call Activity.create method
482
+ await activity.create(loginUser.ObjectId, dbTransaction);
483
+
484
+ // Part 5: Return Newly Created Record
485
+ // Return the newly created UserPrivilege instance with all relevant fields, including UserPrivilegeId, SystemPrivilegeId, Status, CreatedAt, and CreatedById.
486
+ newUserPrivilege.UserPrivilegeId = userPrivilege.UserPrivilegeId;
487
+ return newUserPrivilege;
488
+ } catch (error) {
489
+ throw error;
490
+ }
491
+ }
492
+
493
+ public async update(
494
+ loginUser: UserLogin, //The user object representing the currently logged-in user.
495
+ dbTransaction: any, //The database transaction instance for managing the transaction scope.
496
+ Status: string, //The new access status (Active/Inactive) for the user privilege
497
+ ) {
498
+ try {
499
+ // Part 1: Update User Privilege
500
+ // Call the UserPrivilege._Repo.update() method to perform the update operation, passing:
501
+ // - Status: The new status.
502
+ // - UpdatedById: loginUser.UserId (to indicate who updated the record).
503
+ // - UpdatedAt: Set to the current date and time.
504
+ // - dbTransaction: The database transaction instance.
505
+ const entityValueBefore = {
506
+ UserPrivilegeId: this.UserPrivilegeId,
507
+ UserId: this.UserId,
508
+ SystemPrivilegeId: this.SystemPrivilegeId,
509
+ Status: this.Status,
510
+ CreatedById: this.CreatedById,
511
+ CreatedAt: this.CreatedAt,
512
+ UpdatedById: this.UpdatedById,
513
+ UpdatedAt: this.UpdatedAt,
514
+ };
515
+
516
+ await UserPrivilege._Repository.update(
517
+ {
518
+ Status: Status,
519
+ UpdatedById: loginUser.UserId,
520
+ UpdatedAt: new Date(),
521
+ },
522
+ {
523
+ where: {
524
+ UserPrivilegeId: this.UserPrivilegeId,
525
+ },
526
+ transaction: dbTransaction,
527
+ },
528
+ );
529
+
530
+ const entityValueAfter = {
531
+ UserPrivilegeId: this.UserPrivilegeId,
532
+ UserId: this.UserId,
533
+ SystemPrivilegeId: this.SystemPrivilegeId,
534
+ Status: Status,
535
+ CreatedById: this.CreatedById,
536
+ CreatedAt: this.CreatedAt,
537
+ UpdatedById: loginUser.UserId,
538
+ UpdatedAt: new Date(),
539
+ };
540
+
541
+ // Part 2: Record Activity History
542
+ // Initialize a variable entityValueBefore to store the current state of the user privilege record before the update.
543
+ // Create an instance of the Activity class and set the following properties:
544
+ // - ActivityId: Call activity.createId().
545
+ // - Action: Set to ActionEnum.Update.
546
+ // - Description: Set to Update User Privilege.
547
+ // - EntityType: Set to UserPrivilege.
548
+ // - EntityId: Use the ID of the updated user privilege record.
549
+ // - EntityValueBefore: Stringify entityValueBefore to capture the state before the update.
550
+ // - EntityValueAfter: Stringify the updated user privilege record to capture the new state after the update.
551
+ // Call the activity create method with the following parameters:
552
+ // - dbTransaction
553
+ // - userId: loginUser.UserId
554
+ const activity = new Activity();
555
+ activity.ActivityId = activity.createId();
556
+ activity.Action = ActionEnum.UPDATE;
557
+ activity.Description = 'Update User Privilege';
558
+ activity.EntityType = 'UserPrivilege';
559
+ activity.EntityId = this.SystemPrivilegeId + '';
560
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
561
+ activity.EntityValueAfter = JSON.stringify(entityValueAfter);
562
+ await activity.create(loginUser.ObjectId, dbTransaction);
563
+
564
+ // Part 3: Return Updated Record
565
+ // Retrieve the updated user system access record from the database or return the updated instance as needed.
566
+ return entityValueAfter;
567
+ } catch (error) {
568
+ throw error;
569
+ }
570
+ }
571
+
572
+ public static async remove(
573
+ loginUser: UserLogin, //The currently logged-in user initiating the request.
574
+ dbTransaction: any, //The active database transaction to ensure consistency during the query.
575
+ UserPrivilegeId: number, //The unique identifier of the record to be deleted.
576
+ ) {
577
+ try {
578
+ // Part 1: Privilege Checking
579
+ // Call loginUser.checkPrivileges() method by passing:
580
+ // - SystemCode: Retrieve from app config.
581
+ // - PrivilegeCode: 'USER_PRIVILEGE_REMOVE'.
582
+ // If the user does not have the required privileges, throw an appropriate exception.
583
+ const systemCode =
584
+ ApplicationConfig.getComponentConfigValue('system-code');
585
+ const privilegeCode = 'USER_PRIVILEGE_REMOVE';
586
+ const isPrivileged = await loginUser.checkPrivileges(
587
+ systemCode,
588
+ privilegeCode,
589
+ );
590
+ if (!isPrivileged) {
591
+ throw new ClassError(
592
+ 'UserSystemPrivilege',
593
+ 'UserSystemPrivilegeErrMsg01',
594
+ 'You do not have permission to access this resource.',
595
+ );
596
+ }
597
+
598
+ // Part 2: Retrieve Record
599
+ // Use the UserPrivilege._Repo.findById(UserPrivilegeId) method to retrieve the record.
600
+ // If the record does not exist, throw an exception indicating the record was not found.
601
+
602
+ const userPrivilege = await UserPrivilege._Repository.findOne({
603
+ where: {
604
+ UserPrivilegeId: UserPrivilegeId,
605
+ },
606
+ transaction: dbTransaction,
607
+ });
608
+
609
+ if (!userPrivilege) {
610
+ throw new ClassError(
611
+ 'UserSystemPrivilege',
612
+ 'UserSystemPrivilegeErrMsg01',
613
+ 'User Privilege not Found',
614
+ );
615
+ }
616
+
617
+ // Part 3: Delete Record
618
+ // Call the UserPrivilege._Repo.delete() method, passing:
619
+ // - UserPrivilegeId
620
+ // - dbTransaction to permanently delete the record from the database.
621
+ await UserPrivilege._Repository.delete(UserPrivilegeId, dbTransaction);
622
+
623
+ const entityValueBefore = {
624
+ UserId: userPrivilege.UserId,
625
+ SystemPrivilegeId: userPrivilege.SystemPrivilegeId,
626
+ Status: userPrivilege.Status,
627
+ CreatedById: userPrivilege.CreatedById,
628
+ CreatedAt: userPrivilege.CreatedAt,
629
+ UpdatedById: userPrivilege.UpdatedById,
630
+ UpdatedAt: userPrivilege.UpdatedAt,
631
+ };
632
+
633
+ // Part 4: Record Activity History
634
+ // Instantiate a new activity from the Activity class, and set:
635
+ // - ActivityId: activity.createId()
636
+ // - Action: ActionEnum.Delete
637
+ // - Description: Delete User Privilege
638
+ // - EntityType: UserPrivilege
639
+ // - EntityId: UserPrivilegeId
640
+ // - EntityValueBefore: Stringified representation of the record before deletion.
641
+ // - EntityValueAfter: null.
642
+ // Call the activity.create() method by passing:
643
+ // - dbTransaction
644
+ // - userId: loginUser.UserId.
645
+
646
+ //Instantiate new activity
647
+ const activity = new Activity();
648
+ activity.ActivityId = activity.createId();
649
+ activity.Action = ActionEnum.DELETE;
650
+ activity.Description = 'Delete User Privilege';
651
+ activity.EntityType = 'UserPrivilege';
652
+ activity.EntityId = UserPrivilegeId?.toString();
653
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
654
+ activity.EntityValueAfter = JSON.stringify({});
655
+
656
+ //Call Activity.create method
657
+ await activity.create(loginUser.ObjectId, dbTransaction);
658
+ } catch (error) {
659
+ throw error;
660
+ }
661
+ }
74
662
  }
@@ -8,4 +8,18 @@ export class UserSystemAccessRepository
8
8
  constructor() {
9
9
  super(UserSystemAccessModel);
10
10
  }
11
+
12
+ async delete(UserSystemAccessId: number, dbTransaction?: any) {
13
+ try {
14
+ const options = {
15
+ where: {
16
+ UserSystemAccessId: UserSystemAccessId,
17
+ },
18
+ transaction: dbTransaction,
19
+ };
20
+ await UserSystemAccessModel.destroy(options);
21
+ } catch (error) {
22
+ throw new Error(`An Error occured when delete : ${error.message}`);
23
+ }
24
+ }
11
25
  }