@tomei/sso 0.46.9 → 0.46.10

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomei/sso",
3
- "version": "0.46.9",
3
+ "version": "0.46.10",
4
4
  "description": "Tomei SSO Package",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -8,4 +8,18 @@ export class UserPrivilegeRepository
8
8
  constructor() {
9
9
  super(UserPrivilegeModel);
10
10
  }
11
+
12
+ async delete(UserPrivilegeId: number, dbTransaction?: any) {
13
+ try {
14
+ const options = {
15
+ where: {
16
+ UserPrivilegeId: UserPrivilegeId,
17
+ },
18
+ transaction: dbTransaction,
19
+ };
20
+ await UserPrivilegeModel.destroy(options);
21
+ } catch (error) {
22
+ throw new Error(`An Error occured when delete : ${error.message}`);
23
+ }
24
+ }
11
25
  }
@@ -9,6 +9,10 @@ import { UserGroupRepository } from '../user-group/user-group.repository';
9
9
  import GroupModel from '../../models/group.entity';
10
10
  import User from '../../models/user.entity';
11
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';
12
16
 
13
17
  export class UserPrivilege extends ObjectBase {
14
18
  TableName = 'sso_UserPrivilege';
@@ -43,6 +47,7 @@ export class UserPrivilege extends ObjectBase {
43
47
  private static _Repository = new UserPrivilegeRepository();
44
48
  private static _UserGroupRepository = new UserGroupRepository();
45
49
  private static _GroupPrivilegeRepository = new GroupPrivilegeRepository();
50
+ private static _SystemPrivilegeRepository = new SystemPrivilegeRepository();
46
51
 
47
52
  private constructor(userPrivilegeAttr?: IUserPrivilegeAttr) {
48
53
  super();
@@ -336,4 +341,319 @@ export class UserPrivilege extends ObjectBase {
336
341
  throw error;
337
342
  }
338
343
  }
344
+
345
+ public static async assignPrivileges(
346
+ loginUser: UserLogin, //The currently logged-in user initiating the request.
347
+ dbTransaction: any, //The active database transaction to ensure consistency during the query.
348
+ UserId: string, //The user ID for whom system access is being created.
349
+ SystemPrivilegeId: string, //The system code for which access is being granted.
350
+ Status: string, //The status of access ('Active' or 'Inactive').
351
+ ) {
352
+ try {
353
+ // Part 1: Privilege Check
354
+ // Call the LoginUser.checkPrivileges() method to validate if the loginUser has the privilege to create system privilege:
355
+ // SystemCode: retrieve from the application configuration.
356
+ // PrivilegeCode: set to "USER_PRIVILEGE_CREATE".
357
+ // If the user does not have the required privilege, throw an appropriate error.
358
+ const systemCode =
359
+ ApplicationConfig.getComponentConfigValue('system-code');
360
+ const privilegeCode = 'USER_PRIVILEGE_CREATE';
361
+ const isPrivileged = await loginUser.checkPrivileges(
362
+ systemCode,
363
+ privilegeCode,
364
+ );
365
+ if (!isPrivileged) {
366
+ throw new ClassError(
367
+ 'UserSystemPrivilege',
368
+ 'UserSystemPrivilegeErrMsg01',
369
+ 'You do not have permission to access this resource.',
370
+ );
371
+ }
372
+
373
+ // Part 2: Validation
374
+ // Use UserPrivilege._SystemPrivilegeRepo.findOne method to check if the privileges exist:
375
+ // Pass the following parameters:
376
+ // - SystemPrivilegeId
377
+ // - dbTransaction
378
+ // If the record is not found, throw an error indicating that privileges don't exist.
379
+ // Use the UserPrivilege.findAll() method to check if the privileges has been assigned to the user:
380
+ // Pass the following parameters:
381
+ // - loginUser
382
+ // - dbTransaction
383
+ // - whereOption: set to UserId = UserId and SystemPrivilegeId = SystemPrivilegeId.
384
+ // If a record is found, throw an error indicating that access for this user and system already exists.
385
+
386
+ const isExist = await UserPrivilege._SystemPrivilegeRepository.findAll({
387
+ where: { SystemPrivilegeId: SystemPrivilegeId },
388
+ transaction: dbTransaction,
389
+ });
390
+
391
+ if (isExist?.length < 1) {
392
+ throw new ClassError(
393
+ 'UserSystemPrivilege',
394
+ 'UserSystemPrivilegeErrMsg02',
395
+ "system privileges don't exist",
396
+ );
397
+ }
398
+
399
+ const isUserAlreadyAssign = await UserPrivilege._Repository.findAll({
400
+ where: {
401
+ [Op.and]: [
402
+ { UserId: UserId },
403
+ { SystemPrivilegeId: SystemPrivilegeId },
404
+ ],
405
+ },
406
+ transaction: dbTransaction,
407
+ });
408
+
409
+ if (isUserAlreadyAssign?.length > 0) {
410
+ throw new ClassError(
411
+ 'UserSystemPrivilege',
412
+ 'UserSystemPrivilegeErrMsg03',
413
+ 'User already have access to this privilege',
414
+ );
415
+ }
416
+
417
+ // Part 3: Insert User Privilege Record
418
+ // After successful validation, create a new instance of UserPrivilege with the following fields:
419
+ // - UserPrivilegeId: set to the result of createId
420
+ // - SystemPrivilegeId: set to payload.SystemPrivilegeId
421
+ // - Status: set to payload.Status
422
+ // - CreatedBy: set to LoginUser.UserId
423
+ // - CreatedAt: set to the current timestamps
424
+ // - UpdatedBy: set to LoginUser.UserId
425
+ // - UpdatedAt: set to the current timestamps
426
+ // Save the new UserPrivilege instance in the database within the dbTransaction.
427
+
428
+ const newUserPrivilege = new UserPrivilege();
429
+ newUserPrivilege.UserId = parseInt(UserId);
430
+ newUserPrivilege.SystemPrivilegeId = SystemPrivilegeId;
431
+ newUserPrivilege.Status = Status;
432
+ newUserPrivilege._CreatedById = loginUser.UserId;
433
+ newUserPrivilege._CreatedAt = new Date();
434
+ newUserPrivilege._UpdatedById = loginUser.UserId;
435
+ newUserPrivilege._UpdatedAt = new Date();
436
+
437
+ const payload = {
438
+ UserId: newUserPrivilege.UserId,
439
+ SystemPrivilegeId: newUserPrivilege.SystemPrivilegeId,
440
+ Status: newUserPrivilege.Status,
441
+ CreatedById: newUserPrivilege.CreatedById,
442
+ CreatedAt: newUserPrivilege.CreatedAt,
443
+ UpdatedById: newUserPrivilege.UpdatedById,
444
+ UpdatedAt: newUserPrivilege.UpdatedAt,
445
+ };
446
+
447
+ const userPrivilege = await UserPrivilege._Repository.create(payload, {
448
+ transaction: dbTransaction,
449
+ });
450
+
451
+ // Part 4: Record Activity History
452
+ // Initialize an empty object ({}) as EntityValueBefore.
453
+ // Set EntityValueAfter to the stringified version of the newly created UserPrivilege instance.
454
+ // Create a new activity log entry:
455
+ // - ActivityId: auto-generated by calling activity.createId().
456
+ // - Action: set to ActionEnum.Create.
457
+ // - Description: set to "Create User Privilege".
458
+ // - EntityType: set to UserPrivilege.
459
+ // - EntityId: set to the newly created UserPrivilege.UserPrivilegeId.
460
+ // - EntityValueBefore: set to {} (empty).
461
+ // - EntityValueAfter: set to the stringified version of the new record.
462
+ // Call the activity.create() method, passing:
463
+ // - dbTransaction
464
+ // - userId: set to loginUser.UserId.
465
+
466
+ const entityValueBefore = {};
467
+
468
+ //Instantiate new activity
469
+ const activity = new Activity();
470
+ activity.ActivityId = activity.createId();
471
+ activity.Action = ActionEnum.CREATE;
472
+ activity.Description = 'Create User Privilege';
473
+ activity.EntityType = 'UserPrivilege';
474
+ activity.EntityId = userPrivilege.UserPrivilegeId?.toString();
475
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
476
+ activity.EntityValueAfter = JSON.stringify(payload);
477
+
478
+ //Call Activity.create method
479
+ await activity.create(loginUser.ObjectId, dbTransaction);
480
+
481
+ // Part 5: Return Newly Created Record
482
+ // Return the newly created UserPrivilege instance with all relevant fields, including UserPrivilegeId, SystemPrivilegeId, Status, CreatedAt, and CreatedById.
483
+ newUserPrivilege.UserPrivilegeId = userPrivilege.UserPrivilegeId;
484
+ return newUserPrivilege;
485
+ } catch (error) {
486
+ throw error;
487
+ }
488
+ }
489
+
490
+ public async update(
491
+ loginUser: UserLogin, //The user object representing the currently logged-in user.
492
+ dbTransaction: any, //The database transaction instance for managing the transaction scope.
493
+ Status: string, //The new access status (Active/Inactive) for the user privilege
494
+ ) {
495
+ try {
496
+ // Part 1: Update User Privilege
497
+ // Call the UserPrivilege._Repo.update() method to perform the update operation, passing:
498
+ // - Status: The new status.
499
+ // - UpdatedById: loginUser.UserId (to indicate who updated the record).
500
+ // - UpdatedAt: Set to the current date and time.
501
+ // - dbTransaction: The database transaction instance.
502
+ const entityValueBefore = {
503
+ UserPrivilegeId: this.UserPrivilegeId,
504
+ UserId: this.UserId,
505
+ SystemPrivilegeId: this.SystemPrivilegeId,
506
+ Status: this.Status,
507
+ CreatedById: this.CreatedById,
508
+ CreatedAt: this.CreatedAt,
509
+ UpdatedById: this.UpdatedById,
510
+ UpdatedAt: this.UpdatedAt,
511
+ };
512
+
513
+ await UserPrivilege._Repository.update(
514
+ {
515
+ Status: Status,
516
+ UpdatedById: loginUser.UserId,
517
+ UpdatedAt: new Date(),
518
+ },
519
+ {
520
+ where: {
521
+ UserPrivilegeId: this.UserPrivilegeId,
522
+ },
523
+ transaction: dbTransaction,
524
+ },
525
+ );
526
+
527
+ const entityValueAfter = {
528
+ UserPrivilegeId: this.UserPrivilegeId,
529
+ UserId: this.UserId,
530
+ SystemPrivilegeId: this.SystemPrivilegeId,
531
+ Status: Status,
532
+ CreatedById: this.CreatedById,
533
+ CreatedAt: this.CreatedAt,
534
+ UpdatedById: loginUser.UserId,
535
+ UpdatedAt: new Date(),
536
+ };
537
+
538
+ // Part 2: Record Activity History
539
+ // Initialize a variable entityValueBefore to store the current state of the user privilege record before the update.
540
+ // Create an instance of the Activity class and set the following properties:
541
+ // - ActivityId: Call activity.createId().
542
+ // - Action: Set to ActionEnum.Update.
543
+ // - Description: Set to Update User Privilege.
544
+ // - EntityType: Set to UserPrivilege.
545
+ // - EntityId: Use the ID of the updated user privilege record.
546
+ // - EntityValueBefore: Stringify entityValueBefore to capture the state before the update.
547
+ // - EntityValueAfter: Stringify the updated user privilege record to capture the new state after the update.
548
+ // Call the activity create method with the following parameters:
549
+ // - dbTransaction
550
+ // - userId: loginUser.UserId
551
+ const activity = new Activity();
552
+ activity.ActivityId = activity.createId();
553
+ activity.Action = ActionEnum.UPDATE;
554
+ activity.Description = 'Update User Privilege';
555
+ activity.EntityType = 'UserPrivilege';
556
+ activity.EntityId = this.SystemPrivilegeId + '';
557
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
558
+ activity.EntityValueAfter = JSON.stringify(entityValueAfter);
559
+ await activity.create(loginUser.ObjectId, dbTransaction);
560
+
561
+ // Part 3: Return Updated Record
562
+ // Retrieve the updated user system access record from the database or return the updated instance as needed.
563
+ return entityValueAfter;
564
+ } catch (error) {
565
+ throw error;
566
+ }
567
+ }
568
+
569
+ public static async remove(
570
+ loginUser: UserLogin, //The currently logged-in user initiating the request.
571
+ dbTransaction: any, //The active database transaction to ensure consistency during the query.
572
+ UserPrivilegeId: number, //The unique identifier of the record to be deleted.
573
+ ) {
574
+ try {
575
+ // Part 1: Privilege Checking
576
+ // Call loginUser.checkPrivileges() method by passing:
577
+ // - SystemCode: Retrieve from app config.
578
+ // - PrivilegeCode: 'USER_PRIVILEGE_REMOVE'.
579
+ // If the user does not have the required privileges, throw an appropriate exception.
580
+ const systemCode =
581
+ ApplicationConfig.getComponentConfigValue('system-code');
582
+ const privilegeCode = 'USER_PRIVILEGE_REMOVE';
583
+ const isPrivileged = await loginUser.checkPrivileges(
584
+ systemCode,
585
+ privilegeCode,
586
+ );
587
+ if (!isPrivileged) {
588
+ throw new ClassError(
589
+ 'UserSystemPrivilege',
590
+ 'UserSystemPrivilegeErrMsg01',
591
+ 'You do not have permission to access this resource.',
592
+ );
593
+ }
594
+
595
+ // Part 2: Retrieve Record
596
+ // Use the UserPrivilege._Repo.findById(UserPrivilegeId) method to retrieve the record.
597
+ // If the record does not exist, throw an exception indicating the record was not found.
598
+
599
+ const userPrivilege = await UserPrivilege._Repository.findOne({
600
+ where: {
601
+ UserPrivilegeId: UserPrivilegeId,
602
+ },
603
+ transaction: dbTransaction,
604
+ });
605
+
606
+ if (!userPrivilege) {
607
+ throw new ClassError(
608
+ 'UserSystemPrivilege',
609
+ 'UserSystemPrivilegeErrMsg01',
610
+ 'User Privilege not Found',
611
+ );
612
+ }
613
+
614
+ // Part 3: Delete Record
615
+ // Call the UserPrivilege._Repo.delete() method, passing:
616
+ // - UserPrivilegeId
617
+ // - dbTransaction to permanently delete the record from the database.
618
+ await UserPrivilege._Repository.delete(UserPrivilegeId, dbTransaction);
619
+
620
+ const entityValueBefore = {
621
+ UserId: userPrivilege.UserId,
622
+ SystemPrivilegeId: userPrivilege.SystemPrivilegeId,
623
+ Status: userPrivilege.Status,
624
+ CreatedById: userPrivilege.CreatedById,
625
+ CreatedAt: userPrivilege.CreatedAt,
626
+ UpdatedById: userPrivilege.UpdatedById,
627
+ UpdatedAt: userPrivilege.UpdatedAt,
628
+ };
629
+
630
+ // Part 4: Record Activity History
631
+ // Instantiate a new activity from the Activity class, and set:
632
+ // - ActivityId: activity.createId()
633
+ // - Action: ActionEnum.Delete
634
+ // - Description: Delete User Privilege
635
+ // - EntityType: UserPrivilege
636
+ // - EntityId: UserPrivilegeId
637
+ // - EntityValueBefore: Stringified representation of the record before deletion.
638
+ // - EntityValueAfter: null.
639
+ // Call the activity.create() method by passing:
640
+ // - dbTransaction
641
+ // - userId: loginUser.UserId.
642
+
643
+ //Instantiate new activity
644
+ const activity = new Activity();
645
+ activity.ActivityId = activity.createId();
646
+ activity.Action = ActionEnum.DELETE;
647
+ activity.Description = 'Delete User Privilege';
648
+ activity.EntityType = 'UserPrivilege';
649
+ activity.EntityId = UserPrivilegeId?.toString();
650
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
651
+ activity.EntityValueAfter = JSON.stringify({});
652
+
653
+ //Call Activity.create method
654
+ await activity.create(loginUser.ObjectId, dbTransaction);
655
+ } catch (error) {
656
+ throw error;
657
+ }
658
+ }
339
659
  }