@tomei/sso 0.61.0 → 0.61.1

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 (134) hide show
  1. package/dist/__tests__/unit/components/group-privilege/group-privilege.test.d.ts +1 -0
  2. package/dist/__tests__/unit/components/group-privilege/group-privilege.test.js +71 -0
  3. package/dist/__tests__/unit/components/group-privilege/group-privilege.test.js.map +1 -0
  4. package/dist/__tests__/unit/components/login-user/login-user.spec.d.ts +0 -0
  5. package/dist/__tests__/unit/components/login-user/login-user.spec.js +6 -0
  6. package/dist/__tests__/unit/components/login-user/login-user.spec.js.map +1 -0
  7. package/dist/src/components/login-history/login-history.d.ts +23 -0
  8. package/dist/src/components/login-history/login-history.js +88 -0
  9. package/dist/src/components/login-history/login-history.js.map +1 -0
  10. package/dist/src/components/login-user/user.js +3 -2
  11. package/dist/src/components/login-user/user.js.map +1 -1
  12. package/dist/src/interfaces/login-history-search-attr.interface.d.ts +8 -0
  13. package/dist/src/interfaces/login-history-search-attr.interface.js +3 -0
  14. package/dist/src/interfaces/login-history-search-attr.interface.js.map +1 -0
  15. package/dist/src/interfaces/login-history.interface.d.ts +11 -0
  16. package/dist/src/interfaces/login-history.interface.js +3 -0
  17. package/dist/src/interfaces/login-history.interface.js.map +1 -0
  18. package/dist/tsconfig.tsbuildinfo +1 -1
  19. package/package.json +1 -1
  20. package/src/components/api-key/api-key.repository.ts +15 -15
  21. package/src/components/api-key/api-key.ts +448 -448
  22. package/src/components/api-key/index.ts +4 -4
  23. package/src/components/building/building.repository.ts +27 -27
  24. package/src/components/building/index.ts +2 -2
  25. package/src/components/group/group.repository.ts +26 -26
  26. package/src/components/group/group.ts +2284 -2284
  27. package/src/components/group/index.ts +3 -3
  28. package/src/components/group-object-privilege/group-object-privilege.repository.ts +25 -25
  29. package/src/components/group-object-privilege/group-object-privilege.ts +278 -278
  30. package/src/components/group-object-privilege/index.ts +2 -2
  31. package/src/components/group-privilege/group-privilege.repository.ts +29 -29
  32. package/src/components/group-privilege/group-privilege.ts +84 -84
  33. package/src/components/group-privilege/index.ts +2 -2
  34. package/src/components/group-reporting-user/group-reporting-user.repository.ts +23 -23
  35. package/src/components/group-reporting-user/group-reporting-user.ts +506 -506
  36. package/src/components/group-reporting-user/index.ts +3 -3
  37. package/src/components/group-system-access/group-system-access.repository.ts +43 -43
  38. package/src/components/group-system-access/group-system-access.ts +90 -90
  39. package/src/components/group-system-access/index.ts +2 -2
  40. package/src/components/index.ts +20 -20
  41. package/src/components/login-user/index.ts +5 -5
  42. package/src/components/login-user/interfaces/check-user-info-duplicated.interface.ts +7 -7
  43. package/src/components/login-user/interfaces/index.ts +1 -1
  44. package/src/components/login-user/interfaces/system-access.interface.ts +13 -13
  45. package/src/components/login-user/interfaces/user-info.interface.ts +34 -34
  46. package/src/components/login-user/login-user.ts +362 -362
  47. package/src/components/login-user/user.repository.ts +11 -11
  48. package/src/components/login-user/user.ts +3 -2
  49. package/src/components/password-hash/index.ts +2 -2
  50. package/src/components/password-hash/interfaces/index.ts +1 -1
  51. package/src/components/password-hash/interfaces/password-hash-service.interface.ts +4 -4
  52. package/src/components/password-hash/password-hash.service.ts +14 -14
  53. package/src/components/staff/index.ts +2 -2
  54. package/src/components/staff/staff.repository.ts +27 -27
  55. package/src/components/system/index.ts +3 -3
  56. package/src/components/system/system.repository.ts +11 -11
  57. package/src/components/system/system.ts +456 -456
  58. package/src/components/system-privilege/index.ts +4 -4
  59. package/src/components/system-privilege/system-privilege.repository.ts +18 -18
  60. package/src/components/system-privilege/system-privilege.ts +541 -541
  61. package/src/components/user-group/index.ts +2 -2
  62. package/src/components/user-group/user-group.repository.ts +19 -19
  63. package/src/components/user-group/user-group.ts +764 -764
  64. package/src/components/user-object-privilege/index.ts +2 -2
  65. package/src/components/user-object-privilege/user-object-privilege.repository.ts +11 -11
  66. package/src/components/user-object-privilege/user-object-privilege.ts +79 -79
  67. package/src/components/user-password-history/index.ts +2 -2
  68. package/src/components/user-password-history/user-password-history.repository.ts +39 -39
  69. package/src/components/user-password-history/user-password-history.ts +187 -187
  70. package/src/components/user-privilege/index.ts +2 -2
  71. package/src/components/user-privilege/user-privilege.repository.ts +25 -25
  72. package/src/components/user-privilege/user-privilege.ts +662 -662
  73. package/src/components/user-reporting-hierarchy/index.ts +2 -2
  74. package/src/components/user-reporting-hierarchy/user-reporting-hierarchy.repository.ts +30 -30
  75. package/src/components/user-reporting-hierarchy/user-reporting-hierarchy.ts +505 -505
  76. package/src/components/user-system-access/index.ts +2 -2
  77. package/src/components/user-system-access/user-system-access.repository.ts +41 -41
  78. package/src/database.ts +15 -15
  79. package/src/enum/api-key.enum.ts +5 -5
  80. package/src/enum/building-type.enum.ts +6 -6
  81. package/src/enum/group-type.enum.ts +8 -8
  82. package/src/enum/index.ts +6 -6
  83. package/src/enum/login-status.enum.ts +4 -4
  84. package/src/enum/object-status.enum.ts +4 -4
  85. package/src/enum/user-status.enum.ts +7 -7
  86. package/src/enum/yn.enum.ts +4 -4
  87. package/src/index.ts +8 -8
  88. package/src/interfaces/api-key-attr.interface.ts +16 -16
  89. package/src/interfaces/group-object-privilege.interface.ts +14 -14
  90. package/src/interfaces/group-privilege.interface.ts +10 -10
  91. package/src/interfaces/group-reporting-user.interface.ts +11 -11
  92. package/src/interfaces/group-search-attr.interface.ts +9 -9
  93. package/src/interfaces/group-system-access.interface.ts +10 -10
  94. package/src/interfaces/group.interface.ts +17 -17
  95. package/src/interfaces/index.ts +13 -13
  96. package/src/interfaces/system-login.interface.ts +6 -6
  97. package/src/interfaces/system-privilege-search.interface.ts +5 -5
  98. package/src/interfaces/system-privilege.interface.ts +11 -11
  99. package/src/interfaces/system-search-attr.interface.ts +5 -5
  100. package/src/interfaces/system.interface.ts +15 -15
  101. package/src/interfaces/user-group.interface.ts +12 -12
  102. package/src/interfaces/user-object-privilege.interface.ts +14 -14
  103. package/src/interfaces/user-password-history.interface.ts +6 -6
  104. package/src/interfaces/user-privilege.interface.ts +10 -10
  105. package/src/interfaces/user-reporting-hierarchy.interface.ts +11 -11
  106. package/src/interfaces/user-session.interface.ts +5 -5
  107. package/src/interfaces/user-system-access.interface.ts +10 -10
  108. package/src/models/api-key-entity.ts +101 -101
  109. package/src/models/building.entity.ts +103 -103
  110. package/src/models/group-object-privilege.entity.ts +91 -91
  111. package/src/models/group-privilege.entity.ts +78 -78
  112. package/src/models/group-reporting-user.entity.ts +95 -95
  113. package/src/models/group-system-access.entity.ts +81 -81
  114. package/src/models/group.entity.ts +127 -127
  115. package/src/models/staff.entity.ts +91 -91
  116. package/src/models/system-privilege.entity.ts +90 -90
  117. package/src/models/system.entity.ts +113 -113
  118. package/src/models/user-group.entity.ts +91 -91
  119. package/src/models/user-object-privilege.entity.ts +90 -90
  120. package/src/models/user-password-history.ts +51 -51
  121. package/src/models/user-privilege.entity.ts +78 -78
  122. package/src/models/user-reporting-hierarchy.entity.ts +102 -102
  123. package/src/models/user-system-access.entity.ts +87 -87
  124. package/src/models/user.entity.ts +193 -193
  125. package/src/redis-client/__mocks__/jest-initial-setup.ts +2 -2
  126. package/src/redis-client/__mocks__/redis-mock.ts +28 -28
  127. package/src/redis-client/index.ts +1 -1
  128. package/src/redis-client/redis.service.ts +75 -75
  129. package/src/session/index.ts +2 -2
  130. package/src/session/interfaces/index.ts +1 -1
  131. package/src/session/interfaces/session-service.interface.ts +26 -26
  132. package/src/session/session.service.ts +96 -96
  133. package/src/types/auth-context.ts +10 -10
  134. package/src/types/index.ts +1 -1
@@ -1,662 +1,662 @@
1
- import { ClassError, ObjectBase } from '@tomei/general';
2
- import { IUserPrivilegeAttr } from '../../interfaces/user-privilege.interface';
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';
17
-
18
- export class UserPrivilege extends ObjectBase {
19
- TableName = 'sso_UserPrivilege';
20
- ObjectType = 'UserPrivilege';
21
- ObjectName: string;
22
- ObjectId: string;
23
- UserPrivilegeId: number;
24
- UserId: number;
25
- SystemPrivilegeId: string;
26
- Status: string;
27
- private _CreatedById: number;
28
- private _UpdatedById: number;
29
- private _CreatedAt: Date;
30
- private _UpdatedAt: Date;
31
-
32
- get CreatedById(): number {
33
- return this._CreatedById;
34
- }
35
-
36
- get UpdatedById(): number {
37
- return this._UpdatedById;
38
- }
39
-
40
- get CreatedAt(): Date {
41
- return this._CreatedAt;
42
- }
43
-
44
- get UpdatedAt(): Date {
45
- return this._UpdatedAt;
46
- }
47
-
48
- private static _Repository = new UserPrivilegeRepository();
49
- private static _UserGroupRepository = new UserGroupRepository();
50
- private static _GroupPrivilegeRepository = new GroupPrivilegeRepository();
51
- private static _SystemPrivilegeRepository = new SystemPrivilegeRepository();
52
-
53
- private constructor(userPrivilegeAttr?: IUserPrivilegeAttr) {
54
- super();
55
- if (userPrivilegeAttr) {
56
- this.UserPrivilegeId = userPrivilegeAttr.UserPrivilegeId;
57
- this.UserId = userPrivilegeAttr.UserId;
58
- this.SystemPrivilegeId = userPrivilegeAttr.SystemPrivilegeId;
59
- this.Status = userPrivilegeAttr.Status;
60
- this._CreatedById = userPrivilegeAttr.CreatedById;
61
- this._UpdatedById = userPrivilegeAttr.UpdatedById;
62
- this._CreatedAt = userPrivilegeAttr.CreatedAt;
63
- this._UpdatedAt = userPrivilegeAttr.UpdatedAt;
64
- }
65
- }
66
-
67
- public static async init(dbTransaction?: any, UserPrivilegeId?: number) {
68
- try {
69
- let userPrivilege = new UserPrivilege();
70
- if (UserPrivilegeId) {
71
- const userPrivilegeAttr = await this._Repository.findOne({
72
- where: { UserPrivilegeId },
73
- transaction: dbTransaction,
74
- });
75
- if (userPrivilegeAttr) {
76
- userPrivilege = new UserPrivilege(userPrivilegeAttr);
77
- } else {
78
- throw new ClassError(
79
- 'UserPrivilege',
80
- 'UserPrivilegeErrMsg00',
81
- 'UserPrivilege not found',
82
- );
83
- }
84
- }
85
- return userPrivilege;
86
- } catch (error) {
87
- throw error;
88
- }
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
- distinct: true,
144
- where: {
145
- UserId: whereOption.UserId,
146
- },
147
- offset: (pagination.page - 1) * pagination.limit,
148
- limit: pagination.limit,
149
- transaction: dbTransaction,
150
- include: [
151
- {
152
- model: SystemPrivilegeModel,
153
- attributes: ['PrivilegeCode'],
154
- include: [
155
- {
156
- model: SystemModel,
157
- attributes: ['Name'],
158
- },
159
- ],
160
- },
161
- {
162
- model: User,
163
- as: 'CreatedByUser',
164
- attributes: ['FullName'],
165
- },
166
- {
167
- model: User,
168
- as: 'UpdatedByUser',
169
- attributes: ['FullName'],
170
- },
171
- ],
172
- };
173
- const { count, rows } =
174
- await this._Repository.findAllWithPagination(options);
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
- }
662
- }
1
+ import { ClassError, ObjectBase } from '@tomei/general';
2
+ import { IUserPrivilegeAttr } from '../../interfaces/user-privilege.interface';
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';
17
+
18
+ export class UserPrivilege extends ObjectBase {
19
+ TableName = 'sso_UserPrivilege';
20
+ ObjectType = 'UserPrivilege';
21
+ ObjectName: string;
22
+ ObjectId: string;
23
+ UserPrivilegeId: number;
24
+ UserId: number;
25
+ SystemPrivilegeId: string;
26
+ Status: string;
27
+ private _CreatedById: number;
28
+ private _UpdatedById: number;
29
+ private _CreatedAt: Date;
30
+ private _UpdatedAt: Date;
31
+
32
+ get CreatedById(): number {
33
+ return this._CreatedById;
34
+ }
35
+
36
+ get UpdatedById(): number {
37
+ return this._UpdatedById;
38
+ }
39
+
40
+ get CreatedAt(): Date {
41
+ return this._CreatedAt;
42
+ }
43
+
44
+ get UpdatedAt(): Date {
45
+ return this._UpdatedAt;
46
+ }
47
+
48
+ private static _Repository = new UserPrivilegeRepository();
49
+ private static _UserGroupRepository = new UserGroupRepository();
50
+ private static _GroupPrivilegeRepository = new GroupPrivilegeRepository();
51
+ private static _SystemPrivilegeRepository = new SystemPrivilegeRepository();
52
+
53
+ private constructor(userPrivilegeAttr?: IUserPrivilegeAttr) {
54
+ super();
55
+ if (userPrivilegeAttr) {
56
+ this.UserPrivilegeId = userPrivilegeAttr.UserPrivilegeId;
57
+ this.UserId = userPrivilegeAttr.UserId;
58
+ this.SystemPrivilegeId = userPrivilegeAttr.SystemPrivilegeId;
59
+ this.Status = userPrivilegeAttr.Status;
60
+ this._CreatedById = userPrivilegeAttr.CreatedById;
61
+ this._UpdatedById = userPrivilegeAttr.UpdatedById;
62
+ this._CreatedAt = userPrivilegeAttr.CreatedAt;
63
+ this._UpdatedAt = userPrivilegeAttr.UpdatedAt;
64
+ }
65
+ }
66
+
67
+ public static async init(dbTransaction?: any, UserPrivilegeId?: number) {
68
+ try {
69
+ let userPrivilege = new UserPrivilege();
70
+ if (UserPrivilegeId) {
71
+ const userPrivilegeAttr = await this._Repository.findOne({
72
+ where: { UserPrivilegeId },
73
+ transaction: dbTransaction,
74
+ });
75
+ if (userPrivilegeAttr) {
76
+ userPrivilege = new UserPrivilege(userPrivilegeAttr);
77
+ } else {
78
+ throw new ClassError(
79
+ 'UserPrivilege',
80
+ 'UserPrivilegeErrMsg00',
81
+ 'UserPrivilege not found',
82
+ );
83
+ }
84
+ }
85
+ return userPrivilege;
86
+ } catch (error) {
87
+ throw error;
88
+ }
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
+ distinct: true,
144
+ where: {
145
+ UserId: whereOption.UserId,
146
+ },
147
+ offset: (pagination.page - 1) * pagination.limit,
148
+ limit: pagination.limit,
149
+ transaction: dbTransaction,
150
+ include: [
151
+ {
152
+ model: SystemPrivilegeModel,
153
+ attributes: ['PrivilegeCode'],
154
+ include: [
155
+ {
156
+ model: SystemModel,
157
+ attributes: ['Name'],
158
+ },
159
+ ],
160
+ },
161
+ {
162
+ model: User,
163
+ as: 'CreatedByUser',
164
+ attributes: ['FullName'],
165
+ },
166
+ {
167
+ model: User,
168
+ as: 'UpdatedByUser',
169
+ attributes: ['FullName'],
170
+ },
171
+ ],
172
+ };
173
+ const { count, rows } =
174
+ await this._Repository.findAllWithPagination(options);
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
+ }
662
+ }