@tomei/sso 0.61.0 → 0.62.0

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 (257) hide show
  1. package/.commitlintrc.json +22 -22
  2. package/.gitlab-ci.yml +16 -16
  3. package/.husky/commit-msg +15 -15
  4. package/.husky/pre-commit +7 -7
  5. package/.prettierrc +4 -4
  6. package/Jenkinsfile +57 -57
  7. package/README.md +23 -23
  8. package/__tests__/unit/components/group/group.spec.ts +79 -79
  9. package/__tests__/unit/components/group-object-privilege/group-object-privilege.spec.ts +88 -88
  10. package/__tests__/unit/components/group-privilege/group-privilege.spec.ts +68 -68
  11. package/__tests__/unit/components/group-reporting-user/group-reporting-user.spec.ts +66 -66
  12. package/__tests__/unit/components/group-system-access/group-system-access.spec.ts +83 -83
  13. package/__tests__/unit/components/login-user/l.spec.ts +746 -746
  14. package/__tests__/unit/components/login-user/login.spec.ts +1164 -1164
  15. package/__tests__/unit/components/password-hash/password-hash.service.spec.ts +31 -31
  16. package/__tests__/unit/components/system/system.spec.ts +254 -254
  17. package/__tests__/unit/components/system-privilege/system-privilege.spec.ts +83 -83
  18. package/__tests__/unit/components/user-group/user-group.spec.ts +86 -86
  19. package/__tests__/unit/components/user-object-privilege/user-object-privilege.spec.ts +78 -78
  20. package/__tests__/unit/components/user-privilege/user-privilege.spec.ts +72 -72
  21. package/__tests__/unit/components/user-system-access/user-system-access.spec.ts +89 -89
  22. package/__tests__/unit/redis-client/redis.service.spec.ts +23 -23
  23. package/__tests__/unit/session/session.service.spec.ts +47 -47
  24. package/__tests__/unit/system-privilege/system-privilage.spec.ts +91 -91
  25. package/coverage/clover.xml +1452 -1452
  26. package/coverage/coverage-final.json +47 -47
  27. package/coverage/lcov-report/base.css +224 -224
  28. package/coverage/lcov-report/block-navigation.js +87 -87
  29. package/coverage/lcov-report/components/group/group.repository.ts.html +117 -117
  30. package/coverage/lcov-report/components/group/group.ts.html +327 -327
  31. package/coverage/lcov-report/components/group/index.html +130 -130
  32. package/coverage/lcov-report/components/group-object-privilege/group-object-privilege.repository.ts.html +117 -117
  33. package/coverage/lcov-report/components/group-object-privilege/group-object-privilege.ts.html +321 -321
  34. package/coverage/lcov-report/components/group-object-privilege/index.html +130 -130
  35. package/coverage/lcov-report/components/group-privilege/group-privilege.repository.ts.html +117 -117
  36. package/coverage/lcov-report/components/group-privilege/group-privilege.ts.html +303 -303
  37. package/coverage/lcov-report/components/group-privilege/index.html +130 -130
  38. package/coverage/lcov-report/components/group-reporting-user/group-reporting-user.repository.ts.html +117 -117
  39. package/coverage/lcov-report/components/group-reporting-user/group-reporting-user.ts.html +327 -327
  40. package/coverage/lcov-report/components/group-reporting-user/index.html +130 -130
  41. package/coverage/lcov-report/components/group-system-access/group-system-access.repository.ts.html +117 -117
  42. package/coverage/lcov-report/components/group-system-access/group-system-access.ts.html +309 -309
  43. package/coverage/lcov-report/components/group-system-access/index.html +130 -130
  44. package/coverage/lcov-report/components/login-history/index.html +115 -115
  45. package/coverage/lcov-report/components/login-history/login-history.repository.ts.html +117 -117
  46. package/coverage/lcov-report/components/login-user/index.html +130 -130
  47. package/coverage/lcov-report/components/login-user/login-user.ts.html +5007 -5007
  48. package/coverage/lcov-report/components/login-user/user.repository.ts.html +117 -117
  49. package/coverage/lcov-report/components/password-hash/index.html +115 -115
  50. package/coverage/lcov-report/components/password-hash/password-hash.service.ts.html +126 -126
  51. package/coverage/lcov-report/components/system/index.html +130 -130
  52. package/coverage/lcov-report/components/system/system.repository.ts.html +117 -117
  53. package/coverage/lcov-report/components/system/system.ts.html +909 -909
  54. package/coverage/lcov-report/components/system-privilege/index.html +130 -130
  55. package/coverage/lcov-report/components/system-privilege/system-privilege.repository.ts.html +120 -120
  56. package/coverage/lcov-report/components/system-privilege/system-privilege.ts.html +390 -390
  57. package/coverage/lcov-report/components/user-group/index.html +130 -130
  58. package/coverage/lcov-report/components/user-group/user-group.repository.ts.html +117 -117
  59. package/coverage/lcov-report/components/user-group/user-group.ts.html +354 -354
  60. package/coverage/lcov-report/components/user-object-privilege/index.html +130 -130
  61. package/coverage/lcov-report/components/user-object-privilege/user-object-privilege.repository.ts.html +117 -117
  62. package/coverage/lcov-report/components/user-object-privilege/user-object-privilege.ts.html +312 -312
  63. package/coverage/lcov-report/components/user-privilege/index.html +130 -130
  64. package/coverage/lcov-report/components/user-privilege/user-privilege.repository.ts.html +117 -117
  65. package/coverage/lcov-report/components/user-privilege/user-privilege.ts.html +306 -306
  66. package/coverage/lcov-report/components/user-system-access/index.html +130 -130
  67. package/coverage/lcov-report/components/user-system-access/user-system-access.repository.ts.html +117 -117
  68. package/coverage/lcov-report/components/user-system-access/user-system-access.ts.html +312 -312
  69. package/coverage/lcov-report/enum/group-type.enum.ts.html +108 -108
  70. package/coverage/lcov-report/enum/index.html +160 -160
  71. package/coverage/lcov-report/enum/index.ts.html +93 -93
  72. package/coverage/lcov-report/enum/user-status.enum.ts.html +105 -105
  73. package/coverage/lcov-report/enum/yn.enum.ts.html +96 -96
  74. package/coverage/lcov-report/index.html +370 -370
  75. package/coverage/lcov-report/models/group-object-privilege.entity.ts.html +333 -333
  76. package/coverage/lcov-report/models/group-privilege.entity.ts.html +315 -315
  77. package/coverage/lcov-report/models/group-reporting-user.entity.ts.html +339 -339
  78. package/coverage/lcov-report/models/group-system-access.entity.ts.html +324 -324
  79. package/coverage/lcov-report/models/group.entity.ts.html +435 -435
  80. package/coverage/lcov-report/models/index.html +310 -310
  81. package/coverage/lcov-report/models/login-history.entity.ts.html +252 -252
  82. package/coverage/lcov-report/models/staff.entity.ts.html +411 -411
  83. package/coverage/lcov-report/models/system-privilege.entity.ts.html +354 -354
  84. package/coverage/lcov-report/models/system.entity.ts.html +423 -423
  85. package/coverage/lcov-report/models/user-group.entity.ts.html +354 -354
  86. package/coverage/lcov-report/models/user-object-privilege.entity.ts.html +330 -330
  87. package/coverage/lcov-report/models/user-privilege.entity.ts.html +315 -315
  88. package/coverage/lcov-report/models/user-system-access.entity.ts.html +315 -315
  89. package/coverage/lcov-report/models/user.entity.ts.html +522 -522
  90. package/coverage/lcov-report/prettify.css +1 -1
  91. package/coverage/lcov-report/prettify.js +2 -2
  92. package/coverage/lcov-report/redis-client/index.html +115 -115
  93. package/coverage/lcov-report/redis-client/redis.service.ts.html +240 -240
  94. package/coverage/lcov-report/session/index.html +115 -115
  95. package/coverage/lcov-report/session/session.service.ts.html +246 -246
  96. package/coverage/lcov-report/sorter.js +196 -196
  97. package/coverage/lcov.info +2490 -2490
  98. package/coverage/test-report.xml +128 -128
  99. package/create-sso-user.sql +39 -39
  100. package/dist/src/components/login-history/login-history.d.ts +23 -0
  101. package/dist/src/components/login-history/login-history.js +88 -0
  102. package/dist/src/components/login-history/login-history.js.map +1 -0
  103. package/dist/src/components/login-user/user.js +4 -3
  104. package/dist/src/components/login-user/user.js.map +1 -1
  105. package/dist/src/interfaces/login-history-search-attr.interface.d.ts +8 -0
  106. package/dist/src/interfaces/login-history-search-attr.interface.js +3 -0
  107. package/dist/src/interfaces/login-history-search-attr.interface.js.map +1 -0
  108. package/dist/src/interfaces/login-history.interface.d.ts +11 -0
  109. package/dist/src/interfaces/login-history.interface.js +3 -0
  110. package/dist/src/interfaces/login-history.interface.js.map +1 -0
  111. package/dist/tsconfig.tsbuildinfo +1 -1
  112. package/eslint.config.mjs +58 -58
  113. package/jest.config.js +14 -14
  114. package/migrations/20240314080602-create-user-table.js +124 -124
  115. package/migrations/20240314080603-create-user-group-table.js +85 -85
  116. package/migrations/20240314080604-create-user-user-group-table.js +55 -55
  117. package/migrations/20240314080605-create-login-history-table.js +53 -53
  118. package/migrations/20240527064925-create-system-table.js +78 -78
  119. package/migrations/20240527064926-create-system-privilege-table.js +71 -71
  120. package/migrations/20240527065342-create-group-table.js +93 -93
  121. package/migrations/20240527065633-create-group-reporting-user-table.js +76 -76
  122. package/migrations/20240528011551-create-group-system-access-table.js +72 -72
  123. package/migrations/20240528023018-user-system-access-table.js +75 -75
  124. package/migrations/20240528032229-user-privilege-table.js +76 -76
  125. package/migrations/20240528063003-create-group-privilege-table.js +76 -76
  126. package/migrations/20240528063051-create-group-object-privilege-table.js +84 -84
  127. package/migrations/20240528063107-create-user-object-privilege-table.js +84 -84
  128. package/migrations/20240528063108-create-api-key-table.js +85 -85
  129. package/migrations/20241104104802-create-building-table.js +95 -95
  130. package/migrations/20250108091132-add-area-manager-user-id-to-building-table.js +14 -14
  131. package/migrations/20250108091133-add-passcode-to-user-table.js +36 -36
  132. package/migrations/20250210115636-create-user-reporting-hierarchy.js +76 -76
  133. package/migrations/20250326043818-crate-user-password-history.js +42 -42
  134. package/package.json +90 -90
  135. package/sampledotenv +7 -7
  136. package/sonar-project.properties +22 -22
  137. package/src/components/api-key/api-key.repository.ts +15 -15
  138. package/src/components/api-key/api-key.ts +448 -448
  139. package/src/components/api-key/index.ts +4 -4
  140. package/src/components/building/building.repository.ts +27 -27
  141. package/src/components/building/index.ts +2 -2
  142. package/src/components/group/group.repository.ts +26 -26
  143. package/src/components/group/group.ts +2284 -2284
  144. package/src/components/group/index.ts +3 -3
  145. package/src/components/group-object-privilege/group-object-privilege.repository.ts +25 -25
  146. package/src/components/group-object-privilege/group-object-privilege.ts +278 -278
  147. package/src/components/group-object-privilege/index.ts +2 -2
  148. package/src/components/group-privilege/group-privilege.repository.ts +29 -29
  149. package/src/components/group-privilege/group-privilege.ts +84 -84
  150. package/src/components/group-privilege/index.ts +2 -2
  151. package/src/components/group-reporting-user/group-reporting-user.repository.ts +23 -23
  152. package/src/components/group-reporting-user/group-reporting-user.ts +506 -506
  153. package/src/components/group-reporting-user/index.ts +3 -3
  154. package/src/components/group-system-access/group-system-access.repository.ts +43 -43
  155. package/src/components/group-system-access/group-system-access.ts +90 -90
  156. package/src/components/group-system-access/index.ts +2 -2
  157. package/src/components/index.ts +20 -20
  158. package/src/components/login-history/index.ts +1 -1
  159. package/src/components/login-history/login-history.repository.ts +11 -11
  160. package/src/components/login-user/index.ts +5 -5
  161. package/src/components/login-user/interfaces/check-user-info-duplicated.interface.ts +7 -7
  162. package/src/components/login-user/interfaces/index.ts +1 -1
  163. package/src/components/login-user/interfaces/system-access.interface.ts +13 -13
  164. package/src/components/login-user/interfaces/user-info.interface.ts +34 -34
  165. package/src/components/login-user/login-user.ts +362 -362
  166. package/src/components/login-user/user.repository.ts +11 -11
  167. package/src/components/login-user/user.ts +3143 -3142
  168. package/src/components/password-hash/index.ts +2 -2
  169. package/src/components/password-hash/interfaces/index.ts +1 -1
  170. package/src/components/password-hash/interfaces/password-hash-service.interface.ts +4 -4
  171. package/src/components/password-hash/password-hash.service.ts +14 -14
  172. package/src/components/staff/index.ts +2 -2
  173. package/src/components/staff/staff.repository.ts +27 -27
  174. package/src/components/system/index.ts +3 -3
  175. package/src/components/system/system.repository.ts +11 -11
  176. package/src/components/system/system.ts +456 -456
  177. package/src/components/system-privilege/index.ts +4 -4
  178. package/src/components/system-privilege/system-privilege.repository.ts +18 -18
  179. package/src/components/system-privilege/system-privilege.ts +541 -541
  180. package/src/components/user-group/index.ts +2 -2
  181. package/src/components/user-group/user-group.repository.ts +19 -19
  182. package/src/components/user-group/user-group.ts +764 -764
  183. package/src/components/user-object-privilege/index.ts +2 -2
  184. package/src/components/user-object-privilege/user-object-privilege.repository.ts +11 -11
  185. package/src/components/user-object-privilege/user-object-privilege.ts +79 -79
  186. package/src/components/user-password-history/index.ts +2 -2
  187. package/src/components/user-password-history/user-password-history.repository.ts +39 -39
  188. package/src/components/user-password-history/user-password-history.ts +187 -187
  189. package/src/components/user-privilege/index.ts +2 -2
  190. package/src/components/user-privilege/user-privilege.repository.ts +25 -25
  191. package/src/components/user-privilege/user-privilege.ts +662 -662
  192. package/src/components/user-reporting-hierarchy/index.ts +2 -2
  193. package/src/components/user-reporting-hierarchy/user-reporting-hierarchy.repository.ts +30 -30
  194. package/src/components/user-reporting-hierarchy/user-reporting-hierarchy.ts +505 -505
  195. package/src/components/user-system-access/index.ts +2 -2
  196. package/src/components/user-system-access/user-system-access.repository.ts +41 -41
  197. package/src/components/user-system-access/user-system-access.ts +717 -717
  198. package/src/database.ts +15 -15
  199. package/src/enum/api-key.enum.ts +5 -5
  200. package/src/enum/building-type.enum.ts +6 -6
  201. package/src/enum/group-type.enum.ts +8 -8
  202. package/src/enum/index.ts +6 -6
  203. package/src/enum/login-status.enum.ts +4 -4
  204. package/src/enum/object-status.enum.ts +4 -4
  205. package/src/enum/user-status.enum.ts +7 -7
  206. package/src/enum/yn.enum.ts +4 -4
  207. package/src/index.ts +8 -8
  208. package/src/interfaces/api-key-attr.interface.ts +16 -16
  209. package/src/interfaces/group-object-privilege.interface.ts +14 -14
  210. package/src/interfaces/group-privilege.interface.ts +10 -10
  211. package/src/interfaces/group-reporting-user.interface.ts +11 -11
  212. package/src/interfaces/group-search-attr.interface.ts +9 -9
  213. package/src/interfaces/group-system-access.interface.ts +10 -10
  214. package/src/interfaces/group.interface.ts +17 -17
  215. package/src/interfaces/index.ts +13 -13
  216. package/src/interfaces/system-login.interface.ts +6 -6
  217. package/src/interfaces/system-privilege-search.interface.ts +5 -5
  218. package/src/interfaces/system-privilege.interface.ts +11 -11
  219. package/src/interfaces/system-search-attr.interface.ts +5 -5
  220. package/src/interfaces/system.interface.ts +15 -15
  221. package/src/interfaces/user-group.interface.ts +12 -12
  222. package/src/interfaces/user-object-privilege.interface.ts +14 -14
  223. package/src/interfaces/user-password-history.interface.ts +6 -6
  224. package/src/interfaces/user-privilege.interface.ts +10 -10
  225. package/src/interfaces/user-reporting-hierarchy.interface.ts +11 -11
  226. package/src/interfaces/user-session.interface.ts +5 -5
  227. package/src/interfaces/user-system-access.interface.ts +10 -10
  228. package/src/models/api-key-entity.ts +101 -101
  229. package/src/models/building.entity.ts +103 -103
  230. package/src/models/group-object-privilege.entity.ts +91 -91
  231. package/src/models/group-privilege.entity.ts +78 -78
  232. package/src/models/group-reporting-user.entity.ts +95 -95
  233. package/src/models/group-system-access.entity.ts +81 -81
  234. package/src/models/group.entity.ts +127 -127
  235. package/src/models/login-history.entity.ts +63 -63
  236. package/src/models/staff.entity.ts +91 -91
  237. package/src/models/system-privilege.entity.ts +90 -90
  238. package/src/models/system.entity.ts +113 -113
  239. package/src/models/user-group.entity.ts +91 -91
  240. package/src/models/user-object-privilege.entity.ts +90 -90
  241. package/src/models/user-password-history.ts +51 -51
  242. package/src/models/user-privilege.entity.ts +78 -78
  243. package/src/models/user-reporting-hierarchy.entity.ts +102 -102
  244. package/src/models/user-system-access.entity.ts +87 -87
  245. package/src/models/user.entity.ts +193 -193
  246. package/src/redis-client/__mocks__/jest-initial-setup.ts +2 -2
  247. package/src/redis-client/__mocks__/redis-mock.ts +28 -28
  248. package/src/redis-client/index.ts +1 -1
  249. package/src/redis-client/redis.service.ts +75 -75
  250. package/src/session/index.ts +2 -2
  251. package/src/session/interfaces/index.ts +1 -1
  252. package/src/session/interfaces/session-service.interface.ts +26 -26
  253. package/src/session/session.service.ts +96 -96
  254. package/src/types/auth-context.ts +10 -10
  255. package/src/types/index.ts +1 -1
  256. package/tsconfig.build.json +5 -5
  257. package/tsconfig.json +23 -23
@@ -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
+ }