@tomei/sso 0.51.0 → 0.51.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (432) hide show
  1. package/.commitlintrc.json +22 -22
  2. package/.eslintrc +16 -16
  3. package/.eslintrc.js +35 -35
  4. package/.gitlab-ci.yml +16 -16
  5. package/.husky/commit-msg +15 -15
  6. package/.husky/pre-commit +7 -7
  7. package/.prettierrc +4 -4
  8. package/Jenkinsfile +57 -57
  9. package/README.md +23 -23
  10. package/__tests__/unit/components/group/group.spec.ts +79 -79
  11. package/__tests__/unit/components/group-object-privilege/group-object-privilege.spec.ts +88 -88
  12. package/__tests__/unit/components/group-privilege/group-privilege.spec.ts +68 -68
  13. package/__tests__/unit/components/group-reporting-user/group-reporting-user.spec.ts +66 -66
  14. package/__tests__/unit/components/group-system-access/group-system-access.spec.ts +83 -83
  15. package/__tests__/unit/components/login-user/l.spec.ts +746 -746
  16. package/__tests__/unit/components/login-user/login.spec.ts +1164 -1164
  17. package/__tests__/unit/components/password-hash/password-hash.service.spec.ts +31 -31
  18. package/__tests__/unit/components/system/system.spec.ts +254 -254
  19. package/__tests__/unit/components/system-privilege/system-privilege.spec.ts +83 -83
  20. package/__tests__/unit/components/user-group/user-group.spec.ts +86 -86
  21. package/__tests__/unit/components/user-object-privilege/user-object-privilege.spec.ts +78 -78
  22. package/__tests__/unit/components/user-privilege/user-privilege.spec.ts +72 -72
  23. package/__tests__/unit/components/user-system-access/user-system-access.spec.ts +89 -89
  24. package/__tests__/unit/redis-client/redis.service.spec.ts +23 -23
  25. package/__tests__/unit/session/session.service.spec.ts +47 -47
  26. package/__tests__/unit/system-privilege/system-privilage.spec.ts +91 -91
  27. package/coverage/clover.xml +1452 -1452
  28. package/coverage/coverage-final.json +47 -47
  29. package/coverage/lcov-report/base.css +224 -224
  30. package/coverage/lcov-report/block-navigation.js +87 -87
  31. package/coverage/lcov-report/components/group/group.repository.ts.html +117 -117
  32. package/coverage/lcov-report/components/group/group.ts.html +327 -327
  33. package/coverage/lcov-report/components/group/index.html +130 -130
  34. package/coverage/lcov-report/components/group-object-privilege/group-object-privilege.repository.ts.html +117 -117
  35. package/coverage/lcov-report/components/group-object-privilege/group-object-privilege.ts.html +321 -321
  36. package/coverage/lcov-report/components/group-object-privilege/index.html +130 -130
  37. package/coverage/lcov-report/components/group-privilege/group-privilege.repository.ts.html +117 -117
  38. package/coverage/lcov-report/components/group-privilege/group-privilege.ts.html +303 -303
  39. package/coverage/lcov-report/components/group-privilege/index.html +130 -130
  40. package/coverage/lcov-report/components/group-reporting-user/group-reporting-user.repository.ts.html +117 -117
  41. package/coverage/lcov-report/components/group-reporting-user/group-reporting-user.ts.html +327 -327
  42. package/coverage/lcov-report/components/group-reporting-user/index.html +130 -130
  43. package/coverage/lcov-report/components/group-system-access/group-system-access.repository.ts.html +117 -117
  44. package/coverage/lcov-report/components/group-system-access/group-system-access.ts.html +309 -309
  45. package/coverage/lcov-report/components/group-system-access/index.html +130 -130
  46. package/coverage/lcov-report/components/login-history/index.html +115 -115
  47. package/coverage/lcov-report/components/login-history/login-history.repository.ts.html +117 -117
  48. package/coverage/lcov-report/components/login-user/index.html +130 -130
  49. package/coverage/lcov-report/components/login-user/login-user.ts.html +5007 -5007
  50. package/coverage/lcov-report/components/login-user/user.repository.ts.html +117 -117
  51. package/coverage/lcov-report/components/password-hash/index.html +115 -115
  52. package/coverage/lcov-report/components/password-hash/password-hash.service.ts.html +126 -126
  53. package/coverage/lcov-report/components/system/index.html +130 -130
  54. package/coverage/lcov-report/components/system/system.repository.ts.html +117 -117
  55. package/coverage/lcov-report/components/system/system.ts.html +909 -909
  56. package/coverage/lcov-report/components/system-privilege/index.html +130 -130
  57. package/coverage/lcov-report/components/system-privilege/system-privilege.repository.ts.html +120 -120
  58. package/coverage/lcov-report/components/system-privilege/system-privilege.ts.html +390 -390
  59. package/coverage/lcov-report/components/user-group/index.html +130 -130
  60. package/coverage/lcov-report/components/user-group/user-group.repository.ts.html +117 -117
  61. package/coverage/lcov-report/components/user-group/user-group.ts.html +354 -354
  62. package/coverage/lcov-report/components/user-object-privilege/index.html +130 -130
  63. package/coverage/lcov-report/components/user-object-privilege/user-object-privilege.repository.ts.html +117 -117
  64. package/coverage/lcov-report/components/user-object-privilege/user-object-privilege.ts.html +312 -312
  65. package/coverage/lcov-report/components/user-privilege/index.html +130 -130
  66. package/coverage/lcov-report/components/user-privilege/user-privilege.repository.ts.html +117 -117
  67. package/coverage/lcov-report/components/user-privilege/user-privilege.ts.html +306 -306
  68. package/coverage/lcov-report/components/user-system-access/index.html +130 -130
  69. package/coverage/lcov-report/components/user-system-access/user-system-access.repository.ts.html +117 -117
  70. package/coverage/lcov-report/components/user-system-access/user-system-access.ts.html +312 -312
  71. package/coverage/lcov-report/enum/group-type.enum.ts.html +108 -108
  72. package/coverage/lcov-report/enum/index.html +160 -160
  73. package/coverage/lcov-report/enum/index.ts.html +93 -93
  74. package/coverage/lcov-report/enum/user-status.enum.ts.html +105 -105
  75. package/coverage/lcov-report/enum/yn.enum.ts.html +96 -96
  76. package/coverage/lcov-report/index.html +370 -370
  77. package/coverage/lcov-report/models/group-object-privilege.entity.ts.html +333 -333
  78. package/coverage/lcov-report/models/group-privilege.entity.ts.html +315 -315
  79. package/coverage/lcov-report/models/group-reporting-user.entity.ts.html +339 -339
  80. package/coverage/lcov-report/models/group-system-access.entity.ts.html +324 -324
  81. package/coverage/lcov-report/models/group.entity.ts.html +435 -435
  82. package/coverage/lcov-report/models/index.html +310 -310
  83. package/coverage/lcov-report/models/login-history.entity.ts.html +252 -252
  84. package/coverage/lcov-report/models/staff.entity.ts.html +411 -411
  85. package/coverage/lcov-report/models/system-privilege.entity.ts.html +354 -354
  86. package/coverage/lcov-report/models/system.entity.ts.html +423 -423
  87. package/coverage/lcov-report/models/user-group.entity.ts.html +354 -354
  88. package/coverage/lcov-report/models/user-object-privilege.entity.ts.html +330 -330
  89. package/coverage/lcov-report/models/user-privilege.entity.ts.html +315 -315
  90. package/coverage/lcov-report/models/user-system-access.entity.ts.html +315 -315
  91. package/coverage/lcov-report/models/user.entity.ts.html +522 -522
  92. package/coverage/lcov-report/prettify.css +1 -1
  93. package/coverage/lcov-report/prettify.js +2 -2
  94. package/coverage/lcov-report/redis-client/index.html +115 -115
  95. package/coverage/lcov-report/redis-client/redis.service.ts.html +240 -240
  96. package/coverage/lcov-report/session/index.html +115 -115
  97. package/coverage/lcov-report/session/session.service.ts.html +246 -246
  98. package/coverage/lcov-report/sorter.js +196 -196
  99. package/coverage/lcov.info +2490 -2490
  100. package/coverage/test-report.xml +128 -128
  101. package/create-sso-user.sql +39 -39
  102. package/dist/__tests__/unit/components/group/group.spec.d.ts +1 -1
  103. package/dist/__tests__/unit/components/group/group.spec.js +71 -71
  104. package/dist/__tests__/unit/components/group-object-privilege/group-object-privilege.spec.d.ts +1 -1
  105. package/dist/__tests__/unit/components/group-object-privilege/group-object-privilege.spec.js +85 -85
  106. package/dist/__tests__/unit/components/group-privilege/group-privilege.spec.d.ts +1 -1
  107. package/dist/__tests__/unit/components/group-privilege/group-privilege.spec.js +70 -70
  108. package/dist/__tests__/unit/components/group-reporting-user/group-reporting-user.spec.d.ts +1 -1
  109. package/dist/__tests__/unit/components/group-reporting-user/group-reporting-user.spec.js +57 -57
  110. package/dist/__tests__/unit/components/group-system-access/group-system-access.spec.d.ts +1 -1
  111. package/dist/__tests__/unit/components/group-system-access/group-system-access.spec.js +82 -82
  112. package/dist/__tests__/unit/components/login-user/l.spec.js +5 -5
  113. package/dist/__tests__/unit/components/login-user/login.spec.d.ts +1 -1
  114. package/dist/__tests__/unit/components/login-user/login.spec.js +2 -2
  115. package/dist/__tests__/unit/components/password-hash/password-hash.service.spec.d.ts +1 -1
  116. package/dist/__tests__/unit/components/password-hash/password-hash.service.spec.js +37 -37
  117. package/dist/__tests__/unit/components/system/system.spec.d.ts +1 -1
  118. package/dist/__tests__/unit/components/system/system.spec.js +203 -203
  119. package/dist/__tests__/unit/components/system-privilege/system-privilege.spec.d.ts +1 -1
  120. package/dist/__tests__/unit/components/system-privilege/system-privilege.spec.js +84 -84
  121. package/dist/__tests__/unit/components/user-group/user-group.spec.d.ts +1 -1
  122. package/dist/__tests__/unit/components/user-group/user-group.spec.js +81 -81
  123. package/dist/__tests__/unit/components/user-object-privilege/user-object-privilege.spec.d.ts +1 -1
  124. package/dist/__tests__/unit/components/user-object-privilege/user-object-privilege.spec.js +78 -78
  125. package/dist/__tests__/unit/components/user-privilege/user-privilege.spec.d.ts +1 -1
  126. package/dist/__tests__/unit/components/user-privilege/user-privilege.spec.js +75 -75
  127. package/dist/__tests__/unit/components/user-system-access/user-system-access.spec.d.ts +1 -1
  128. package/dist/__tests__/unit/components/user-system-access/user-system-access.spec.js +82 -82
  129. package/dist/__tests__/unit/components/user-system-access/user-system-access.spec.js.map +1 -1
  130. package/dist/__tests__/unit/redis-client/redis.service.spec.d.ts +1 -1
  131. package/dist/__tests__/unit/redis-client/redis.service.spec.js +31 -31
  132. package/dist/__tests__/unit/session/session.service.spec.d.ts +1 -1
  133. package/dist/__tests__/unit/session/session.service.spec.js +54 -54
  134. package/dist/__tests__/unit/system-privilege/system-privilage.spec.js +5 -5
  135. package/dist/index.d.ts +1 -1
  136. package/dist/index.js +17 -17
  137. package/dist/src/components/api-key/api-key.d.ts +84 -84
  138. package/dist/src/components/api-key/api-key.js +255 -255
  139. package/dist/src/components/api-key/api-key.js.map +1 -1
  140. package/dist/src/components/api-key/api-key.repository.d.ts +6 -6
  141. package/dist/src/components/api-key/api-key.repository.js +25 -25
  142. package/dist/src/components/api-key/index.d.ts +3 -3
  143. package/dist/src/components/api-key/index.js +7 -7
  144. package/dist/src/components/building/building.repository.d.ts +6 -6
  145. package/dist/src/components/building/building.repository.js +37 -37
  146. package/dist/src/components/building/building.repository.js.map +1 -1
  147. package/dist/src/components/building/index.d.ts +1 -1
  148. package/dist/src/components/building/index.js +17 -17
  149. package/dist/src/components/group/group.d.ts +112 -112
  150. package/dist/src/components/group/group.js +1240 -1240
  151. package/dist/src/components/group/group.js.map +1 -1
  152. package/dist/src/components/group/group.repository.d.ts +7 -7
  153. package/dist/src/components/group/group.repository.js +36 -36
  154. package/dist/src/components/group/group.repository.js.map +1 -1
  155. package/dist/src/components/group/index.d.ts +2 -2
  156. package/dist/src/components/group/index.js +18 -18
  157. package/dist/src/components/group-object-privilege/group-object-privilege.d.ts +27 -27
  158. package/dist/src/components/group-object-privilege/group-object-privilege.js +177 -177
  159. package/dist/src/components/group-object-privilege/group-object-privilege.js.map +1 -1
  160. package/dist/src/components/group-object-privilege/group-object-privilege.repository.d.ts +6 -6
  161. package/dist/src/components/group-object-privilege/group-object-privilege.repository.js +33 -33
  162. package/dist/src/components/group-object-privilege/group-object-privilege.repository.js.map +1 -1
  163. package/dist/src/components/group-object-privilege/index.d.ts +2 -2
  164. package/dist/src/components/group-object-privilege/index.js +18 -18
  165. package/dist/src/components/group-privilege/group-privilege.d.ts +24 -24
  166. package/dist/src/components/group-privilege/group-privilege.js +77 -77
  167. package/dist/src/components/group-privilege/group-privilege.js.map +1 -1
  168. package/dist/src/components/group-privilege/group-privilege.repository.d.ts +6 -6
  169. package/dist/src/components/group-privilege/group-privilege.repository.js +35 -35
  170. package/dist/src/components/group-privilege/group-privilege.repository.js.map +1 -1
  171. package/dist/src/components/group-privilege/index.d.ts +2 -2
  172. package/dist/src/components/group-privilege/index.js +18 -18
  173. package/dist/src/components/group-reporting-user/group-reporting-user.d.ts +28 -28
  174. package/dist/src/components/group-reporting-user/group-reporting-user.js +208 -208
  175. package/dist/src/components/group-reporting-user/group-reporting-user.js.map +1 -1
  176. package/dist/src/components/group-reporting-user/group-reporting-user.repository.d.ts +6 -6
  177. package/dist/src/components/group-reporting-user/group-reporting-user.repository.js +30 -30
  178. package/dist/src/components/group-reporting-user/index.d.ts +2 -2
  179. package/dist/src/components/group-reporting-user/index.js +18 -18
  180. package/dist/src/components/group-system-access/group-system-access.d.ts +27 -27
  181. package/dist/src/components/group-system-access/group-system-access.js +80 -80
  182. package/dist/src/components/group-system-access/group-system-access.js.map +1 -1
  183. package/dist/src/components/group-system-access/group-system-access.repository.d.ts +7 -7
  184. package/dist/src/components/group-system-access/group-system-access.repository.js +55 -54
  185. package/dist/src/components/group-system-access/group-system-access.repository.js.map +1 -1
  186. package/dist/src/components/group-system-access/index.d.ts +2 -2
  187. package/dist/src/components/group-system-access/index.js +18 -18
  188. package/dist/src/components/index.d.ts +17 -17
  189. package/dist/src/components/index.js +33 -33
  190. package/dist/src/components/login-history/index.d.ts +1 -1
  191. package/dist/src/components/login-history/index.js +17 -17
  192. package/dist/src/components/login-history/login-history.repository.d.ts +5 -5
  193. package/dist/src/components/login-history/login-history.repository.js +11 -11
  194. package/dist/src/components/login-user/index.d.ts +4 -4
  195. package/dist/src/components/login-user/index.js +20 -20
  196. package/dist/src/components/login-user/interfaces/check-user-info-duplicated.interface.d.ts +7 -7
  197. package/dist/src/components/login-user/interfaces/check-user-info-duplicated.interface.js +2 -2
  198. package/dist/src/components/login-user/interfaces/index.d.ts +1 -1
  199. package/dist/src/components/login-user/interfaces/index.js +17 -17
  200. package/dist/src/components/login-user/interfaces/system-access.interface.d.ts +13 -13
  201. package/dist/src/components/login-user/interfaces/system-access.interface.js +2 -2
  202. package/dist/src/components/login-user/interfaces/user-info.interface.d.ts +30 -30
  203. package/dist/src/components/login-user/interfaces/user-info.interface.js +2 -2
  204. package/dist/src/components/login-user/login-user.d.ts +13 -13
  205. package/dist/src/components/login-user/login-user.js +140 -140
  206. package/dist/src/components/login-user/login-user.js.map +1 -1
  207. package/dist/src/components/login-user/user.d.ts +143 -143
  208. package/dist/src/components/login-user/user.js +1791 -1791
  209. package/dist/src/components/login-user/user.js.map +1 -1
  210. package/dist/src/components/login-user/user.repository.d.ts +5 -5
  211. package/dist/src/components/login-user/user.repository.js +11 -11
  212. package/dist/src/components/password-hash/index.d.ts +2 -2
  213. package/dist/src/components/password-hash/index.js +18 -18
  214. package/dist/src/components/password-hash/interfaces/index.d.ts +1 -1
  215. package/dist/src/components/password-hash/interfaces/index.js +17 -17
  216. package/dist/src/components/password-hash/interfaces/password-hash-service.interface.d.ts +4 -4
  217. package/dist/src/components/password-hash/interfaces/password-hash-service.interface.js +2 -2
  218. package/dist/src/components/password-hash/password-hash.service.d.ts +6 -6
  219. package/dist/src/components/password-hash/password-hash.service.js +27 -27
  220. package/dist/src/components/staff/index.d.ts +1 -1
  221. package/dist/src/components/staff/index.js +17 -17
  222. package/dist/src/components/staff/staff.repository.d.ts +6 -6
  223. package/dist/src/components/staff/staff.repository.js +37 -37
  224. package/dist/src/components/staff/staff.repository.js.map +1 -1
  225. package/dist/src/components/system/index.d.ts +2 -2
  226. package/dist/src/components/system/index.js +18 -18
  227. package/dist/src/components/system/system.d.ts +39 -39
  228. package/dist/src/components/system/system.js +300 -300
  229. package/dist/src/components/system/system.js.map +1 -1
  230. package/dist/src/components/system/system.repository.d.ts +5 -5
  231. package/dist/src/components/system/system.repository.js +11 -11
  232. package/dist/src/components/system-privilege/index.d.ts +3 -3
  233. package/dist/src/components/system-privilege/index.js +7 -7
  234. package/dist/src/components/system-privilege/system-privilege.d.ts +52 -52
  235. package/dist/src/components/system-privilege/system-privilege.js +335 -335
  236. package/dist/src/components/system-privilege/system-privilege.js.map +1 -1
  237. package/dist/src/components/system-privilege/system-privilege.repository.d.ts +6 -6
  238. package/dist/src/components/system-privilege/system-privilege.repository.js +28 -28
  239. package/dist/src/components/user-group/index.d.ts +2 -2
  240. package/dist/src/components/user-group/index.js +18 -18
  241. package/dist/src/components/user-group/user-group.d.ts +50 -50
  242. package/dist/src/components/user-group/user-group.js +352 -352
  243. package/dist/src/components/user-group/user-group.js.map +1 -1
  244. package/dist/src/components/user-group/user-group.repository.d.ts +5 -5
  245. package/dist/src/components/user-group/user-group.repository.js +11 -11
  246. package/dist/src/components/user-object-privilege/index.d.ts +2 -2
  247. package/dist/src/components/user-object-privilege/index.js +18 -18
  248. package/dist/src/components/user-object-privilege/user-object-privilege.d.ts +23 -23
  249. package/dist/src/components/user-object-privilege/user-object-privilege.js +69 -69
  250. package/dist/src/components/user-object-privilege/user-object-privilege.js.map +1 -1
  251. package/dist/src/components/user-object-privilege/user-object-privilege.repository.d.ts +5 -5
  252. package/dist/src/components/user-object-privilege/user-object-privilege.repository.js +11 -11
  253. package/dist/src/components/user-privilege/index.d.ts +2 -2
  254. package/dist/src/components/user-privilege/index.js +18 -18
  255. package/dist/src/components/user-privilege/user-privilege.d.ts +64 -64
  256. package/dist/src/components/user-privilege/user-privilege.js +406 -406
  257. package/dist/src/components/user-privilege/user-privilege.js.map +1 -1
  258. package/dist/src/components/user-privilege/user-privilege.repository.d.ts +6 -6
  259. package/dist/src/components/user-privilege/user-privilege.repository.js +36 -36
  260. package/dist/src/components/user-privilege/user-privilege.repository.js.map +1 -1
  261. package/dist/src/components/user-system-access/index.d.ts +2 -2
  262. package/dist/src/components/user-system-access/index.js +18 -18
  263. package/dist/src/components/user-system-access/user-system-access.d.ts +56 -56
  264. package/dist/src/components/user-system-access/user-system-access.js +277 -277
  265. package/dist/src/components/user-system-access/user-system-access.js.map +1 -1
  266. package/dist/src/components/user-system-access/user-system-access.repository.d.ts +6 -6
  267. package/dist/src/components/user-system-access/user-system-access.repository.js +36 -36
  268. package/dist/src/components/user-system-access/user-system-access.repository.js.map +1 -1
  269. package/dist/src/database.d.ts +4 -4
  270. package/dist/src/database.js +13 -14
  271. package/dist/src/database.js.map +1 -1
  272. package/dist/src/enum/api-key.enum.d.ts +5 -5
  273. package/dist/src/enum/api-key.enum.js +9 -9
  274. package/dist/src/enum/api-key.enum.js.map +1 -1
  275. package/dist/src/enum/group-type.enum.d.ts +8 -8
  276. package/dist/src/enum/group-type.enum.js +12 -12
  277. package/dist/src/enum/group-type.enum.js.map +1 -1
  278. package/dist/src/enum/index.d.ts +6 -6
  279. package/dist/src/enum/index.js +22 -22
  280. package/dist/src/enum/login-status.enum.d.ts +4 -4
  281. package/dist/src/enum/login-status.enum.js +8 -8
  282. package/dist/src/enum/login-status.enum.js.map +1 -1
  283. package/dist/src/enum/object-status.enum.d.ts +4 -4
  284. package/dist/src/enum/object-status.enum.js +8 -8
  285. package/dist/src/enum/object-status.enum.js.map +1 -1
  286. package/dist/src/enum/user-status.enum.d.ts +7 -7
  287. package/dist/src/enum/user-status.enum.js +11 -11
  288. package/dist/src/enum/user-status.enum.js.map +1 -1
  289. package/dist/src/enum/yn.enum.d.ts +4 -4
  290. package/dist/src/enum/yn.enum.js +8 -8
  291. package/dist/src/enum/yn.enum.js.map +1 -1
  292. package/dist/src/index.d.ts +6 -6
  293. package/dist/src/index.js +24 -24
  294. package/dist/src/interfaces/api-key-attr.interface.d.ts +15 -15
  295. package/dist/src/interfaces/api-key-attr.interface.js +2 -2
  296. package/dist/src/interfaces/group-object-privilege.interface.d.ts +13 -13
  297. package/dist/src/interfaces/group-object-privilege.interface.js +2 -2
  298. package/dist/src/interfaces/group-privilege.interface.d.ts +10 -10
  299. package/dist/src/interfaces/group-privilege.interface.js +2 -2
  300. package/dist/src/interfaces/group-reporting-user.interface.d.ts +11 -11
  301. package/dist/src/interfaces/group-reporting-user.interface.js +2 -2
  302. package/dist/src/interfaces/group-search-attr.interface.d.ts +8 -8
  303. package/dist/src/interfaces/group-search-attr.interface.js +2 -2
  304. package/dist/src/interfaces/group-system-access.interface.d.ts +10 -10
  305. package/dist/src/interfaces/group-system-access.interface.js +2 -2
  306. package/dist/src/interfaces/group.interface.d.ts +16 -16
  307. package/dist/src/interfaces/group.interface.js +2 -2
  308. package/dist/src/interfaces/index.d.ts +13 -13
  309. package/dist/src/interfaces/index.js +29 -29
  310. package/dist/src/interfaces/system-login.interface.d.ts +6 -6
  311. package/dist/src/interfaces/system-login.interface.js +2 -2
  312. package/dist/src/interfaces/system-privilege-search.interface.d.ts +5 -5
  313. package/dist/src/interfaces/system-privilege-search.interface.js +2 -2
  314. package/dist/src/interfaces/system-privilege.interface.d.ts +11 -11
  315. package/dist/src/interfaces/system-privilege.interface.js +2 -2
  316. package/dist/src/interfaces/system-search-attr.interface.d.ts +5 -5
  317. package/dist/src/interfaces/system-search-attr.interface.js +2 -2
  318. package/dist/src/interfaces/system.interface.d.ts +15 -15
  319. package/dist/src/interfaces/system.interface.js +2 -2
  320. package/dist/src/interfaces/user-group.interface.d.ts +12 -12
  321. package/dist/src/interfaces/user-group.interface.js +2 -2
  322. package/dist/src/interfaces/user-object-privilege.interface.d.ts +13 -13
  323. package/dist/src/interfaces/user-object-privilege.interface.js +2 -2
  324. package/dist/src/interfaces/user-privilege.interface.d.ts +10 -10
  325. package/dist/src/interfaces/user-privilege.interface.js +2 -2
  326. package/dist/src/interfaces/user-session.interface.d.ts +4 -4
  327. package/dist/src/interfaces/user-session.interface.js +2 -2
  328. package/dist/src/interfaces/user-system-access.interface.d.ts +10 -10
  329. package/dist/src/interfaces/user-system-access.interface.js +2 -2
  330. package/dist/src/models/api-key-entity.d.ts +21 -21
  331. package/dist/src/models/api-key-entity.js +121 -121
  332. package/dist/src/models/api-key-entity.js.map +1 -1
  333. package/dist/src/models/building.entity.d.ts +29 -29
  334. package/dist/src/models/building.entity.js +212 -212
  335. package/dist/src/models/building.entity.js.map +1 -1
  336. package/dist/src/models/group-object-privilege.entity.d.ts +21 -21
  337. package/dist/src/models/group-object-privilege.entity.js +110 -110
  338. package/dist/src/models/group-object-privilege.entity.js.map +1 -1
  339. package/dist/src/models/group-privilege.entity.d.ts +18 -18
  340. package/dist/src/models/group-privilege.entity.js +95 -95
  341. package/dist/src/models/group-privilege.entity.js.map +1 -1
  342. package/dist/src/models/group-reporting-user.entity.d.ts +17 -17
  343. package/dist/src/models/group-reporting-user.entity.js +113 -113
  344. package/dist/src/models/group-reporting-user.entity.js.map +1 -1
  345. package/dist/src/models/group-system-access.entity.d.ts +18 -18
  346. package/dist/src/models/group-system-access.entity.js +98 -98
  347. package/dist/src/models/group-system-access.entity.js.map +1 -1
  348. package/dist/src/models/group.entity.d.ts +32 -32
  349. package/dist/src/models/group.entity.js +153 -154
  350. package/dist/src/models/group.entity.js.map +1 -1
  351. package/dist/src/models/login-history.entity.d.ts +14 -14
  352. package/dist/src/models/login-history.entity.js +77 -77
  353. package/dist/src/models/login-history.entity.js.map +1 -1
  354. package/dist/src/models/staff.entity.d.ts +18 -18
  355. package/dist/src/models/staff.entity.js +109 -109
  356. package/dist/src/models/staff.entity.js.map +1 -1
  357. package/dist/src/models/system-privilege.entity.d.ts +18 -18
  358. package/dist/src/models/system-privilege.entity.js +107 -107
  359. package/dist/src/models/system-privilege.entity.js.map +1 -1
  360. package/dist/src/models/system.entity.d.ts +25 -25
  361. package/dist/src/models/system.entity.js +135 -135
  362. package/dist/src/models/system.entity.js.map +1 -1
  363. package/dist/src/models/user-group.entity.d.ts +19 -19
  364. package/dist/src/models/user-group.entity.js +110 -110
  365. package/dist/src/models/user-group.entity.js.map +1 -1
  366. package/dist/src/models/user-object-privilege.entity.d.ts +20 -20
  367. package/dist/src/models/user-object-privilege.entity.js +109 -109
  368. package/dist/src/models/user-object-privilege.entity.js.map +1 -1
  369. package/dist/src/models/user-privilege.entity.d.ts +17 -17
  370. package/dist/src/models/user-privilege.entity.js +95 -95
  371. package/dist/src/models/user-privilege.entity.js.map +1 -1
  372. package/dist/src/models/user-system-access.entity.d.ts +17 -17
  373. package/dist/src/models/user-system-access.entity.js +104 -104
  374. package/dist/src/models/user-system-access.entity.js.map +1 -1
  375. package/dist/src/models/user.entity.d.ts +40 -40
  376. package/dist/src/models/user.entity.js +214 -215
  377. package/dist/src/models/user.entity.js.map +1 -1
  378. package/dist/src/redis-client/__mocks__/jest-initial-setup.d.ts +1 -1
  379. package/dist/src/redis-client/__mocks__/jest-initial-setup.js +4 -4
  380. package/dist/src/redis-client/__mocks__/redis-mock.d.ts +2 -2
  381. package/dist/src/redis-client/__mocks__/redis-mock.js +22 -22
  382. package/dist/src/redis-client/index.d.ts +1 -1
  383. package/dist/src/redis-client/index.js +17 -17
  384. package/dist/src/redis-client/redis.service.d.ts +9 -9
  385. package/dist/src/redis-client/redis.service.js +87 -87
  386. package/dist/src/redis-client/redis.service.js.map +1 -1
  387. package/dist/src/session/index.d.ts +2 -2
  388. package/dist/src/session/index.js +18 -18
  389. package/dist/src/session/interfaces/index.d.ts +1 -1
  390. package/dist/src/session/interfaces/index.js +17 -17
  391. package/dist/src/session/interfaces/session-service.interface.d.ts +9 -9
  392. package/dist/src/session/interfaces/session-service.interface.js +2 -2
  393. package/dist/src/session/session.service.d.ts +13 -13
  394. package/dist/src/session/session.service.js +95 -95
  395. package/dist/src/session/session.service.js.map +1 -1
  396. package/dist/tsconfig.tsbuildinfo +1 -1
  397. package/eslint.config.mjs +37 -0
  398. package/jest.config.js +14 -14
  399. package/migrations/20240314080602-create-user-table.js +124 -124
  400. package/migrations/20240314080603-create-user-group-table.js +85 -85
  401. package/migrations/20240314080604-create-user-user-group-table.js +55 -55
  402. package/migrations/20240314080605-create-login-history-table.js +53 -53
  403. package/migrations/20240527064925-create-system-table.js +78 -78
  404. package/migrations/20240527064926-create-system-privilege-table.js +71 -71
  405. package/migrations/20240527065342-create-group-table.js +93 -93
  406. package/migrations/20240527065633-create-group-reporting-user-table.js +76 -76
  407. package/migrations/20240528011551-create-group-system-access-table.js +72 -72
  408. package/migrations/20240528023018-user-system-access-table.js +75 -75
  409. package/migrations/20240528032229-user-privilege-table.js +76 -76
  410. package/migrations/20240528063003-create-group-privilege-table.js +76 -76
  411. package/migrations/20240528063051-create-group-object-privilege-table.js +84 -84
  412. package/migrations/20240528063107-create-user-object-privilege-table.js +84 -84
  413. package/migrations/20240528063108-create-api-key-table.js +85 -85
  414. package/migrations/20241104104802-create-building-table.js +95 -95
  415. package/package.json +89 -89
  416. package/sampledotenv +7 -7
  417. package/sonar-project.properties +22 -22
  418. package/src/components/group/group.ts +2 -3
  419. package/src/components/group-system-access/group-system-access.repository.ts +2 -3
  420. package/src/components/login-user/login-user.ts +2 -3
  421. package/src/components/login-user/user.ts +6 -6
  422. package/src/components/system-privilege/system-privilege.ts +2 -3
  423. package/src/components/user-privilege/user-privilege.ts +2 -3
  424. package/src/components/user-system-access/user-system-access.ts +2 -3
  425. package/tsconfig.build.json +5 -5
  426. package/tsconfig.json +22 -22
  427. package/dist/__tests__/unit/components/group-privilege/group-privilege.test.d.ts +0 -1
  428. package/dist/__tests__/unit/components/group-privilege/group-privilege.test.js +0 -71
  429. package/dist/__tests__/unit/components/group-privilege/group-privilege.test.js.map +0 -1
  430. package/dist/__tests__/unit/components/login-user/login-user.spec.d.ts +0 -0
  431. package/dist/__tests__/unit/components/login-user/login-user.spec.js +0 -6
  432. package/dist/__tests__/unit/components/login-user/login-user.spec.js.map +0 -1
@@ -1,1792 +1,1792 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.User = void 0;
13
- const general_1 = require("@tomei/general");
14
- const user_repository_1 = require("./user.repository");
15
- const system_repository_1 = require("../system/system.repository");
16
- const login_history_repository_1 = require("../login-history/login-history.repository");
17
- const password_hash_service_1 = require("../password-hash/password-hash.service");
18
- const user_group_repository_1 = require("../user-group/user-group.repository");
19
- const staff_entity_1 = require("../../models/staff.entity");
20
- const system_privilege_entity_1 = require("../../models/system-privilege.entity");
21
- const yn_enum_1 = require("../../enum/yn.enum");
22
- const enum_1 = require("../../enum");
23
- const config_1 = require("@tomei/config");
24
- const sequelize_1 = require("sequelize");
25
- const activity_history_1 = require("@tomei/activity-history");
26
- const user_entity_1 = require("../../models/user.entity");
27
- const group_entity_1 = require("../../models/group.entity");
28
- const group_system_access_repository_1 = require("../group-system-access/group-system-access.repository");
29
- const group_repository_1 = require("../group/group.repository");
30
- const system_entity_1 = require("../../models/system.entity");
31
- const user_system_access_repository_1 = require("../user-system-access/user-system-access.repository");
32
- const group_system_access_entity_1 = require("../../models/group-system-access.entity");
33
- const user_privilege_repository_1 = require("../user-privilege/user-privilege.repository");
34
- const user_object_privilege_repository_1 = require("../user-object-privilege/user-object-privilege.repository");
35
- const group_privilege_entity_1 = require("../../models/group-privilege.entity");
36
- const group_object_privilege_repository_1 = require("../group-object-privilege/group-object-privilege.repository");
37
- const speakeasy = require("speakeasy");
38
- const login_status_enum_1 = require("../../enum/login-status.enum");
39
- const redis_service_1 = require("../../redis-client/redis.service");
40
- const login_user_1 = require("./login-user");
41
- const session_service_1 = require("../../session/session.service");
42
- const crypto_1 = require("crypto");
43
- class User extends general_1.UserBase {
44
- get SessionService() {
45
- return this._SessionService;
46
- }
47
- get UserId() {
48
- return parseInt(this.ObjectId);
49
- }
50
- set UserId(value) {
51
- this.ObjectId = value.toString();
52
- }
53
- get Password() {
54
- return this._Password;
55
- }
56
- set Password(value) {
57
- this._Password = value;
58
- }
59
- get Status() {
60
- return this._Status;
61
- }
62
- set Status(value) {
63
- this._Status = value;
64
- }
65
- get UserName() {
66
- return this._UserName;
67
- }
68
- set UserName(value) {
69
- this._UserName = value;
70
- }
71
- get DefaultPasswordChangedYN() {
72
- return this._DefaultPasswordChangedYN;
73
- }
74
- set DefaultPasswordChangedYN(value) {
75
- this._DefaultPasswordChangedYN = value;
76
- }
77
- get FirstLoginAt() {
78
- return this._FirstLoginAt;
79
- }
80
- set FirstLoginAt(value) {
81
- this._FirstLoginAt = value;
82
- }
83
- get LastLoginAt() {
84
- return this._LastLoginAt;
85
- }
86
- set LastLoginAt(value) {
87
- this._LastLoginAt = value;
88
- }
89
- get MFAEnabled() {
90
- return this._MFAEnabled;
91
- }
92
- set MFAEnabled(value) {
93
- this._MFAEnabled = value;
94
- }
95
- get MFAConfig() {
96
- return this._MFAConfig;
97
- }
98
- set MFAConfig(value) {
99
- this._MFAConfig = value;
100
- }
101
- get RecoveryEmail() {
102
- return this._RecoveryEmail;
103
- }
104
- set RecoveryEmail(value) {
105
- this._RecoveryEmail = value;
106
- }
107
- get FailedLoginAttemptCount() {
108
- return this._FailedLoginAttemptCount;
109
- }
110
- set FailedLoginAttemptCount(value) {
111
- this._FailedLoginAttemptCount = value;
112
- }
113
- get LastFailedLoginAt() {
114
- return this._LastFailedLoginAt;
115
- }
116
- set LastFailedLoginAt(value) {
117
- this._LastFailedLoginAt = value;
118
- }
119
- get LastPasswordChangedAt() {
120
- return this._LastPasswordChangedAt;
121
- }
122
- set LastPasswordChangedAt(value) {
123
- this._LastPasswordChangedAt = value;
124
- }
125
- get NeedToChangePasswordYN() {
126
- return this._NeedToChangePasswordYN;
127
- }
128
- set NeedToChangePasswordYN(value) {
129
- this._NeedToChangePasswordYN = value;
130
- }
131
- get CreatedById() {
132
- return this._CreatedById;
133
- }
134
- set CreatedById(value) {
135
- this._CreatedById = value;
136
- }
137
- get CreatedAt() {
138
- return this._CreatedAt;
139
- }
140
- set CreatedAt(value) {
141
- this._CreatedAt = value;
142
- }
143
- get UpdatedById() {
144
- return this._UpdatedById;
145
- }
146
- set UpdatedById(value) {
147
- this._UpdatedById = value;
148
- }
149
- get UpdatedAt() {
150
- return this._UpdatedAt;
151
- }
152
- set UpdatedAt(value) {
153
- this._UpdatedAt = value;
154
- }
155
- getDetails() {
156
- return __awaiter(this, void 0, void 0, function* () {
157
- return {
158
- FullName: this.FullName,
159
- UserName: this.UserName,
160
- IDNo: this.IDNo,
161
- IDType: this.IDType,
162
- Email: this.Email,
163
- ContactNo: this.ContactNo,
164
- };
165
- });
166
- }
167
- constructor(sessionService, dbTransaction, userInfo) {
168
- super();
169
- this.ObjectName = 'User';
170
- this.TableName = 'sso_Users';
171
- this.ObjectType = 'User';
172
- this._SessionService = sessionService;
173
- if (dbTransaction) {
174
- this._dbTransaction = dbTransaction;
175
- }
176
- if (userInfo) {
177
- this.UserId = userInfo.UserId;
178
- this.UserName = userInfo.UserName;
179
- this.FullName = userInfo.FullName;
180
- this.IDNo = userInfo.IDNo;
181
- this.IDType = userInfo.IDType;
182
- this.Email = userInfo.Email;
183
- this.ContactNo = userInfo.ContactNo;
184
- this.Password = userInfo.Password;
185
- this.staffs = userInfo.staffs;
186
- this.Status = userInfo.Status;
187
- this.DefaultPasswordChangedYN = userInfo.DefaultPasswordChangedYN;
188
- this.FirstLoginAt = userInfo.FirstLoginAt;
189
- this.LastLoginAt = userInfo.LastLoginAt;
190
- this.MFAEnabled = userInfo.MFAEnabled;
191
- this.MFAConfig = userInfo.MFAConfig;
192
- this.RecoveryEmail = userInfo.RecoveryEmail;
193
- this.FailedLoginAttemptCount = userInfo.FailedLoginAttemptCount;
194
- this.LastFailedLoginAt = userInfo.LastFailedLoginAt;
195
- this.LastPasswordChangedAt = userInfo.LastPasswordChangedAt;
196
- this.NeedToChangePasswordYN = userInfo.NeedToChangePasswordYN;
197
- this.CreatedById = userInfo.CreatedById;
198
- this.CreatedAt = userInfo.CreatedAt;
199
- this.UpdatedById = userInfo.UpdatedById;
200
- this.UpdatedAt = userInfo.UpdatedAt;
201
- }
202
- }
203
- static init(sessionService, userId, dbTransaction = null) {
204
- return __awaiter(this, void 0, void 0, function* () {
205
- User._RedisService = yield redis_service_1.RedisService.init();
206
- if (userId) {
207
- if (dbTransaction) {
208
- User._Repository = new user_repository_1.UserRepository();
209
- }
210
- const user = yield User._Repository.findOne({
211
- where: {
212
- UserId: userId,
213
- },
214
- include: [
215
- {
216
- model: staff_entity_1.default,
217
- },
218
- ],
219
- transaction: dbTransaction,
220
- });
221
- if (!user) {
222
- throw new Error('Invalid credentials.');
223
- }
224
- if (user) {
225
- const userAttr = {
226
- UserId: user.UserId,
227
- UserName: user.UserName,
228
- FullName: (user === null || user === void 0 ? void 0 : user.FullName) || null,
229
- IDNo: (user === null || user === void 0 ? void 0 : user.IdNo) || null,
230
- IDType: (user === null || user === void 0 ? void 0 : user.IdType) || null,
231
- ContactNo: (user === null || user === void 0 ? void 0 : user.ContactNo) || null,
232
- Email: user.Email,
233
- Password: user.Password,
234
- Status: user.Status,
235
- DefaultPasswordChangedYN: user.DefaultPasswordChangedYN,
236
- FirstLoginAt: user.FirstLoginAt,
237
- LastLoginAt: user.LastLoginAt,
238
- MFAEnabled: user.MFAEnabled,
239
- MFAConfig: user.MFAConfig,
240
- RecoveryEmail: user.RecoveryEmail,
241
- FailedLoginAttemptCount: user.FailedLoginAttemptCount,
242
- LastFailedLoginAt: user.LastFailedLoginAt,
243
- LastPasswordChangedAt: user.LastPasswordChangedAt,
244
- NeedToChangePasswordYN: user.NeedToChangePasswordYN,
245
- CreatedById: user.CreatedById,
246
- CreatedAt: user.CreatedAt,
247
- UpdatedById: user.UpdatedById,
248
- UpdatedAt: user.UpdatedAt,
249
- staffs: user === null || user === void 0 ? void 0 : user.Staff,
250
- };
251
- return new User(sessionService, dbTransaction, userAttr);
252
- }
253
- else {
254
- throw new Error('User not found');
255
- }
256
- }
257
- return new User(sessionService, dbTransaction);
258
- });
259
- }
260
- setEmail(email, dbTransaction) {
261
- return __awaiter(this, void 0, void 0, function* () {
262
- try {
263
- if (this.Email === email) {
264
- return;
265
- }
266
- const user = yield User._Repository.findOne({
267
- where: {
268
- Email: email,
269
- },
270
- transaction: dbTransaction,
271
- });
272
- if (user) {
273
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Email already exists');
274
- }
275
- this.Email = email;
276
- }
277
- catch (error) {
278
- throw error;
279
- }
280
- });
281
- }
282
- login(systemCode, email, password, ipAddress, dbTransaction) {
283
- return __awaiter(this, void 0, void 0, function* () {
284
- try {
285
- if (!this.ObjectId) {
286
- const user = yield User._Repository.findOne({
287
- transaction: dbTransaction,
288
- where: {
289
- Email: email,
290
- Status: {
291
- [sequelize_1.Op.or]: [enum_1.UserStatus.ACTIVE, enum_1.UserStatus.LOCKED],
292
- },
293
- },
294
- include: [
295
- {
296
- model: staff_entity_1.default,
297
- },
298
- ],
299
- });
300
- if (user) {
301
- const userAttr = {
302
- UserId: user.UserId,
303
- UserName: user.UserName,
304
- FullName: (user === null || user === void 0 ? void 0 : user.FullName) || null,
305
- IDNo: (user === null || user === void 0 ? void 0 : user.IdNo) || null,
306
- IDType: (user === null || user === void 0 ? void 0 : user.IdType) || null,
307
- ContactNo: (user === null || user === void 0 ? void 0 : user.ContactNo) || null,
308
- Email: user.Email,
309
- Password: user.Password,
310
- Status: user.Status,
311
- DefaultPasswordChangedYN: user.DefaultPasswordChangedYN,
312
- FirstLoginAt: user.FirstLoginAt,
313
- LastLoginAt: user.LastLoginAt,
314
- MFAEnabled: user.MFAEnabled,
315
- MFAConfig: user.MFAConfig,
316
- RecoveryEmail: user.RecoveryEmail,
317
- FailedLoginAttemptCount: user.FailedLoginAttemptCount,
318
- LastFailedLoginAt: user.LastFailedLoginAt,
319
- LastPasswordChangedAt: user.LastPasswordChangedAt,
320
- NeedToChangePasswordYN: user.NeedToChangePasswordYN,
321
- CreatedById: user.CreatedById,
322
- CreatedAt: user.CreatedAt,
323
- UpdatedById: user.UpdatedById,
324
- UpdatedAt: user.UpdatedAt,
325
- staffs: (user === null || user === void 0 ? void 0 : user.Staff) || null,
326
- };
327
- this.UserId = userAttr.UserId;
328
- this.FullName = userAttr.FullName;
329
- this.IDNo = userAttr.IDNo;
330
- this.Email = userAttr.Email;
331
- this.ContactNo = userAttr.ContactNo;
332
- this.Password = userAttr.Password;
333
- this.Status = userAttr.Status;
334
- this.DefaultPasswordChangedYN = userAttr.DefaultPasswordChangedYN;
335
- this.FirstLoginAt = userAttr.FirstLoginAt;
336
- this.LastLoginAt = userAttr.LastLoginAt;
337
- this.MFAEnabled = userAttr.MFAEnabled;
338
- this.MFAConfig = userAttr.MFAConfig;
339
- this.RecoveryEmail = userAttr.RecoveryEmail;
340
- this.FailedLoginAttemptCount = userAttr.FailedLoginAttemptCount;
341
- this.LastFailedLoginAt = userAttr.LastFailedLoginAt;
342
- this.LastPasswordChangedAt = userAttr.LastPasswordChangedAt;
343
- this.NeedToChangePasswordYN = userAttr.NeedToChangePasswordYN;
344
- this.CreatedById = userAttr.CreatedById;
345
- this.CreatedAt = userAttr.CreatedAt;
346
- this.UpdatedById = userAttr.UpdatedById;
347
- this.UpdatedAt = userAttr.UpdatedAt;
348
- this.staffs = userAttr.staffs;
349
- }
350
- else {
351
- throw new general_1.ClassError('User', 'UserErrMsg0X', 'Invalid Credentials');
352
- }
353
- }
354
- if (this.ObjectId && this.Email !== email) {
355
- throw new Error('Invalid credentials.');
356
- }
357
- const check2FA = yield User.check2FA(this, dbTransaction);
358
- try {
359
- const system = yield User._SystemRepository.findOne({
360
- where: {
361
- SystemCode: systemCode,
362
- Status: 'Active',
363
- },
364
- });
365
- if (!system) {
366
- throw new Error('Invalid credentials.');
367
- }
368
- const passwordHashService = new password_hash_service_1.PasswordHashService();
369
- const isPasswordValid = yield passwordHashService.verify(password, this.Password);
370
- if (!isPasswordValid) {
371
- throw new Error('Invalid credentials.');
372
- }
373
- yield this.checkSystemAccess(this.UserId, system.SystemCode, dbTransaction);
374
- if (this.Status === enum_1.UserStatus.LOCKED) {
375
- const isReleaseLock = User.shouldReleaseLock(this.LastFailedLoginAt);
376
- if (isReleaseLock) {
377
- yield User.releaseLock(this.UserId, dbTransaction);
378
- this.Status = enum_1.UserStatus.ACTIVE;
379
- }
380
- else {
381
- throw new Error('Invalid credentials.');
382
- }
383
- }
384
- }
385
- catch (error) {
386
- yield this.incrementFailedLoginAttemptCount(dbTransaction);
387
- }
388
- const system = yield User._SystemRepository.findOne({
389
- where: {
390
- SystemCode: systemCode,
391
- },
392
- });
393
- yield this.alertNewLogin(this.ObjectId, system.SystemCode, ipAddress);
394
- this.FailedLoginAttemptCount = 0;
395
- this.LastLoginAt = new Date();
396
- if (!this.FirstLoginAt) {
397
- this.FirstLoginAt = new Date();
398
- }
399
- yield User._Repository.update({
400
- FullName: this.FullName,
401
- UserName: this.UserName,
402
- IDNo: this.IDNo,
403
- Email: this.Email,
404
- ContactNo: this.ContactNo,
405
- Password: this.Password,
406
- Status: this.Status,
407
- DefaultPasswordChangedYN: this.DefaultPasswordChangedYN,
408
- FirstLoginAt: this.FirstLoginAt,
409
- LastLoginAt: this.LastLoginAt,
410
- MFAEnabled: this.MFAEnabled,
411
- MFAConfig: this.MFAConfig,
412
- RecoveryEmail: this.RecoveryEmail,
413
- FailedLoginAttemptCount: this.FailedLoginAttemptCount,
414
- LastFailedLoginAt: this.LastFailedLoginAt,
415
- LastPasswordChangedAt: this.LastPasswordChangedAt,
416
- NeedToChangePasswordYN: this.NeedToChangePasswordYN,
417
- }, {
418
- where: {
419
- UserId: this.UserId,
420
- },
421
- transaction: dbTransaction,
422
- });
423
- const userSession = yield this._SessionService.retrieveUserSession(this.ObjectId);
424
- const systemLogin = userSession.systemLogins.find((system) => system.code === systemCode);
425
- const sessionId = (0, crypto_1.randomUUID)();
426
- if (systemLogin) {
427
- systemLogin.sessionId = sessionId;
428
- userSession.systemLogins.map((system) => system.code === systemCode ? systemLogin : system);
429
- }
430
- else {
431
- const newLogin = {
432
- id: system.SystemCode,
433
- code: system.SystemCode,
434
- sessionId: sessionId,
435
- privileges: yield this.getPrivileges(system.SystemCode, dbTransaction),
436
- };
437
- userSession.systemLogins.push(newLogin);
438
- }
439
- this._SessionService.setUserSession(this.ObjectId, userSession);
440
- yield User._LoginHistoryRepository.create({
441
- UserId: this.UserId,
442
- SystemCode: system.SystemCode,
443
- OriginIp: ipAddress,
444
- CreatedAt: new Date(),
445
- LoginStatus: login_status_enum_1.LoginStatusEnum.SUCCESS,
446
- }, {
447
- transaction: dbTransaction,
448
- });
449
- const is2FAEnabledYN = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'is2FAEnabledYN');
450
- const loginUser = yield login_user_1.LoginUser.init(this.SessionService, this.UserId, dbTransaction);
451
- if (is2FAEnabledYN === 'Y') {
452
- loginUser.session.Id = `${this.UserId}:`;
453
- }
454
- else {
455
- loginUser.session.Id = `${this.UserId}:${sessionId}`;
456
- }
457
- return loginUser;
458
- }
459
- catch (error) {
460
- if (this.ObjectId) {
461
- yield User._LoginHistoryRepository.create({
462
- UserId: this.UserId,
463
- SystemCode: systemCode,
464
- OriginIp: ipAddress,
465
- LoginStatus: login_status_enum_1.LoginStatusEnum.FAILURE,
466
- CreatedAt: new Date(),
467
- }, {
468
- transaction: dbTransaction,
469
- });
470
- }
471
- throw error;
472
- }
473
- });
474
- }
475
- checkSystemAccess(userId, systemCode, dbTransaction) {
476
- return __awaiter(this, void 0, void 0, function* () {
477
- try {
478
- let isUserHaveAccess = false;
479
- const systemAccess = yield User._UserSystemAccessRepo.findOne({
480
- where: {
481
- UserId: userId,
482
- SystemCode: systemCode,
483
- Status: 'Active',
484
- },
485
- dbTransaction,
486
- });
487
- if (systemAccess) {
488
- isUserHaveAccess = true;
489
- }
490
- else {
491
- const userGroups = yield User._UserGroupRepo.findAll({
492
- where: {
493
- UserId: userId,
494
- InheritGroupAccessYN: 'Y',
495
- Status: 'Active',
496
- },
497
- include: [
498
- {
499
- model: group_entity_1.default,
500
- },
501
- ],
502
- dbTransaction,
503
- });
504
- for (const usergroup of userGroups) {
505
- const group = usergroup.Group;
506
- const groupSystemAccess = yield User.getInheritedSystemAccess(dbTransaction, group);
507
- for (const system of groupSystemAccess) {
508
- if (system.SystemCode === systemCode) {
509
- isUserHaveAccess = true;
510
- break;
511
- }
512
- }
513
- }
514
- }
515
- if (!isUserHaveAccess) {
516
- throw new Error("User don't have access to the system.");
517
- }
518
- }
519
- catch (error) {
520
- throw error;
521
- }
522
- });
523
- }
524
- checkPrivileges(systemCode, privilegeName) {
525
- return __awaiter(this, void 0, void 0, function* () {
526
- try {
527
- if (!this.ObjectId) {
528
- throw new Error('ObjectId(UserId) is not set');
529
- }
530
- const userSession = yield this._SessionService.retrieveUserSession(this.ObjectId);
531
- const systemLogin = userSession.systemLogins.find((system) => system.code === systemCode);
532
- if (!systemLogin) {
533
- return false;
534
- }
535
- const privileges = systemLogin.privileges;
536
- const hasPrivilege = privileges.includes(privilegeName);
537
- return hasPrivilege;
538
- }
539
- catch (error) {
540
- throw error;
541
- }
542
- });
543
- }
544
- alertNewLogin(userId, systemCode, ipAddress) {
545
- return __awaiter(this, void 0, void 0, function* () {
546
- try {
547
- const userLogins = yield User._LoginHistoryRepository.findAll({
548
- where: {
549
- UserId: userId,
550
- SystemCode: systemCode,
551
- },
552
- });
553
- const gotPreviousLogins = (userLogins === null || userLogins === void 0 ? void 0 : userLogins.length) !== 0;
554
- let ipFound = undefined;
555
- if (gotPreviousLogins) {
556
- ipFound = userLogins.find((item) => item.OriginIp === ipAddress);
557
- }
558
- }
559
- catch (error) {
560
- throw error;
561
- }
562
- });
563
- }
564
- getPrivileges(systemCode, dbTransaction) {
565
- return __awaiter(this, void 0, void 0, function* () {
566
- try {
567
- const system = yield User._SystemRepository.findOne({
568
- where: {
569
- SystemCode: systemCode,
570
- },
571
- transaction: dbTransaction,
572
- });
573
- if (!system) {
574
- throw new Error('Invalid system code.');
575
- }
576
- const userPrivileges = yield this.getUserPersonalPrivileges(systemCode, dbTransaction);
577
- const objectPrivileges = yield this.getObjectPrivileges(systemCode, dbTransaction);
578
- const userGroupOwnByUser = yield User._UserGroupRepo.findAll({
579
- where: {
580
- UserId: this.UserId,
581
- InheritGroupSystemAccessYN: 'Y',
582
- InheritGroupPrivilegeYN: 'Y',
583
- Status: 'Active',
584
- },
585
- include: [
586
- {
587
- model: group_entity_1.default,
588
- where: {
589
- Status: 'Active',
590
- },
591
- include: [
592
- {
593
- model: group_system_access_entity_1.default,
594
- where: {
595
- SystemCode: systemCode,
596
- },
597
- },
598
- ],
599
- },
600
- ],
601
- transaction: dbTransaction,
602
- });
603
- let groupsPrivileges = [];
604
- for (const userGroup of userGroupOwnByUser) {
605
- const gp = yield this.getInheritedPrivileges(userGroup.GroupCode, systemCode, dbTransaction);
606
- groupsPrivileges = [...groupsPrivileges, ...gp];
607
- }
608
- const privileges = [
609
- ...userPrivileges,
610
- ...objectPrivileges,
611
- ...groupsPrivileges,
612
- ];
613
- return privileges;
614
- }
615
- catch (error) {
616
- throw error;
617
- }
618
- });
619
- }
620
- getInheritedPrivileges(groupCode, systemCode, dbTransaction) {
621
- return __awaiter(this, void 0, void 0, function* () {
622
- try {
623
- const group = yield User._GroupRepo.findOne({
624
- where: {
625
- GroupCode: groupCode,
626
- Status: 'Active',
627
- },
628
- include: [
629
- {
630
- model: group_privilege_entity_1.default,
631
- where: {
632
- Status: 'Active',
633
- },
634
- include: [
635
- {
636
- model: system_privilege_entity_1.default,
637
- where: {
638
- SystemCode: systemCode,
639
- Status: 'Active',
640
- },
641
- },
642
- ],
643
- },
644
- ],
645
- transaction: dbTransaction,
646
- });
647
- const objectPrivileges = yield User._GroupObjectPrivilegeRepo.findAll({
648
- where: {
649
- GroupCode: groupCode,
650
- },
651
- include: {
652
- model: system_privilege_entity_1.default,
653
- where: {
654
- SystemCode: systemCode,
655
- Status: 'Active',
656
- },
657
- },
658
- transaction: dbTransaction,
659
- });
660
- const gp = (group === null || group === void 0 ? void 0 : group.GroupPrivileges) || [];
661
- const op = objectPrivileges || [];
662
- let privileges = [];
663
- const groupPrivileges = [];
664
- for (const groupPrivilege of gp) {
665
- groupPrivileges.push(groupPrivilege.Privilege.PrivilegeCode);
666
- }
667
- const ops = [];
668
- for (const objectPrivilege of op) {
669
- ops.push(objectPrivilege.Privilege.PrivilegeCode);
670
- }
671
- privileges = [...privileges, ...groupPrivileges, ...ops];
672
- if ((group === null || group === void 0 ? void 0 : group.ParentGroupCode) && (group === null || group === void 0 ? void 0 : group.InheritParentPrivilegeYN) === 'Y') {
673
- const parentGroupPrivileges = yield this.getInheritedPrivileges(group.ParentGroupCode, systemCode, dbTransaction);
674
- privileges = [...privileges, ...parentGroupPrivileges];
675
- }
676
- return privileges;
677
- }
678
- catch (error) {
679
- throw error;
680
- }
681
- });
682
- }
683
- getUserPersonalPrivileges(systemCode, dbTransaction) {
684
- return __awaiter(this, void 0, void 0, function* () {
685
- try {
686
- const userPrivileges = (yield User._UserPrivilegeRepo.findAll({
687
- where: {
688
- UserId: this.UserId,
689
- Status: 'Active',
690
- },
691
- include: {
692
- model: system_privilege_entity_1.default,
693
- where: {
694
- SystemCode: systemCode,
695
- Status: 'Active',
696
- },
697
- },
698
- transaction: dbTransaction,
699
- })) || [];
700
- const privileges = userPrivileges.map((u) => u.Privilege.PrivilegeCode);
701
- return privileges;
702
- }
703
- catch (error) {
704
- throw error;
705
- }
706
- });
707
- }
708
- getObjectPrivileges(systemCode, dbTransaction) {
709
- return __awaiter(this, void 0, void 0, function* () {
710
- try {
711
- const userObjectPrivileges = (yield User._UserObjectPrivilegeRepo.findAll({
712
- where: {
713
- UserId: this.UserId,
714
- },
715
- include: {
716
- model: system_privilege_entity_1.default,
717
- where: {
718
- SystemCode: systemCode,
719
- Status: 'Active',
720
- },
721
- },
722
- transaction: dbTransaction,
723
- })) || [];
724
- const privilegesCodes = userObjectPrivileges.map((u) => u.Privilege.PrivilegeCode);
725
- return privilegesCodes;
726
- }
727
- catch (error) {
728
- throw error;
729
- }
730
- });
731
- }
732
- static checkUserInfoDuplicated(dbTransaction, query) {
733
- return __awaiter(this, void 0, void 0, function* () {
734
- try {
735
- const { Email, UserName, IdType, IdNo, ContactNo } = query;
736
- const where = {
737
- [sequelize_1.Op.or]: {},
738
- };
739
- if (Email) {
740
- where[sequelize_1.Op.or]['Email'] = Email;
741
- }
742
- if (UserName) {
743
- where[sequelize_1.Op.or]['UserName'] = UserName;
744
- }
745
- if (IdType && IdNo) {
746
- where[sequelize_1.Op.and] = [{ IdType: IdType }, { IdNo: IdNo }];
747
- }
748
- if (ContactNo) {
749
- where[sequelize_1.Op.or]['ContactNo'] = ContactNo;
750
- }
751
- const user = yield User._Repository.findAll({
752
- where,
753
- transaction: dbTransaction,
754
- });
755
- if (user && user.length > 0) {
756
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'User info already exists');
757
- }
758
- }
759
- catch (error) {
760
- throw error;
761
- }
762
- });
763
- }
764
- static generateDefaultPassword() {
765
- try {
766
- const passwordPolicy = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'passwordPolicy');
767
- if (!passwordPolicy ||
768
- !passwordPolicy.maxLen ||
769
- !passwordPolicy.minLen ||
770
- !passwordPolicy.nonAcceptableChar ||
771
- !passwordPolicy.numOfCapitalLetters ||
772
- !passwordPolicy.numOfNumbers ||
773
- !passwordPolicy.numOfSpecialChars) {
774
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Missing password policy. Please set in config file.');
775
- }
776
- if (passwordPolicy.numOfCapitalLetters +
777
- passwordPolicy.numOfNumbers +
778
- passwordPolicy.numOfSpecialChars >
779
- passwordPolicy.maxLen) {
780
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Password policy is invalid. Please set in config file.');
781
- }
782
- const { maxLen, minLen, nonAcceptableChar, numOfCapitalLetters, numOfNumbers, numOfSpecialChars, } = passwordPolicy;
783
- const passwordLength = Math.floor(Math.random() * (maxLen - minLen + 1)) + minLen;
784
- const words = 'abcdefghijklmnopqrstuvwxyz';
785
- const capitalLetters = words.toUpperCase();
786
- const numbers = '0123456789';
787
- const specialChars = '!@#$%^&*()_+-={}[]|:;"<>,.?/~`';
788
- const nonAcceptableChars = nonAcceptableChar.split(',');
789
- const filteredWords = words
790
- .split('')
791
- .filter((word) => !nonAcceptableChars.includes(word));
792
- const filteredCapitalLetters = capitalLetters
793
- .split('')
794
- .filter((word) => !nonAcceptableChars.includes(word));
795
- const filteredNumbers = numbers
796
- .split('')
797
- .filter((word) => !nonAcceptableChars.includes(word));
798
- const filteredSpecialChars = specialChars
799
- .split('')
800
- .filter((word) => !nonAcceptableChars.includes(word));
801
- const generatedCapitalLetters = [];
802
- const generatedNumbers = [];
803
- const generatedSpecialChars = [];
804
- const generatedWords = [];
805
- for (let i = 0; i < numOfCapitalLetters; i++) {
806
- const randomIndex = Math.floor(Math.random() * filteredCapitalLetters.length);
807
- generatedCapitalLetters.push(filteredCapitalLetters[randomIndex]);
808
- }
809
- for (let i = 0; i < numOfNumbers; i++) {
810
- const randomIndex = Math.floor(Math.random() * filteredNumbers.length);
811
- generatedNumbers.push(filteredNumbers[randomIndex]);
812
- }
813
- for (let i = 0; i < numOfSpecialChars; i++) {
814
- const randomIndex = Math.floor(Math.random() * filteredSpecialChars.length);
815
- generatedSpecialChars.push(filteredSpecialChars[randomIndex]);
816
- }
817
- for (let i = 0; i <
818
- passwordLength -
819
- (numOfCapitalLetters + numOfNumbers + numOfSpecialChars); i++) {
820
- const randomIndex = Math.floor(Math.random() * filteredWords.length);
821
- generatedWords.push(filteredWords[randomIndex]);
822
- }
823
- let generatedPassword = '';
824
- const allGeneratedChars = generatedCapitalLetters.concat(generatedNumbers, generatedSpecialChars, generatedWords);
825
- allGeneratedChars.sort(() => Math.random() - 0.5);
826
- generatedPassword = allGeneratedChars.join('');
827
- return generatedPassword;
828
- }
829
- catch (error) {
830
- throw error;
831
- }
832
- }
833
- static setPassword(dbTransaction, user, password) {
834
- return __awaiter(this, void 0, void 0, function* () {
835
- try {
836
- const passwordPolicy = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'passwordPolicy');
837
- if (!passwordPolicy ||
838
- !passwordPolicy.maxLen ||
839
- !passwordPolicy.minLen ||
840
- !passwordPolicy.nonAcceptableChar ||
841
- !passwordPolicy.numOfCapitalLetters ||
842
- !passwordPolicy.numOfNumbers ||
843
- !passwordPolicy.numOfSpecialChars) {
844
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Missing password policy. Please set in config file.');
845
- }
846
- try {
847
- if (password.length < passwordPolicy.minLen) {
848
- throw Error('Password is too short');
849
- }
850
- if (password.length > passwordPolicy.maxLen) {
851
- throw Error('Password is too long');
852
- }
853
- const nonAcceptableChars = passwordPolicy.nonAcceptableChar.split(',');
854
- const nonAcceptableCharsFound = nonAcceptableChars.some((char) => password.includes(char));
855
- if (nonAcceptableCharsFound) {
856
- throw Error('Password contains unacceptable characters');
857
- }
858
- const capitalLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
859
- const numOfCapitalLetters = passwordPolicy.numOfCapitalLetters;
860
- const capitalLettersFound = capitalLetters
861
- .split('')
862
- .filter((char) => password.includes(char)).length;
863
- if (capitalLettersFound < numOfCapitalLetters) {
864
- throw Error('Password does not contain enough capital letters');
865
- }
866
- const numbers = '0123456789';
867
- const numOfNumbers = passwordPolicy.numOfNumbers;
868
- const numbersFound = numbers
869
- .split('')
870
- .filter((char) => password.includes(char)).length;
871
- if (numbersFound < numOfNumbers) {
872
- throw Error('Password does not contain enough numbers');
873
- }
874
- const specialChars = '!@#$%^&*()_+-={}[]|:;"<>,.?/~`';
875
- const numOfSpecialChars = passwordPolicy.numOfSpecialChars;
876
- const specialCharsFound = specialChars
877
- .split('')
878
- .filter((char) => password.includes(char)).length;
879
- if (specialCharsFound < numOfSpecialChars) {
880
- throw Error('Password does not contain enough special characters');
881
- }
882
- }
883
- catch (error) {
884
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', "Your password doesn't meet security requirements. Try using a mix of uppercase and lowercase letters, numbers, and symbols.");
885
- }
886
- const passwordHashService = new password_hash_service_1.PasswordHashService();
887
- const hashedPassword = yield passwordHashService.hashPassword(password);
888
- user._Password = hashedPassword;
889
- return user;
890
- }
891
- catch (error) {
892
- throw error;
893
- }
894
- });
895
- }
896
- generateAuthorizationToken() {
897
- return __awaiter(this, void 0, void 0, function* () {
898
- const plaintextToken = (0, crypto_1.randomBytes)(32).toString('hex');
899
- const hashedToken = (0, crypto_1.createHash)('sha256')
900
- .update(plaintextToken)
901
- .digest('hex');
902
- this._SessionService.setAuthorizationCode(hashedToken, this.ObjectId, 60 * 60 * 24);
903
- return { plaintextToken, hashedToken };
904
- });
905
- }
906
- validateAuthorizationToken(autorizationToken) {
907
- return __awaiter(this, void 0, void 0, function* () {
908
- try {
909
- const hashedSubmittedToken = (0, crypto_1.createHash)('sha256')
910
- .update(autorizationToken)
911
- .digest('hex');
912
- const userId = yield this._SessionService.retrieveAuthorizationCode(hashedSubmittedToken);
913
- if (!userId) {
914
- return null;
915
- }
916
- yield this._SessionService.deleteAuthorizationCode(hashedSubmittedToken);
917
- return userId;
918
- }
919
- catch (error) {
920
- throw error;
921
- }
922
- });
923
- }
924
- static resetPassword(sessionService, autorizationToken, password, dbTransaction) {
925
- return __awaiter(this, void 0, void 0, function* () {
926
- try {
927
- const hashedSubmittedToken = (0, crypto_1.createHash)('sha256')
928
- .update(autorizationToken)
929
- .digest('hex');
930
- const userId = yield sessionService.retrieveAuthorizationCode(hashedSubmittedToken);
931
- if (!userId) {
932
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid token', 'setupFirstPassword', 401);
933
- }
934
- yield sessionService.deleteAuthorizationCode(hashedSubmittedToken);
935
- console.log(`Token verified for user: ${userId}`);
936
- const user = yield User.init(sessionService, parseInt(userId), dbTransaction);
937
- yield User.setPassword(dbTransaction, user, password);
938
- yield User._Repository.update({
939
- Password: user._Password,
940
- DefaultPasswordChangedYN: yn_enum_1.YN.Yes,
941
- NeedToChangePasswordYN: yn_enum_1.YN.No,
942
- }, {
943
- where: {
944
- UserId: user.UserId,
945
- },
946
- transaction: dbTransaction,
947
- });
948
- }
949
- catch (error) {
950
- throw error;
951
- }
952
- });
953
- }
954
- static create(loginUser, dbTransaction, user) {
955
- return __awaiter(this, void 0, void 0, function* () {
956
- try {
957
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
958
- const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'User - Create');
959
- if (!isPrivileged) {
960
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'You do not have the privilege to create user');
961
- }
962
- if (!user.Email && !user.UserName) {
963
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Email and Username is required');
964
- }
965
- yield User.checkUserInfoDuplicated(dbTransaction, {
966
- Email: user.Email,
967
- UserName: user.UserName,
968
- IdType: user.IDType,
969
- IdNo: user.IDNo,
970
- ContactNo: user.ContactNo,
971
- });
972
- const defaultPassword = User.generateDefaultPassword();
973
- user = yield User.setPassword(dbTransaction, user, defaultPassword);
974
- const userInfo = {
975
- UserName: user.UserName,
976
- FullName: user.FullName,
977
- IDNo: user.IDNo,
978
- IDType: user.IDType,
979
- Email: user.Email,
980
- ContactNo: user.ContactNo,
981
- Password: user.Password,
982
- Status: enum_1.UserStatus.ACTIVE,
983
- FirstLoginAt: null,
984
- LastLoginAt: null,
985
- MFAEnabled: null,
986
- MFAConfig: null,
987
- RecoveryEmail: null,
988
- FailedLoginAttemptCount: 0,
989
- LastFailedLoginAt: null,
990
- LastPasswordChangedAt: null,
991
- DefaultPasswordChangedYN: yn_enum_1.YN.No,
992
- NeedToChangePasswordYN: yn_enum_1.YN.Yes,
993
- CreatedById: loginUser.UserId,
994
- CreatedAt: new Date(),
995
- UpdatedById: loginUser.UserId,
996
- UpdatedAt: new Date(),
997
- UserId: null,
998
- };
999
- const newUser = yield User._Repository.create({
1000
- Email: userInfo.Email,
1001
- UserName: userInfo.UserName,
1002
- FullName: userInfo.FullName,
1003
- IdNo: userInfo.IDNo,
1004
- IdType: userInfo.IDType,
1005
- Password: userInfo.Password,
1006
- Status: userInfo.Status,
1007
- DefaultPasswordChangedYN: userInfo.DefaultPasswordChangedYN,
1008
- FirstLoginAt: userInfo.FirstLoginAt,
1009
- LastLoginAt: userInfo.LastLoginAt,
1010
- MFAEnabled: userInfo.MFAEnabled,
1011
- MFAConfig: userInfo.MFAConfig,
1012
- RecoveryEmail: userInfo.RecoveryEmail,
1013
- FailedLoginAttemptCount: userInfo.FailedLoginAttemptCount,
1014
- LastFailedLoginAt: userInfo.LastFailedLoginAt,
1015
- LastPasswordChangedAt: userInfo.LastPasswordChangedAt,
1016
- NeedToChangePasswordYN: userInfo.NeedToChangePasswordYN,
1017
- CreatedById: userInfo.CreatedById,
1018
- CreatedAt: userInfo.CreatedAt,
1019
- UpdatedById: userInfo.UpdatedById,
1020
- UpdatedAt: userInfo.UpdatedAt,
1021
- }, {
1022
- transaction: dbTransaction,
1023
- });
1024
- userInfo.UserId = newUser.UserId;
1025
- const userToBeCreated = new User(loginUser.SessionService, dbTransaction, userInfo);
1026
- const activity = new activity_history_1.Activity();
1027
- activity.ActivityId = activity.createId();
1028
- activity.Action = activity_history_1.ActionEnum.CREATE;
1029
- activity.Description = 'Create User';
1030
- activity.EntityType = 'LoginUser';
1031
- activity.EntityId = newUser.UserId.toString();
1032
- activity.EntityValueBefore = JSON.stringify({});
1033
- activity.EntityValueAfter = JSON.stringify(newUser.get({ plain: true }));
1034
- yield activity.create(loginUser.ObjectId, dbTransaction);
1035
- return userToBeCreated;
1036
- }
1037
- catch (error) {
1038
- throw error;
1039
- }
1040
- });
1041
- }
1042
- incrementFailedLoginAttemptCount(dbTransaction) {
1043
- return __awaiter(this, void 0, void 0, function* () {
1044
- const maxFailedLoginAttempts = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'maxFailedLoginAttempts');
1045
- const autoReleaseYN = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'autoReleaseYN');
1046
- if (!maxFailedLoginAttempts || !autoReleaseYN) {
1047
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Missing maxFailedLoginAttempts and or autoReleaseYN. Please set in config file.');
1048
- }
1049
- const FailedLoginAttemptCount = this.FailedLoginAttemptCount + 1;
1050
- const LastFailedLoginAt = new Date();
1051
- if (FailedLoginAttemptCount > maxFailedLoginAttempts) {
1052
- this.Status = enum_1.UserStatus.LOCKED;
1053
- }
1054
- yield User._Repository.update({
1055
- FailedLoginAttemptCount: FailedLoginAttemptCount,
1056
- LastFailedLoginAt: LastFailedLoginAt,
1057
- Status: this.Status,
1058
- }, {
1059
- where: {
1060
- UserId: this.UserId,
1061
- },
1062
- transaction: dbTransaction,
1063
- });
1064
- if (this.Status === enum_1.UserStatus.LOCKED && autoReleaseYN === 'Y') {
1065
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Your account has been temporarily locked due to too many failed login attempts, please try again later.');
1066
- }
1067
- if (this.Status === enum_1.UserStatus.LOCKED && autoReleaseYN === 'N') {
1068
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Your account has been locked due to too many failed login attempts, please contact IT Support for instructions on how to unlock your account');
1069
- }
1070
- if (this.Status == enum_1.UserStatus.LOCKED) {
1071
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid credentials.');
1072
- }
1073
- });
1074
- }
1075
- static shouldReleaseLock(LastFailedLoginAt) {
1076
- const minuteToAutoRelease = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'minuteToAutoRelease');
1077
- const autoReleaseYN = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'autoReleaseYN');
1078
- if (!minuteToAutoRelease || !autoReleaseYN) {
1079
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Missing minuteToAutoRelease and or autoReleaseYN. Please set in config file.');
1080
- }
1081
- if (autoReleaseYN === 'Y') {
1082
- const lastFailedDate = new Date(LastFailedLoginAt);
1083
- const currentDate = new Date();
1084
- const timeDifferenceInMillis = currentDate.getTime() - lastFailedDate.getTime();
1085
- const timeDifferenceInMinutes = timeDifferenceInMillis / (1000 * 60);
1086
- if (timeDifferenceInMinutes > +minuteToAutoRelease) {
1087
- return true;
1088
- }
1089
- else {
1090
- return false;
1091
- }
1092
- }
1093
- else if (autoReleaseYN === 'N') {
1094
- return false;
1095
- }
1096
- }
1097
- static releaseLock(UserId, dbTransaction) {
1098
- this._Repository.update({
1099
- FailedLoginAttemptCount: 0,
1100
- Status: enum_1.UserStatus.ACTIVE,
1101
- }, {
1102
- where: {
1103
- UserId: UserId,
1104
- },
1105
- transaction: dbTransaction,
1106
- });
1107
- }
1108
- static getGroups(loginUser, dbTransaction) {
1109
- return __awaiter(this, void 0, void 0, function* () {
1110
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1111
- const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'UserGroup - List Own');
1112
- if (!isPrivileged) {
1113
- throw new Error('You do not have permission to list UserGroup.');
1114
- }
1115
- const userGroups = yield User._UserGroupRepo.findAll({
1116
- where: {
1117
- UserId: loginUser.ObjectId,
1118
- Status: 'Active',
1119
- },
1120
- include: [{ model: user_entity_1.default, as: 'User' }, { model: group_entity_1.default }],
1121
- transaction: dbTransaction,
1122
- });
1123
- return userGroups;
1124
- });
1125
- }
1126
- static getInheritedSystemAccess(dbTransaction, group) {
1127
- return __awaiter(this, void 0, void 0, function* () {
1128
- const dataSystemAccesses = yield User._GroupSystemAccessRepo.findAll({
1129
- where: {
1130
- GroupCode: group.GroupCode,
1131
- Status: 'Active',
1132
- },
1133
- include: [{ model: system_entity_1.default }],
1134
- transaction: dbTransaction,
1135
- });
1136
- let systemAccesses = dataSystemAccesses;
1137
- if (group.InheritParentPrivilegeYN === 'Y' && group.ParentGroupCode) {
1138
- const GroupCode = group.ParentGroupCode;
1139
- const parentGroup = yield User._GroupRepo.findByPk(GroupCode, dbTransaction);
1140
- const dataParentSystemAccesses = yield User.getInheritedSystemAccess(dbTransaction, parentGroup);
1141
- const parentSystemAccesses = dataParentSystemAccesses;
1142
- systemAccesses = systemAccesses.concat(parentSystemAccesses);
1143
- }
1144
- return systemAccesses;
1145
- });
1146
- }
1147
- static combineSystemAccess(loginUser, dbTransaction, groups) {
1148
- return __awaiter(this, void 0, void 0, function* () {
1149
- const userAccess = yield User._UserSystemAccessRepo.findAll({
1150
- where: {
1151
- UserId: loginUser.ObjectId,
1152
- Status: 'Active',
1153
- },
1154
- include: [{ model: system_entity_1.default }],
1155
- transaction: dbTransaction,
1156
- });
1157
- const groupAccessPromises = groups.map((e) => __awaiter(this, void 0, void 0, function* () {
1158
- if (e.InheritParentSystemAccessYN) {
1159
- return yield this.getInheritedSystemAccess(dbTransaction, e);
1160
- }
1161
- else {
1162
- return [];
1163
- }
1164
- }));
1165
- const groupAccess = (yield Promise.all(groupAccessPromises)).flat();
1166
- const allAccess = userAccess.concat(groupAccess);
1167
- const uniqueAccess = new Set(allAccess.filter((value, index, self) => {
1168
- return self.some((prev) => prev.SystemCode === value.SystemCode);
1169
- }));
1170
- return Array.from(uniqueAccess);
1171
- });
1172
- }
1173
- static getSystems(loginUser, dbTransaction) {
1174
- return __awaiter(this, void 0, void 0, function* () {
1175
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1176
- const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'System – List Own');
1177
- if (!isPrivileged) {
1178
- throw new Error('You do not have permission to list UserGroup.');
1179
- }
1180
- const groups = yield User.getGroups(loginUser, dbTransaction);
1181
- const systemAccess = yield User.combineSystemAccess(loginUser, dbTransaction, groups);
1182
- const output = [];
1183
- if (systemAccess) {
1184
- for (let i = 0; i < systemAccess.length; i++) {
1185
- const system = yield User._SystemRepository.findOne({
1186
- where: {
1187
- SystemCode: systemAccess[i].SystemCode,
1188
- Status: 'Active',
1189
- },
1190
- });
1191
- output.push({
1192
- UserSystemAccessId: systemAccess[i].UserSystemAccessId,
1193
- UserId: systemAccess[i].UserId,
1194
- SystemCode: systemAccess[i].SystemCode,
1195
- Status: systemAccess[i].Status,
1196
- CreatedById: systemAccess[i].CreatedById,
1197
- UpdatedById: systemAccess[i].UpdatedById,
1198
- CreatedAt: systemAccess[i].CreatedAt,
1199
- UpdatedAt: systemAccess[i].UpdatedAt,
1200
- System: system,
1201
- });
1202
- }
1203
- }
1204
- return output;
1205
- });
1206
- }
1207
- static check2FA(loginUser, dbTransaction) {
1208
- return __awaiter(this, void 0, void 0, function* () {
1209
- try {
1210
- const user = yield User._Repository.findOne({
1211
- where: {
1212
- UserId: loginUser.UserId,
1213
- },
1214
- transaction: dbTransaction,
1215
- });
1216
- if (user.MFAEnabled === 1) {
1217
- return true;
1218
- }
1219
- return false;
1220
- }
1221
- catch (error) {
1222
- throw error;
1223
- }
1224
- });
1225
- }
1226
- static setup2FA(userId, dbTransaction) {
1227
- var _a, _b, _c, _d;
1228
- return __awaiter(this, void 0, void 0, function* () {
1229
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1230
- const user = yield User._Repository.findOne({
1231
- where: {
1232
- UserId: userId,
1233
- },
1234
- });
1235
- if (!user) {
1236
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Credentials');
1237
- }
1238
- const secretCode = speakeasy.generateSecret({ name: 'Tomei SSO' });
1239
- let userMFAConfig = null;
1240
- if ((user === null || user === void 0 ? void 0 : user.MFAConfig) !== null && typeof (user === null || user === void 0 ? void 0 : user.MFAConfig) === 'string') {
1241
- try {
1242
- userMFAConfig = JSON.parse(user === null || user === void 0 ? void 0 : user.MFAConfig);
1243
- }
1244
- catch (error) {
1245
- console.error('Invalid JSON string on MFAConfig:', error);
1246
- }
1247
- }
1248
- const MFAConfig = {
1249
- totp: {
1250
- enabled: true,
1251
- secret: secretCode.base32,
1252
- issuer: systemCode,
1253
- },
1254
- sms: {
1255
- enabled: ((_a = userMFAConfig === null || userMFAConfig === void 0 ? void 0 : userMFAConfig.sms) === null || _a === void 0 ? void 0 : _a.enable) || false,
1256
- phoneNumber: ((_b = userMFAConfig === null || userMFAConfig === void 0 ? void 0 : userMFAConfig.sms) === null || _b === void 0 ? void 0 : _b.phoneNumber) || '',
1257
- },
1258
- email: {
1259
- enabled: ((_c = userMFAConfig === null || userMFAConfig === void 0 ? void 0 : userMFAConfig.email) === null || _c === void 0 ? void 0 : _c.enable) || false,
1260
- emailAddress: ((_d = userMFAConfig === null || userMFAConfig === void 0 ? void 0 : userMFAConfig.email) === null || _d === void 0 ? void 0 : _d.emailAddress) || '',
1261
- },
1262
- };
1263
- user.MFAEnabled = 0;
1264
- user.MFAConfig = JSON.stringify(MFAConfig);
1265
- yield User._Repository.update({
1266
- MFAEnabled: user.MFAEnabled,
1267
- MFAConfig: user.MFAConfig,
1268
- }, {
1269
- where: {
1270
- UserId: userId,
1271
- },
1272
- transaction: dbTransaction,
1273
- });
1274
- return secretCode.otpauth_url;
1275
- });
1276
- }
1277
- verify2FASetup(userId, mfaToken, systemCode, dbTransaction) {
1278
- return __awaiter(this, void 0, void 0, function* () {
1279
- const user = yield User._Repository.findOne({
1280
- where: {
1281
- UserId: userId,
1282
- },
1283
- });
1284
- if (!user) {
1285
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Credentials');
1286
- }
1287
- let userMFAConfig = null;
1288
- if ((user === null || user === void 0 ? void 0 : user.MFAConfig) !== null && typeof (user === null || user === void 0 ? void 0 : user.MFAConfig) === 'string') {
1289
- try {
1290
- userMFAConfig = JSON.parse(user === null || user === void 0 ? void 0 : user.MFAConfig);
1291
- }
1292
- catch (error) {
1293
- console.error('Invalid JSON string on MFAConfig:', error);
1294
- }
1295
- }
1296
- const isVerified = yield speakeasy.totp.verify({
1297
- secret: userMFAConfig.totp.secret,
1298
- encoding: 'base32',
1299
- token: mfaToken,
1300
- });
1301
- if (!isVerified) {
1302
- return false;
1303
- }
1304
- user.MFAEnabled = 1;
1305
- yield user.save({ transaction: dbTransaction });
1306
- const userSession = yield this._SessionService.retrieveUserSession(`${userId}`);
1307
- if (!systemCode) {
1308
- systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1309
- }
1310
- const systemLogin = userSession.systemLogins.find((e) => e.code === systemCode);
1311
- return `${userId}:${systemLogin.sessionId}`;
1312
- });
1313
- }
1314
- verify2FACode(userId, mfaToken, systemCode, dbTransaction) {
1315
- return __awaiter(this, void 0, void 0, function* () {
1316
- const user = yield User._Repository.findOne({
1317
- where: {
1318
- UserId: userId,
1319
- },
1320
- transaction: dbTransaction,
1321
- });
1322
- if (!user) {
1323
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Credentials');
1324
- }
1325
- let userMFAConfig = null;
1326
- if ((user === null || user === void 0 ? void 0 : user.MFAConfig) !== null && typeof (user === null || user === void 0 ? void 0 : user.MFAConfig) === 'string') {
1327
- try {
1328
- userMFAConfig = JSON.parse(user === null || user === void 0 ? void 0 : user.MFAConfig);
1329
- }
1330
- catch (error) {
1331
- console.error('Invalid JSON string on MFAConfig:', error);
1332
- }
1333
- }
1334
- const isVerified = yield speakeasy.totp.verify({
1335
- secret: userMFAConfig.totp.secret,
1336
- encoding: 'base32',
1337
- token: mfaToken,
1338
- });
1339
- if (!isVerified) {
1340
- return false;
1341
- }
1342
- const userSession = yield this._SessionService.retrieveUserSession(`${userId}`);
1343
- if (!systemCode) {
1344
- systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1345
- }
1346
- const systemLogin = userSession.systemLogins.find((e) => e.code === systemCode);
1347
- return `${userId}:${systemLogin.sessionId}`;
1348
- });
1349
- }
1350
- bypass2FA(systemCode, dbTransaction) {
1351
- return __awaiter(this, void 0, void 0, function* () {
1352
- try {
1353
- const user = yield User._Repository.findOne({
1354
- where: {
1355
- UserId: this.UserId,
1356
- },
1357
- transaction: dbTransaction,
1358
- });
1359
- if (user.MFAEnabled === 1) {
1360
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Cannot bypass 2FA as it is enabled');
1361
- }
1362
- const userSession = yield this._SessionService.retrieveUserSession(`${this.UserId}`);
1363
- if (!systemCode) {
1364
- systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1365
- }
1366
- const systemLogin = userSession.systemLogins.find((e) => e.code === systemCode);
1367
- return `${this.UserId}:${systemLogin.sessionId}`;
1368
- }
1369
- catch (error) {
1370
- throw error;
1371
- }
1372
- });
1373
- }
1374
- addUserGroup(GroupCode, loginUser, dbTransaction) {
1375
- return __awaiter(this, void 0, void 0, function* () {
1376
- const group = yield User._GroupRepo.findOne({
1377
- where: {
1378
- GroupCode,
1379
- },
1380
- transaction: dbTransaction,
1381
- });
1382
- if (!group) {
1383
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Group Code');
1384
- }
1385
- const entityValueAfter = {
1386
- UserId: this.UserId,
1387
- GroupCode: group.GroupCode,
1388
- CreatedAt: new Date(),
1389
- CreatedById: loginUser.UserId,
1390
- UpdatedAt: new Date(),
1391
- UpdatedById: loginUser.UserId,
1392
- };
1393
- yield User._UserGroupRepo.create(entityValueAfter, {
1394
- transaction: dbTransaction,
1395
- });
1396
- const activity = new activity_history_1.Activity();
1397
- activity.ActivityId = activity.createId();
1398
- activity.Action = activity_history_1.ActionEnum.CREATE;
1399
- activity.Description = 'Add User Group';
1400
- activity.EntityType = 'UserGroup';
1401
- activity.EntityId = group.GroupCode;
1402
- activity.EntityValueBefore = JSON.stringify({});
1403
- activity.EntityValueAfter = JSON.stringify(entityValueAfter);
1404
- yield activity.create(loginUser.ObjectId, dbTransaction);
1405
- });
1406
- }
1407
- update(data, loginUser, dbTransaction) {
1408
- return __awaiter(this, void 0, void 0, function* () {
1409
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1410
- const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'User - Update');
1411
- if (!isPrivileged) {
1412
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'You do not have the privilege to update user');
1413
- }
1414
- if (!this.UserId) {
1415
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'UserId is required');
1416
- }
1417
- if (data.Email !== this.Email) {
1418
- yield User.checkUserInfoDuplicated(dbTransaction, {
1419
- UserName: data.UserName,
1420
- });
1421
- }
1422
- if (data.UserName !== this.UserName) {
1423
- yield User.checkUserInfoDuplicated(dbTransaction, {
1424
- UserName: data.UserName,
1425
- });
1426
- }
1427
- if (data.BuildingCode) {
1428
- const building = yield group_entity_1.default.findOne({
1429
- where: {
1430
- Type: 'Building',
1431
- GroupCode: data.BuildingCode,
1432
- },
1433
- transaction: dbTransaction,
1434
- });
1435
- if (!building) {
1436
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Building Code');
1437
- }
1438
- const userBuilding = yield User._UserGroupRepo.findOne({
1439
- where: {
1440
- UserId: this.UserId,
1441
- },
1442
- include: [
1443
- {
1444
- model: group_entity_1.default,
1445
- where: {
1446
- Type: 'Building',
1447
- },
1448
- },
1449
- ],
1450
- transaction: dbTransaction,
1451
- });
1452
- if (userBuilding) {
1453
- yield User._UserGroupRepo.update({
1454
- GroupCode: data.BuildingCode,
1455
- UpdatedAt: new Date(),
1456
- UpdatedById: loginUser.UserId,
1457
- }, {
1458
- where: {
1459
- UserId: this.UserId,
1460
- GroupCode: userBuilding.GroupCode,
1461
- },
1462
- transaction: dbTransaction,
1463
- });
1464
- }
1465
- else {
1466
- yield User._UserGroupRepo.create({
1467
- UserId: this.UserId,
1468
- GroupCode: data.BuildingCode,
1469
- CreatedAt: new Date(),
1470
- CreatedById: loginUser.UserId,
1471
- UpdatedAt: new Date(),
1472
- UpdatedById: loginUser.UserId,
1473
- }, {
1474
- transaction: dbTransaction,
1475
- });
1476
- }
1477
- }
1478
- if (data.CompanyCode) {
1479
- const company = yield group_entity_1.default.findOne({
1480
- where: {
1481
- Type: 'Company',
1482
- GroupCode: data.CompanyCode,
1483
- },
1484
- transaction: dbTransaction,
1485
- });
1486
- if (!company) {
1487
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Company Code');
1488
- }
1489
- const userCompany = yield User._UserGroupRepo.findOne({
1490
- where: {
1491
- UserId: this.UserId,
1492
- },
1493
- include: [
1494
- {
1495
- model: group_entity_1.default,
1496
- where: {
1497
- Type: 'Company',
1498
- },
1499
- },
1500
- ],
1501
- transaction: dbTransaction,
1502
- });
1503
- if (userCompany) {
1504
- yield User._UserGroupRepo.update({
1505
- GroupCode: data.CompanyCode,
1506
- UpdatedAt: new Date(),
1507
- UpdatedById: loginUser.UserId,
1508
- }, {
1509
- where: {
1510
- UserId: this.UserId,
1511
- GroupCode: userCompany.GroupCode,
1512
- },
1513
- transaction: dbTransaction,
1514
- });
1515
- }
1516
- else {
1517
- yield User._UserGroupRepo.create({
1518
- UserId: this.UserId,
1519
- GroupCode: data.CompanyCode,
1520
- CreatedAt: new Date(),
1521
- CreatedById: loginUser.UserId,
1522
- UpdatedAt: new Date(),
1523
- UpdatedById: loginUser.UserId,
1524
- }, {
1525
- transaction: dbTransaction,
1526
- });
1527
- }
1528
- }
1529
- if (data.DepartmentCode) {
1530
- const department = yield group_entity_1.default.findOne({
1531
- where: {
1532
- Type: 'Department',
1533
- GroupCode: data.DepartmentCode,
1534
- },
1535
- transaction: dbTransaction,
1536
- });
1537
- if (!department) {
1538
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Department Code');
1539
- }
1540
- const userDepartment = yield User._UserGroupRepo.findOne({
1541
- where: {
1542
- UserId: this.UserId,
1543
- },
1544
- include: [
1545
- {
1546
- model: group_entity_1.default,
1547
- where: {
1548
- Type: 'Department',
1549
- },
1550
- },
1551
- ],
1552
- transaction: dbTransaction,
1553
- });
1554
- if (userDepartment) {
1555
- yield User._UserGroupRepo.update({
1556
- GroupCode: data.DepartmentCode,
1557
- UpdatedAt: new Date(),
1558
- UpdatedById: loginUser.UserId,
1559
- }, {
1560
- where: {
1561
- UserId: this.UserId,
1562
- GroupCode: userDepartment.GroupCode,
1563
- },
1564
- transaction: dbTransaction,
1565
- });
1566
- }
1567
- else {
1568
- yield User._UserGroupRepo.create({
1569
- UserId: this.UserId,
1570
- GroupCode: data.DepartmentCode,
1571
- CreatedAt: new Date(),
1572
- CreatedById: loginUser.UserId,
1573
- UpdatedAt: new Date(),
1574
- UpdatedById: loginUser.UserId,
1575
- }, {
1576
- transaction: dbTransaction,
1577
- });
1578
- }
1579
- }
1580
- const entityValueBefore = {
1581
- UserId: this.UserId,
1582
- UserName: this.UserName,
1583
- Email: this.Email,
1584
- Password: this.Password,
1585
- Status: this.Status,
1586
- DefaultPasswordChangedYN: this.DefaultPasswordChangedYN,
1587
- FirstLoginAt: this.FirstLoginAt,
1588
- LastLoginAt: this.LastLoginAt,
1589
- MFAEnabled: this.MFAEnabled,
1590
- MFAConfig: this.MFAConfig,
1591
- RecoveryEmail: this.RecoveryEmail,
1592
- FailedLoginAttemptCount: this.FailedLoginAttemptCount,
1593
- LastFailedLoginAt: this.LastFailedLoginAt,
1594
- LastPasswordChangedAt: this.LastPasswordChangedAt,
1595
- NeedToChangePasswordYN: this.NeedToChangePasswordYN,
1596
- CreatedById: this.CreatedById,
1597
- CreatedAt: this.CreatedAt,
1598
- UpdatedById: this.UpdatedById,
1599
- UpdatedAt: this.UpdatedAt,
1600
- };
1601
- this.UserName = data.UserName;
1602
- this.Email = data.Email;
1603
- this.Status = data.Status;
1604
- this.RecoveryEmail = data.RecoveryEmail;
1605
- this.UpdatedAt = new Date();
1606
- this.UpdatedById = loginUser.UserId;
1607
- yield User._Repository.update({
1608
- UserName: this.UserName,
1609
- Email: this.Email,
1610
- Status: this.Status,
1611
- RecoveryEmail: this.RecoveryEmail,
1612
- UpdatedById: this.UpdatedById,
1613
- UpdatedAt: this.UpdatedAt,
1614
- }, {
1615
- where: {
1616
- UserId: this.UserId,
1617
- },
1618
- transaction: dbTransaction,
1619
- });
1620
- const entityValueAfter = {
1621
- UserId: this.UserId,
1622
- UserName: this.UserName,
1623
- Email: this.Email,
1624
- Password: this.Password,
1625
- Status: this.Status,
1626
- DefaultPasswordChangedYN: this.DefaultPasswordChangedYN,
1627
- FirstLoginAt: this.FirstLoginAt,
1628
- LastLoginAt: this.LastLoginAt,
1629
- MFAEnabled: this.MFAEnabled,
1630
- MFAConfig: this.MFAConfig,
1631
- RecoveryEmail: this.RecoveryEmail,
1632
- FailedLoginAttemptCount: this.FailedLoginAttemptCount,
1633
- LastFailedLoginAt: this.LastFailedLoginAt,
1634
- LastPasswordChangedAt: this.LastPasswordChangedAt,
1635
- NeedToChangePasswordYN: this.NeedToChangePasswordYN,
1636
- CreatedById: this.CreatedById,
1637
- CreatedAt: this.CreatedAt,
1638
- UpdatedById: this.UpdatedById,
1639
- UpdatedAt: this.UpdatedAt,
1640
- };
1641
- const activity = new activity_history_1.Activity();
1642
- activity.ActivityId = activity.createId();
1643
- activity.Action = activity_history_1.ActionEnum.UPDATE;
1644
- activity.Description = 'Update User';
1645
- activity.EntityType = 'LoginUser';
1646
- activity.EntityId = this.UserId.toString();
1647
- activity.EntityValueBefore = JSON.stringify(entityValueBefore);
1648
- activity.EntityValueAfter = JSON.stringify(entityValueAfter);
1649
- yield activity.create(loginUser.ObjectId, dbTransaction);
1650
- return this;
1651
- });
1652
- }
1653
- static findById(loginUser, dbTransaction, UserId) {
1654
- return __awaiter(this, void 0, void 0, function* () {
1655
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1656
- const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'USER_VIEW');
1657
- if (!isPrivileged) {
1658
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'You do not have the privilege to find user');
1659
- }
1660
- const user = yield User._Repository.findOne({
1661
- where: {
1662
- UserId: UserId,
1663
- Status: 'Active',
1664
- },
1665
- transaction: dbTransaction,
1666
- });
1667
- const userAttr = {
1668
- UserId: user.UserId,
1669
- UserName: user.UserName,
1670
- FullName: (user === null || user === void 0 ? void 0 : user.FullName) || null,
1671
- IDNo: (user === null || user === void 0 ? void 0 : user.IdNo) || null,
1672
- IDType: (user === null || user === void 0 ? void 0 : user.IdType) || null,
1673
- ContactNo: (user === null || user === void 0 ? void 0 : user.ContactNo) || null,
1674
- Email: user.Email,
1675
- Password: user.Password,
1676
- Status: user.Status,
1677
- DefaultPasswordChangedYN: user.DefaultPasswordChangedYN,
1678
- FirstLoginAt: user.FirstLoginAt,
1679
- LastLoginAt: user.LastLoginAt,
1680
- MFAEnabled: user.MFAEnabled,
1681
- MFAConfig: user.MFAConfig,
1682
- RecoveryEmail: user.RecoveryEmail,
1683
- FailedLoginAttemptCount: user.FailedLoginAttemptCount,
1684
- LastFailedLoginAt: user.LastFailedLoginAt,
1685
- LastPasswordChangedAt: user.LastPasswordChangedAt,
1686
- NeedToChangePasswordYN: user.NeedToChangePasswordYN,
1687
- CreatedById: user.CreatedById,
1688
- CreatedAt: user.CreatedAt,
1689
- UpdatedById: user.UpdatedById,
1690
- UpdatedAt: user.UpdatedAt,
1691
- staffs: (user === null || user === void 0 ? void 0 : user.Staff) || null,
1692
- };
1693
- return new User(null, dbTransaction, userAttr);
1694
- });
1695
- }
1696
- static getFullName(dbTransaction, UserId) {
1697
- return __awaiter(this, void 0, void 0, function* () {
1698
- try {
1699
- const user = yield User._Repository.findOne({
1700
- where: {
1701
- UserId: UserId,
1702
- },
1703
- transaction: dbTransaction,
1704
- });
1705
- if (!user) {
1706
- throw new general_1.ClassError('User', 'UserErrMsg0X', 'No user found.');
1707
- }
1708
- if (user === null || user === void 0 ? void 0 : user.FullName) {
1709
- return user === null || user === void 0 ? void 0 : user.FullName;
1710
- }
1711
- else if (user === null || user === void 0 ? void 0 : user.UserName) {
1712
- return user === null || user === void 0 ? void 0 : user.UserName;
1713
- }
1714
- else {
1715
- return '';
1716
- }
1717
- }
1718
- catch (error) {
1719
- throw error;
1720
- }
1721
- });
1722
- }
1723
- static findByEmail(loginUser, dbTransaction, Email) {
1724
- return __awaiter(this, void 0, void 0, function* () {
1725
- try {
1726
- const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1727
- const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'USER_VIEW');
1728
- if (!isPrivileged) {
1729
- throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'You do not have the privilege to find user');
1730
- }
1731
- const user = yield User._Repository.findOne({
1732
- where: {
1733
- Email: Email,
1734
- },
1735
- include: [
1736
- {
1737
- model: staff_entity_1.default,
1738
- },
1739
- ],
1740
- transaction: dbTransaction,
1741
- });
1742
- if (!user) {
1743
- throw new general_1.ClassError('User', 'UserErrMsg0X', 'User not found.');
1744
- }
1745
- const userAttr = {
1746
- UserId: user.UserId,
1747
- UserName: user.UserName,
1748
- FullName: (user === null || user === void 0 ? void 0 : user.FullName) || null,
1749
- IDNo: (user === null || user === void 0 ? void 0 : user.IdNo) || null,
1750
- IDType: (user === null || user === void 0 ? void 0 : user.IdType) || null,
1751
- ContactNo: (user === null || user === void 0 ? void 0 : user.ContactNo) || null,
1752
- Email: user.Email,
1753
- Password: user.Password,
1754
- Status: user.Status,
1755
- DefaultPasswordChangedYN: user.DefaultPasswordChangedYN,
1756
- FirstLoginAt: user.FirstLoginAt,
1757
- LastLoginAt: user.LastLoginAt,
1758
- MFAEnabled: user.MFAEnabled,
1759
- MFAConfig: user.MFAConfig,
1760
- RecoveryEmail: user.RecoveryEmail,
1761
- FailedLoginAttemptCount: user.FailedLoginAttemptCount,
1762
- LastFailedLoginAt: user.LastFailedLoginAt,
1763
- LastPasswordChangedAt: user.LastPasswordChangedAt,
1764
- NeedToChangePasswordYN: user.NeedToChangePasswordYN,
1765
- CreatedById: user.CreatedById,
1766
- CreatedAt: user.CreatedAt,
1767
- UpdatedById: user.UpdatedById,
1768
- UpdatedAt: user.UpdatedAt,
1769
- staffs: user === null || user === void 0 ? void 0 : user.Staff,
1770
- };
1771
- const sessionService = yield session_service_1.SessionService.init(undefined);
1772
- const usr = new User(sessionService, undefined, userAttr);
1773
- return usr;
1774
- }
1775
- catch (error) {
1776
- throw error;
1777
- }
1778
- });
1779
- }
1780
- }
1781
- exports.User = User;
1782
- User._Repository = new user_repository_1.UserRepository();
1783
- User._LoginHistoryRepository = new login_history_repository_1.LoginHistoryRepository();
1784
- User._UserGroupRepo = new user_group_repository_1.UserGroupRepository();
1785
- User._UserPrivilegeRepo = new user_privilege_repository_1.UserPrivilegeRepository();
1786
- User._UserObjectPrivilegeRepo = new user_object_privilege_repository_1.UserObjectPrivilegeRepository();
1787
- User._GroupObjectPrivilegeRepo = new group_object_privilege_repository_1.GroupObjectPrivilegeRepository();
1788
- User._SystemRepository = new system_repository_1.SystemRepository();
1789
- User._UserSystemAccessRepo = new user_system_access_repository_1.UserSystemAccessRepository();
1790
- User._GroupSystemAccessRepo = new group_system_access_repository_1.GroupSystemAccessRepository();
1791
- User._GroupRepo = new group_repository_1.GroupRepository();
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.User = void 0;
13
+ const general_1 = require("@tomei/general");
14
+ const user_repository_1 = require("./user.repository");
15
+ const system_repository_1 = require("../system/system.repository");
16
+ const login_history_repository_1 = require("../login-history/login-history.repository");
17
+ const password_hash_service_1 = require("../password-hash/password-hash.service");
18
+ const user_group_repository_1 = require("../user-group/user-group.repository");
19
+ const staff_entity_1 = require("../../models/staff.entity");
20
+ const system_privilege_entity_1 = require("../../models/system-privilege.entity");
21
+ const yn_enum_1 = require("../../enum/yn.enum");
22
+ const enum_1 = require("../../enum");
23
+ const config_1 = require("@tomei/config");
24
+ const sequelize_1 = require("sequelize");
25
+ const activity_history_1 = require("@tomei/activity-history");
26
+ const user_entity_1 = require("../../models/user.entity");
27
+ const group_entity_1 = require("../../models/group.entity");
28
+ const group_system_access_repository_1 = require("../group-system-access/group-system-access.repository");
29
+ const group_repository_1 = require("../group/group.repository");
30
+ const system_entity_1 = require("../../models/system.entity");
31
+ const user_system_access_repository_1 = require("../user-system-access/user-system-access.repository");
32
+ const group_system_access_entity_1 = require("../../models/group-system-access.entity");
33
+ const user_privilege_repository_1 = require("../user-privilege/user-privilege.repository");
34
+ const user_object_privilege_repository_1 = require("../user-object-privilege/user-object-privilege.repository");
35
+ const group_privilege_entity_1 = require("../../models/group-privilege.entity");
36
+ const group_object_privilege_repository_1 = require("../group-object-privilege/group-object-privilege.repository");
37
+ const speakeasy = require("speakeasy");
38
+ const login_status_enum_1 = require("../../enum/login-status.enum");
39
+ const redis_service_1 = require("../../redis-client/redis.service");
40
+ const login_user_1 = require("./login-user");
41
+ const session_service_1 = require("../../session/session.service");
42
+ const crypto_1 = require("crypto");
43
+ class User extends general_1.UserBase {
44
+ get SessionService() {
45
+ return this._SessionService;
46
+ }
47
+ get UserId() {
48
+ return parseInt(this.ObjectId);
49
+ }
50
+ set UserId(value) {
51
+ this.ObjectId = value.toString();
52
+ }
53
+ get Password() {
54
+ return this._Password;
55
+ }
56
+ set Password(value) {
57
+ this._Password = value;
58
+ }
59
+ get Status() {
60
+ return this._Status;
61
+ }
62
+ set Status(value) {
63
+ this._Status = value;
64
+ }
65
+ get UserName() {
66
+ return this._UserName;
67
+ }
68
+ set UserName(value) {
69
+ this._UserName = value;
70
+ }
71
+ get DefaultPasswordChangedYN() {
72
+ return this._DefaultPasswordChangedYN;
73
+ }
74
+ set DefaultPasswordChangedYN(value) {
75
+ this._DefaultPasswordChangedYN = value;
76
+ }
77
+ get FirstLoginAt() {
78
+ return this._FirstLoginAt;
79
+ }
80
+ set FirstLoginAt(value) {
81
+ this._FirstLoginAt = value;
82
+ }
83
+ get LastLoginAt() {
84
+ return this._LastLoginAt;
85
+ }
86
+ set LastLoginAt(value) {
87
+ this._LastLoginAt = value;
88
+ }
89
+ get MFAEnabled() {
90
+ return this._MFAEnabled;
91
+ }
92
+ set MFAEnabled(value) {
93
+ this._MFAEnabled = value;
94
+ }
95
+ get MFAConfig() {
96
+ return this._MFAConfig;
97
+ }
98
+ set MFAConfig(value) {
99
+ this._MFAConfig = value;
100
+ }
101
+ get RecoveryEmail() {
102
+ return this._RecoveryEmail;
103
+ }
104
+ set RecoveryEmail(value) {
105
+ this._RecoveryEmail = value;
106
+ }
107
+ get FailedLoginAttemptCount() {
108
+ return this._FailedLoginAttemptCount;
109
+ }
110
+ set FailedLoginAttemptCount(value) {
111
+ this._FailedLoginAttemptCount = value;
112
+ }
113
+ get LastFailedLoginAt() {
114
+ return this._LastFailedLoginAt;
115
+ }
116
+ set LastFailedLoginAt(value) {
117
+ this._LastFailedLoginAt = value;
118
+ }
119
+ get LastPasswordChangedAt() {
120
+ return this._LastPasswordChangedAt;
121
+ }
122
+ set LastPasswordChangedAt(value) {
123
+ this._LastPasswordChangedAt = value;
124
+ }
125
+ get NeedToChangePasswordYN() {
126
+ return this._NeedToChangePasswordYN;
127
+ }
128
+ set NeedToChangePasswordYN(value) {
129
+ this._NeedToChangePasswordYN = value;
130
+ }
131
+ get CreatedById() {
132
+ return this._CreatedById;
133
+ }
134
+ set CreatedById(value) {
135
+ this._CreatedById = value;
136
+ }
137
+ get CreatedAt() {
138
+ return this._CreatedAt;
139
+ }
140
+ set CreatedAt(value) {
141
+ this._CreatedAt = value;
142
+ }
143
+ get UpdatedById() {
144
+ return this._UpdatedById;
145
+ }
146
+ set UpdatedById(value) {
147
+ this._UpdatedById = value;
148
+ }
149
+ get UpdatedAt() {
150
+ return this._UpdatedAt;
151
+ }
152
+ set UpdatedAt(value) {
153
+ this._UpdatedAt = value;
154
+ }
155
+ getDetails() {
156
+ return __awaiter(this, void 0, void 0, function* () {
157
+ return {
158
+ FullName: this.FullName,
159
+ UserName: this.UserName,
160
+ IDNo: this.IDNo,
161
+ IDType: this.IDType,
162
+ Email: this.Email,
163
+ ContactNo: this.ContactNo,
164
+ };
165
+ });
166
+ }
167
+ constructor(sessionService, dbTransaction, userInfo) {
168
+ super();
169
+ this.ObjectName = 'User';
170
+ this.TableName = 'sso_Users';
171
+ this.ObjectType = 'User';
172
+ this._SessionService = sessionService;
173
+ if (dbTransaction) {
174
+ this._dbTransaction = dbTransaction;
175
+ }
176
+ if (userInfo) {
177
+ this.UserId = userInfo.UserId;
178
+ this.UserName = userInfo.UserName;
179
+ this.FullName = userInfo.FullName;
180
+ this.IDNo = userInfo.IDNo;
181
+ this.IDType = userInfo.IDType;
182
+ this.Email = userInfo.Email;
183
+ this.ContactNo = userInfo.ContactNo;
184
+ this.Password = userInfo.Password;
185
+ this.staffs = userInfo.staffs;
186
+ this.Status = userInfo.Status;
187
+ this.DefaultPasswordChangedYN = userInfo.DefaultPasswordChangedYN;
188
+ this.FirstLoginAt = userInfo.FirstLoginAt;
189
+ this.LastLoginAt = userInfo.LastLoginAt;
190
+ this.MFAEnabled = userInfo.MFAEnabled;
191
+ this.MFAConfig = userInfo.MFAConfig;
192
+ this.RecoveryEmail = userInfo.RecoveryEmail;
193
+ this.FailedLoginAttemptCount = userInfo.FailedLoginAttemptCount;
194
+ this.LastFailedLoginAt = userInfo.LastFailedLoginAt;
195
+ this.LastPasswordChangedAt = userInfo.LastPasswordChangedAt;
196
+ this.NeedToChangePasswordYN = userInfo.NeedToChangePasswordYN;
197
+ this.CreatedById = userInfo.CreatedById;
198
+ this.CreatedAt = userInfo.CreatedAt;
199
+ this.UpdatedById = userInfo.UpdatedById;
200
+ this.UpdatedAt = userInfo.UpdatedAt;
201
+ }
202
+ }
203
+ static init(sessionService_1, userId_1) {
204
+ return __awaiter(this, arguments, void 0, function* (sessionService, userId, dbTransaction = null) {
205
+ User._RedisService = yield redis_service_1.RedisService.init();
206
+ if (userId) {
207
+ if (dbTransaction) {
208
+ User._Repository = new user_repository_1.UserRepository();
209
+ }
210
+ const user = yield User._Repository.findOne({
211
+ where: {
212
+ UserId: userId,
213
+ },
214
+ include: [
215
+ {
216
+ model: staff_entity_1.default,
217
+ },
218
+ ],
219
+ transaction: dbTransaction,
220
+ });
221
+ if (!user) {
222
+ throw new Error('Invalid credentials.');
223
+ }
224
+ if (user) {
225
+ const userAttr = {
226
+ UserId: user.UserId,
227
+ UserName: user.UserName,
228
+ FullName: (user === null || user === void 0 ? void 0 : user.FullName) || null,
229
+ IDNo: (user === null || user === void 0 ? void 0 : user.IdNo) || null,
230
+ IDType: (user === null || user === void 0 ? void 0 : user.IdType) || null,
231
+ ContactNo: (user === null || user === void 0 ? void 0 : user.ContactNo) || null,
232
+ Email: user.Email,
233
+ Password: user.Password,
234
+ Status: user.Status,
235
+ DefaultPasswordChangedYN: user.DefaultPasswordChangedYN,
236
+ FirstLoginAt: user.FirstLoginAt,
237
+ LastLoginAt: user.LastLoginAt,
238
+ MFAEnabled: user.MFAEnabled,
239
+ MFAConfig: user.MFAConfig,
240
+ RecoveryEmail: user.RecoveryEmail,
241
+ FailedLoginAttemptCount: user.FailedLoginAttemptCount,
242
+ LastFailedLoginAt: user.LastFailedLoginAt,
243
+ LastPasswordChangedAt: user.LastPasswordChangedAt,
244
+ NeedToChangePasswordYN: user.NeedToChangePasswordYN,
245
+ CreatedById: user.CreatedById,
246
+ CreatedAt: user.CreatedAt,
247
+ UpdatedById: user.UpdatedById,
248
+ UpdatedAt: user.UpdatedAt,
249
+ staffs: user === null || user === void 0 ? void 0 : user.Staff,
250
+ };
251
+ return new User(sessionService, dbTransaction, userAttr);
252
+ }
253
+ else {
254
+ throw new Error('User not found');
255
+ }
256
+ }
257
+ return new User(sessionService, dbTransaction);
258
+ });
259
+ }
260
+ setEmail(email, dbTransaction) {
261
+ return __awaiter(this, void 0, void 0, function* () {
262
+ try {
263
+ if (this.Email === email) {
264
+ return;
265
+ }
266
+ const user = yield User._Repository.findOne({
267
+ where: {
268
+ Email: email,
269
+ },
270
+ transaction: dbTransaction,
271
+ });
272
+ if (user) {
273
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Email already exists');
274
+ }
275
+ this.Email = email;
276
+ }
277
+ catch (error) {
278
+ throw error;
279
+ }
280
+ });
281
+ }
282
+ login(systemCode, email, password, ipAddress, dbTransaction) {
283
+ return __awaiter(this, void 0, void 0, function* () {
284
+ try {
285
+ if (!this.ObjectId) {
286
+ const user = yield User._Repository.findOne({
287
+ transaction: dbTransaction,
288
+ where: {
289
+ Email: email,
290
+ Status: {
291
+ [sequelize_1.Op.or]: [enum_1.UserStatus.ACTIVE, enum_1.UserStatus.LOCKED],
292
+ },
293
+ },
294
+ include: [
295
+ {
296
+ model: staff_entity_1.default,
297
+ },
298
+ ],
299
+ });
300
+ if (user) {
301
+ const userAttr = {
302
+ UserId: user.UserId,
303
+ UserName: user.UserName,
304
+ FullName: (user === null || user === void 0 ? void 0 : user.FullName) || null,
305
+ IDNo: (user === null || user === void 0 ? void 0 : user.IdNo) || null,
306
+ IDType: (user === null || user === void 0 ? void 0 : user.IdType) || null,
307
+ ContactNo: (user === null || user === void 0 ? void 0 : user.ContactNo) || null,
308
+ Email: user.Email,
309
+ Password: user.Password,
310
+ Status: user.Status,
311
+ DefaultPasswordChangedYN: user.DefaultPasswordChangedYN,
312
+ FirstLoginAt: user.FirstLoginAt,
313
+ LastLoginAt: user.LastLoginAt,
314
+ MFAEnabled: user.MFAEnabled,
315
+ MFAConfig: user.MFAConfig,
316
+ RecoveryEmail: user.RecoveryEmail,
317
+ FailedLoginAttemptCount: user.FailedLoginAttemptCount,
318
+ LastFailedLoginAt: user.LastFailedLoginAt,
319
+ LastPasswordChangedAt: user.LastPasswordChangedAt,
320
+ NeedToChangePasswordYN: user.NeedToChangePasswordYN,
321
+ CreatedById: user.CreatedById,
322
+ CreatedAt: user.CreatedAt,
323
+ UpdatedById: user.UpdatedById,
324
+ UpdatedAt: user.UpdatedAt,
325
+ staffs: (user === null || user === void 0 ? void 0 : user.Staff) || null,
326
+ };
327
+ this.UserId = userAttr.UserId;
328
+ this.FullName = userAttr.FullName;
329
+ this.IDNo = userAttr.IDNo;
330
+ this.Email = userAttr.Email;
331
+ this.ContactNo = userAttr.ContactNo;
332
+ this.Password = userAttr.Password;
333
+ this.Status = userAttr.Status;
334
+ this.DefaultPasswordChangedYN = userAttr.DefaultPasswordChangedYN;
335
+ this.FirstLoginAt = userAttr.FirstLoginAt;
336
+ this.LastLoginAt = userAttr.LastLoginAt;
337
+ this.MFAEnabled = userAttr.MFAEnabled;
338
+ this.MFAConfig = userAttr.MFAConfig;
339
+ this.RecoveryEmail = userAttr.RecoveryEmail;
340
+ this.FailedLoginAttemptCount = userAttr.FailedLoginAttemptCount;
341
+ this.LastFailedLoginAt = userAttr.LastFailedLoginAt;
342
+ this.LastPasswordChangedAt = userAttr.LastPasswordChangedAt;
343
+ this.NeedToChangePasswordYN = userAttr.NeedToChangePasswordYN;
344
+ this.CreatedById = userAttr.CreatedById;
345
+ this.CreatedAt = userAttr.CreatedAt;
346
+ this.UpdatedById = userAttr.UpdatedById;
347
+ this.UpdatedAt = userAttr.UpdatedAt;
348
+ this.staffs = userAttr.staffs;
349
+ }
350
+ else {
351
+ throw new general_1.ClassError('User', 'UserErrMsg0X', 'Invalid Credentials');
352
+ }
353
+ }
354
+ if (this.ObjectId && this.Email !== email) {
355
+ throw new Error('Invalid credentials.');
356
+ }
357
+ const check2FA = yield User.check2FA(this, dbTransaction);
358
+ try {
359
+ const system = yield User._SystemRepository.findOne({
360
+ where: {
361
+ SystemCode: systemCode,
362
+ Status: 'Active',
363
+ },
364
+ });
365
+ if (!system) {
366
+ throw new Error('Invalid credentials.');
367
+ }
368
+ const passwordHashService = new password_hash_service_1.PasswordHashService();
369
+ const isPasswordValid = yield passwordHashService.verify(password, this.Password);
370
+ if (!isPasswordValid) {
371
+ throw new Error('Invalid credentials.');
372
+ }
373
+ yield this.checkSystemAccess(this.UserId, system.SystemCode, dbTransaction);
374
+ if (this.Status === enum_1.UserStatus.LOCKED) {
375
+ const isReleaseLock = User.shouldReleaseLock(this.LastFailedLoginAt);
376
+ if (isReleaseLock) {
377
+ yield User.releaseLock(this.UserId, dbTransaction);
378
+ this.Status = enum_1.UserStatus.ACTIVE;
379
+ }
380
+ else {
381
+ throw new Error('Invalid credentials.');
382
+ }
383
+ }
384
+ }
385
+ catch (error) {
386
+ yield this.incrementFailedLoginAttemptCount(dbTransaction);
387
+ }
388
+ const system = yield User._SystemRepository.findOne({
389
+ where: {
390
+ SystemCode: systemCode,
391
+ },
392
+ });
393
+ yield this.alertNewLogin(this.ObjectId, system.SystemCode, ipAddress);
394
+ this.FailedLoginAttemptCount = 0;
395
+ this.LastLoginAt = new Date();
396
+ if (!this.FirstLoginAt) {
397
+ this.FirstLoginAt = new Date();
398
+ }
399
+ yield User._Repository.update({
400
+ FullName: this.FullName,
401
+ UserName: this.UserName,
402
+ IDNo: this.IDNo,
403
+ Email: this.Email,
404
+ ContactNo: this.ContactNo,
405
+ Password: this.Password,
406
+ Status: this.Status,
407
+ DefaultPasswordChangedYN: this.DefaultPasswordChangedYN,
408
+ FirstLoginAt: this.FirstLoginAt,
409
+ LastLoginAt: this.LastLoginAt,
410
+ MFAEnabled: this.MFAEnabled,
411
+ MFAConfig: this.MFAConfig,
412
+ RecoveryEmail: this.RecoveryEmail,
413
+ FailedLoginAttemptCount: this.FailedLoginAttemptCount,
414
+ LastFailedLoginAt: this.LastFailedLoginAt,
415
+ LastPasswordChangedAt: this.LastPasswordChangedAt,
416
+ NeedToChangePasswordYN: this.NeedToChangePasswordYN,
417
+ }, {
418
+ where: {
419
+ UserId: this.UserId,
420
+ },
421
+ transaction: dbTransaction,
422
+ });
423
+ const userSession = yield this._SessionService.retrieveUserSession(this.ObjectId);
424
+ const systemLogin = userSession.systemLogins.find((system) => system.code === systemCode);
425
+ const sessionId = (0, crypto_1.randomUUID)();
426
+ if (systemLogin) {
427
+ systemLogin.sessionId = sessionId;
428
+ userSession.systemLogins.map((system) => system.code === systemCode ? systemLogin : system);
429
+ }
430
+ else {
431
+ const newLogin = {
432
+ id: system.SystemCode,
433
+ code: system.SystemCode,
434
+ sessionId: sessionId,
435
+ privileges: yield this.getPrivileges(system.SystemCode, dbTransaction),
436
+ };
437
+ userSession.systemLogins.push(newLogin);
438
+ }
439
+ this._SessionService.setUserSession(this.ObjectId, userSession);
440
+ yield User._LoginHistoryRepository.create({
441
+ UserId: this.UserId,
442
+ SystemCode: system.SystemCode,
443
+ OriginIp: ipAddress,
444
+ CreatedAt: new Date(),
445
+ LoginStatus: login_status_enum_1.LoginStatusEnum.SUCCESS,
446
+ }, {
447
+ transaction: dbTransaction,
448
+ });
449
+ const is2FAEnabledYN = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'is2FAEnabledYN');
450
+ const loginUser = yield login_user_1.LoginUser.init(this.SessionService, this.UserId, dbTransaction);
451
+ if (is2FAEnabledYN === 'Y') {
452
+ loginUser.session.Id = `${this.UserId}:`;
453
+ }
454
+ else {
455
+ loginUser.session.Id = `${this.UserId}:${sessionId}`;
456
+ }
457
+ return loginUser;
458
+ }
459
+ catch (error) {
460
+ if (this.ObjectId) {
461
+ yield User._LoginHistoryRepository.create({
462
+ UserId: this.UserId,
463
+ SystemCode: systemCode,
464
+ OriginIp: ipAddress,
465
+ LoginStatus: login_status_enum_1.LoginStatusEnum.FAILURE,
466
+ CreatedAt: new Date(),
467
+ }, {
468
+ transaction: dbTransaction,
469
+ });
470
+ }
471
+ throw error;
472
+ }
473
+ });
474
+ }
475
+ checkSystemAccess(userId, systemCode, dbTransaction) {
476
+ return __awaiter(this, void 0, void 0, function* () {
477
+ try {
478
+ let isUserHaveAccess = false;
479
+ const systemAccess = yield User._UserSystemAccessRepo.findOne({
480
+ where: {
481
+ UserId: userId,
482
+ SystemCode: systemCode,
483
+ Status: 'Active',
484
+ },
485
+ dbTransaction,
486
+ });
487
+ if (systemAccess) {
488
+ isUserHaveAccess = true;
489
+ }
490
+ else {
491
+ const userGroups = yield User._UserGroupRepo.findAll({
492
+ where: {
493
+ UserId: userId,
494
+ InheritGroupAccessYN: 'Y',
495
+ Status: 'Active',
496
+ },
497
+ include: [
498
+ {
499
+ model: group_entity_1.default,
500
+ },
501
+ ],
502
+ dbTransaction,
503
+ });
504
+ for (const usergroup of userGroups) {
505
+ const group = usergroup.Group;
506
+ const groupSystemAccess = yield User.getInheritedSystemAccess(dbTransaction, group);
507
+ for (const system of groupSystemAccess) {
508
+ if (system.SystemCode === systemCode) {
509
+ isUserHaveAccess = true;
510
+ break;
511
+ }
512
+ }
513
+ }
514
+ }
515
+ if (!isUserHaveAccess) {
516
+ throw new Error("User don't have access to the system.");
517
+ }
518
+ }
519
+ catch (error) {
520
+ throw error;
521
+ }
522
+ });
523
+ }
524
+ checkPrivileges(systemCode, privilegeName) {
525
+ return __awaiter(this, void 0, void 0, function* () {
526
+ try {
527
+ if (!this.ObjectId) {
528
+ throw new Error('ObjectId(UserId) is not set');
529
+ }
530
+ const userSession = yield this._SessionService.retrieveUserSession(this.ObjectId);
531
+ const systemLogin = userSession.systemLogins.find((system) => system.code === systemCode);
532
+ if (!systemLogin) {
533
+ return false;
534
+ }
535
+ const privileges = systemLogin.privileges;
536
+ const hasPrivilege = privileges.includes(privilegeName);
537
+ return hasPrivilege;
538
+ }
539
+ catch (error) {
540
+ throw error;
541
+ }
542
+ });
543
+ }
544
+ alertNewLogin(userId, systemCode, ipAddress) {
545
+ return __awaiter(this, void 0, void 0, function* () {
546
+ try {
547
+ const userLogins = yield User._LoginHistoryRepository.findAll({
548
+ where: {
549
+ UserId: userId,
550
+ SystemCode: systemCode,
551
+ },
552
+ });
553
+ const gotPreviousLogins = (userLogins === null || userLogins === void 0 ? void 0 : userLogins.length) !== 0;
554
+ let ipFound = undefined;
555
+ if (gotPreviousLogins) {
556
+ ipFound = userLogins.find((item) => item.OriginIp === ipAddress);
557
+ }
558
+ }
559
+ catch (error) {
560
+ throw error;
561
+ }
562
+ });
563
+ }
564
+ getPrivileges(systemCode, dbTransaction) {
565
+ return __awaiter(this, void 0, void 0, function* () {
566
+ try {
567
+ const system = yield User._SystemRepository.findOne({
568
+ where: {
569
+ SystemCode: systemCode,
570
+ },
571
+ transaction: dbTransaction,
572
+ });
573
+ if (!system) {
574
+ throw new Error('Invalid system code.');
575
+ }
576
+ const userPrivileges = yield this.getUserPersonalPrivileges(systemCode, dbTransaction);
577
+ const objectPrivileges = yield this.getObjectPrivileges(systemCode, dbTransaction);
578
+ const userGroupOwnByUser = yield User._UserGroupRepo.findAll({
579
+ where: {
580
+ UserId: this.UserId,
581
+ InheritGroupSystemAccessYN: 'Y',
582
+ InheritGroupPrivilegeYN: 'Y',
583
+ Status: 'Active',
584
+ },
585
+ include: [
586
+ {
587
+ model: group_entity_1.default,
588
+ where: {
589
+ Status: 'Active',
590
+ },
591
+ include: [
592
+ {
593
+ model: group_system_access_entity_1.default,
594
+ where: {
595
+ SystemCode: systemCode,
596
+ },
597
+ },
598
+ ],
599
+ },
600
+ ],
601
+ transaction: dbTransaction,
602
+ });
603
+ let groupsPrivileges = [];
604
+ for (const userGroup of userGroupOwnByUser) {
605
+ const gp = yield this.getInheritedPrivileges(userGroup.GroupCode, systemCode, dbTransaction);
606
+ groupsPrivileges = [...groupsPrivileges, ...gp];
607
+ }
608
+ const privileges = [
609
+ ...userPrivileges,
610
+ ...objectPrivileges,
611
+ ...groupsPrivileges,
612
+ ];
613
+ return privileges;
614
+ }
615
+ catch (error) {
616
+ throw error;
617
+ }
618
+ });
619
+ }
620
+ getInheritedPrivileges(groupCode, systemCode, dbTransaction) {
621
+ return __awaiter(this, void 0, void 0, function* () {
622
+ try {
623
+ const group = yield User._GroupRepo.findOne({
624
+ where: {
625
+ GroupCode: groupCode,
626
+ Status: 'Active',
627
+ },
628
+ include: [
629
+ {
630
+ model: group_privilege_entity_1.default,
631
+ where: {
632
+ Status: 'Active',
633
+ },
634
+ include: [
635
+ {
636
+ model: system_privilege_entity_1.default,
637
+ where: {
638
+ SystemCode: systemCode,
639
+ Status: 'Active',
640
+ },
641
+ },
642
+ ],
643
+ },
644
+ ],
645
+ transaction: dbTransaction,
646
+ });
647
+ const objectPrivileges = yield User._GroupObjectPrivilegeRepo.findAll({
648
+ where: {
649
+ GroupCode: groupCode,
650
+ },
651
+ include: {
652
+ model: system_privilege_entity_1.default,
653
+ where: {
654
+ SystemCode: systemCode,
655
+ Status: 'Active',
656
+ },
657
+ },
658
+ transaction: dbTransaction,
659
+ });
660
+ const gp = (group === null || group === void 0 ? void 0 : group.GroupPrivileges) || [];
661
+ const op = objectPrivileges || [];
662
+ let privileges = [];
663
+ const groupPrivileges = [];
664
+ for (const groupPrivilege of gp) {
665
+ groupPrivileges.push(groupPrivilege.Privilege.PrivilegeCode);
666
+ }
667
+ const ops = [];
668
+ for (const objectPrivilege of op) {
669
+ ops.push(objectPrivilege.Privilege.PrivilegeCode);
670
+ }
671
+ privileges = [...privileges, ...groupPrivileges, ...ops];
672
+ if ((group === null || group === void 0 ? void 0 : group.ParentGroupCode) && (group === null || group === void 0 ? void 0 : group.InheritParentPrivilegeYN) === 'Y') {
673
+ const parentGroupPrivileges = yield this.getInheritedPrivileges(group.ParentGroupCode, systemCode, dbTransaction);
674
+ privileges = [...privileges, ...parentGroupPrivileges];
675
+ }
676
+ return privileges;
677
+ }
678
+ catch (error) {
679
+ throw error;
680
+ }
681
+ });
682
+ }
683
+ getUserPersonalPrivileges(systemCode, dbTransaction) {
684
+ return __awaiter(this, void 0, void 0, function* () {
685
+ try {
686
+ const userPrivileges = (yield User._UserPrivilegeRepo.findAll({
687
+ where: {
688
+ UserId: this.UserId,
689
+ Status: 'Active',
690
+ },
691
+ include: {
692
+ model: system_privilege_entity_1.default,
693
+ where: {
694
+ SystemCode: systemCode,
695
+ Status: 'Active',
696
+ },
697
+ },
698
+ transaction: dbTransaction,
699
+ })) || [];
700
+ const privileges = userPrivileges.map((u) => u.Privilege.PrivilegeCode);
701
+ return privileges;
702
+ }
703
+ catch (error) {
704
+ throw error;
705
+ }
706
+ });
707
+ }
708
+ getObjectPrivileges(systemCode, dbTransaction) {
709
+ return __awaiter(this, void 0, void 0, function* () {
710
+ try {
711
+ const userObjectPrivileges = (yield User._UserObjectPrivilegeRepo.findAll({
712
+ where: {
713
+ UserId: this.UserId,
714
+ },
715
+ include: {
716
+ model: system_privilege_entity_1.default,
717
+ where: {
718
+ SystemCode: systemCode,
719
+ Status: 'Active',
720
+ },
721
+ },
722
+ transaction: dbTransaction,
723
+ })) || [];
724
+ const privilegesCodes = userObjectPrivileges.map((u) => u.Privilege.PrivilegeCode);
725
+ return privilegesCodes;
726
+ }
727
+ catch (error) {
728
+ throw error;
729
+ }
730
+ });
731
+ }
732
+ static checkUserInfoDuplicated(dbTransaction, query) {
733
+ return __awaiter(this, void 0, void 0, function* () {
734
+ try {
735
+ const { Email, UserName, IdType, IdNo, ContactNo } = query;
736
+ const where = {
737
+ [sequelize_1.Op.or]: {},
738
+ };
739
+ if (Email) {
740
+ where[sequelize_1.Op.or]['Email'] = Email;
741
+ }
742
+ if (UserName) {
743
+ where[sequelize_1.Op.or]['UserName'] = UserName;
744
+ }
745
+ if (IdType && IdNo) {
746
+ where[sequelize_1.Op.and] = [{ IdType: IdType }, { IdNo: IdNo }];
747
+ }
748
+ if (ContactNo) {
749
+ where[sequelize_1.Op.or]['ContactNo'] = ContactNo;
750
+ }
751
+ const user = yield User._Repository.findAll({
752
+ where,
753
+ transaction: dbTransaction,
754
+ });
755
+ if (user && user.length > 0) {
756
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'User info already exists');
757
+ }
758
+ }
759
+ catch (error) {
760
+ throw error;
761
+ }
762
+ });
763
+ }
764
+ static generateDefaultPassword() {
765
+ try {
766
+ const passwordPolicy = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'passwordPolicy');
767
+ if (!passwordPolicy ||
768
+ !passwordPolicy.maxLen ||
769
+ !passwordPolicy.minLen ||
770
+ !passwordPolicy.nonAcceptableChar ||
771
+ !passwordPolicy.numOfCapitalLetters ||
772
+ !passwordPolicy.numOfNumbers ||
773
+ !passwordPolicy.numOfSpecialChars) {
774
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Missing password policy. Please set in config file.');
775
+ }
776
+ if (passwordPolicy.numOfCapitalLetters +
777
+ passwordPolicy.numOfNumbers +
778
+ passwordPolicy.numOfSpecialChars >
779
+ passwordPolicy.maxLen) {
780
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Password policy is invalid. Please set in config file.');
781
+ }
782
+ const { maxLen, minLen, nonAcceptableChar, numOfCapitalLetters, numOfNumbers, numOfSpecialChars, } = passwordPolicy;
783
+ const passwordLength = Math.floor(Math.random() * (maxLen - minLen + 1)) + minLen;
784
+ const words = 'abcdefghijklmnopqrstuvwxyz';
785
+ const capitalLetters = words.toUpperCase();
786
+ const numbers = '0123456789';
787
+ const specialChars = '!@#$%^&*()_+-={}[]|:;"<>,.?/~`';
788
+ const nonAcceptableChars = nonAcceptableChar.split(',');
789
+ const filteredWords = words
790
+ .split('')
791
+ .filter((word) => !nonAcceptableChars.includes(word));
792
+ const filteredCapitalLetters = capitalLetters
793
+ .split('')
794
+ .filter((word) => !nonAcceptableChars.includes(word));
795
+ const filteredNumbers = numbers
796
+ .split('')
797
+ .filter((word) => !nonAcceptableChars.includes(word));
798
+ const filteredSpecialChars = specialChars
799
+ .split('')
800
+ .filter((word) => !nonAcceptableChars.includes(word));
801
+ const generatedCapitalLetters = [];
802
+ const generatedNumbers = [];
803
+ const generatedSpecialChars = [];
804
+ const generatedWords = [];
805
+ for (let i = 0; i < numOfCapitalLetters; i++) {
806
+ const randomIndex = Math.floor(Math.random() * filteredCapitalLetters.length);
807
+ generatedCapitalLetters.push(filteredCapitalLetters[randomIndex]);
808
+ }
809
+ for (let i = 0; i < numOfNumbers; i++) {
810
+ const randomIndex = Math.floor(Math.random() * filteredNumbers.length);
811
+ generatedNumbers.push(filteredNumbers[randomIndex]);
812
+ }
813
+ for (let i = 0; i < numOfSpecialChars; i++) {
814
+ const randomIndex = Math.floor(Math.random() * filteredSpecialChars.length);
815
+ generatedSpecialChars.push(filteredSpecialChars[randomIndex]);
816
+ }
817
+ for (let i = 0; i <
818
+ passwordLength -
819
+ (numOfCapitalLetters + numOfNumbers + numOfSpecialChars); i++) {
820
+ const randomIndex = Math.floor(Math.random() * filteredWords.length);
821
+ generatedWords.push(filteredWords[randomIndex]);
822
+ }
823
+ let generatedPassword = '';
824
+ const allGeneratedChars = generatedCapitalLetters.concat(generatedNumbers, generatedSpecialChars, generatedWords);
825
+ allGeneratedChars.sort(() => Math.random() - 0.5);
826
+ generatedPassword = allGeneratedChars.join('');
827
+ return generatedPassword;
828
+ }
829
+ catch (error) {
830
+ throw error;
831
+ }
832
+ }
833
+ static setPassword(dbTransaction, user, password) {
834
+ return __awaiter(this, void 0, void 0, function* () {
835
+ try {
836
+ const passwordPolicy = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'passwordPolicy');
837
+ if (!passwordPolicy ||
838
+ !passwordPolicy.maxLen ||
839
+ !passwordPolicy.minLen ||
840
+ !passwordPolicy.nonAcceptableChar ||
841
+ !passwordPolicy.numOfCapitalLetters ||
842
+ !passwordPolicy.numOfNumbers ||
843
+ !passwordPolicy.numOfSpecialChars) {
844
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Missing password policy. Please set in config file.');
845
+ }
846
+ try {
847
+ if (password.length < passwordPolicy.minLen) {
848
+ throw Error('Password is too short');
849
+ }
850
+ if (password.length > passwordPolicy.maxLen) {
851
+ throw Error('Password is too long');
852
+ }
853
+ const nonAcceptableChars = passwordPolicy.nonAcceptableChar.split(',');
854
+ const nonAcceptableCharsFound = nonAcceptableChars.some((char) => password.includes(char));
855
+ if (nonAcceptableCharsFound) {
856
+ throw Error('Password contains unacceptable characters');
857
+ }
858
+ const capitalLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
859
+ const numOfCapitalLetters = passwordPolicy.numOfCapitalLetters;
860
+ const capitalLettersFound = capitalLetters
861
+ .split('')
862
+ .filter((char) => password.includes(char)).length;
863
+ if (capitalLettersFound < numOfCapitalLetters) {
864
+ throw Error('Password does not contain enough capital letters');
865
+ }
866
+ const numbers = '0123456789';
867
+ const numOfNumbers = passwordPolicy.numOfNumbers;
868
+ const numbersFound = numbers
869
+ .split('')
870
+ .filter((char) => password.includes(char)).length;
871
+ if (numbersFound < numOfNumbers) {
872
+ throw Error('Password does not contain enough numbers');
873
+ }
874
+ const specialChars = '!@#$%^&*()_+-={}[]|:;"<>,.?/~`';
875
+ const numOfSpecialChars = passwordPolicy.numOfSpecialChars;
876
+ const specialCharsFound = specialChars
877
+ .split('')
878
+ .filter((char) => password.includes(char)).length;
879
+ if (specialCharsFound < numOfSpecialChars) {
880
+ throw Error('Password does not contain enough special characters');
881
+ }
882
+ }
883
+ catch (error) {
884
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', "Your password doesn't meet security requirements. Try using a mix of uppercase and lowercase letters, numbers, and symbols.");
885
+ }
886
+ const passwordHashService = new password_hash_service_1.PasswordHashService();
887
+ const hashedPassword = yield passwordHashService.hashPassword(password);
888
+ user._Password = hashedPassword;
889
+ return user;
890
+ }
891
+ catch (error) {
892
+ throw error;
893
+ }
894
+ });
895
+ }
896
+ generateAuthorizationToken() {
897
+ return __awaiter(this, void 0, void 0, function* () {
898
+ const plaintextToken = (0, crypto_1.randomBytes)(32).toString('hex');
899
+ const hashedToken = (0, crypto_1.createHash)('sha256')
900
+ .update(plaintextToken)
901
+ .digest('hex');
902
+ this._SessionService.setAuthorizationCode(hashedToken, this.ObjectId, 60 * 60 * 24);
903
+ return { plaintextToken, hashedToken };
904
+ });
905
+ }
906
+ validateAuthorizationToken(autorizationToken) {
907
+ return __awaiter(this, void 0, void 0, function* () {
908
+ try {
909
+ const hashedSubmittedToken = (0, crypto_1.createHash)('sha256')
910
+ .update(autorizationToken)
911
+ .digest('hex');
912
+ const userId = yield this._SessionService.retrieveAuthorizationCode(hashedSubmittedToken);
913
+ if (!userId) {
914
+ return null;
915
+ }
916
+ yield this._SessionService.deleteAuthorizationCode(hashedSubmittedToken);
917
+ return userId;
918
+ }
919
+ catch (error) {
920
+ throw error;
921
+ }
922
+ });
923
+ }
924
+ static resetPassword(sessionService, autorizationToken, password, dbTransaction) {
925
+ return __awaiter(this, void 0, void 0, function* () {
926
+ try {
927
+ const hashedSubmittedToken = (0, crypto_1.createHash)('sha256')
928
+ .update(autorizationToken)
929
+ .digest('hex');
930
+ const userId = yield sessionService.retrieveAuthorizationCode(hashedSubmittedToken);
931
+ if (!userId) {
932
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid token', 'setupFirstPassword', 401);
933
+ }
934
+ yield sessionService.deleteAuthorizationCode(hashedSubmittedToken);
935
+ console.log(`Token verified for user: ${userId}`);
936
+ const user = yield User.init(sessionService, parseInt(userId), dbTransaction);
937
+ yield User.setPassword(dbTransaction, user, password);
938
+ yield User._Repository.update({
939
+ Password: user._Password,
940
+ DefaultPasswordChangedYN: yn_enum_1.YN.Yes,
941
+ NeedToChangePasswordYN: yn_enum_1.YN.No,
942
+ }, {
943
+ where: {
944
+ UserId: user.UserId,
945
+ },
946
+ transaction: dbTransaction,
947
+ });
948
+ }
949
+ catch (error) {
950
+ throw error;
951
+ }
952
+ });
953
+ }
954
+ static create(loginUser, dbTransaction, user) {
955
+ return __awaiter(this, void 0, void 0, function* () {
956
+ try {
957
+ const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
958
+ const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'User - Create');
959
+ if (!isPrivileged) {
960
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'You do not have the privilege to create user');
961
+ }
962
+ if (!user.Email && !user.UserName) {
963
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Email and Username is required');
964
+ }
965
+ yield User.checkUserInfoDuplicated(dbTransaction, {
966
+ Email: user.Email,
967
+ UserName: user.UserName,
968
+ IdType: user.IDType,
969
+ IdNo: user.IDNo,
970
+ ContactNo: user.ContactNo,
971
+ });
972
+ const defaultPassword = User.generateDefaultPassword();
973
+ user = yield User.setPassword(dbTransaction, user, defaultPassword);
974
+ const userInfo = {
975
+ UserName: user.UserName,
976
+ FullName: user.FullName,
977
+ IDNo: user.IDNo,
978
+ IDType: user.IDType,
979
+ Email: user.Email,
980
+ ContactNo: user.ContactNo,
981
+ Password: user.Password,
982
+ Status: enum_1.UserStatus.ACTIVE,
983
+ FirstLoginAt: null,
984
+ LastLoginAt: null,
985
+ MFAEnabled: null,
986
+ MFAConfig: null,
987
+ RecoveryEmail: null,
988
+ FailedLoginAttemptCount: 0,
989
+ LastFailedLoginAt: null,
990
+ LastPasswordChangedAt: null,
991
+ DefaultPasswordChangedYN: yn_enum_1.YN.No,
992
+ NeedToChangePasswordYN: yn_enum_1.YN.Yes,
993
+ CreatedById: loginUser.UserId,
994
+ CreatedAt: new Date(),
995
+ UpdatedById: loginUser.UserId,
996
+ UpdatedAt: new Date(),
997
+ UserId: null,
998
+ };
999
+ const newUser = yield User._Repository.create({
1000
+ Email: userInfo.Email,
1001
+ UserName: userInfo.UserName,
1002
+ FullName: userInfo.FullName,
1003
+ IdNo: userInfo.IDNo,
1004
+ IdType: userInfo.IDType,
1005
+ Password: userInfo.Password,
1006
+ Status: userInfo.Status,
1007
+ DefaultPasswordChangedYN: userInfo.DefaultPasswordChangedYN,
1008
+ FirstLoginAt: userInfo.FirstLoginAt,
1009
+ LastLoginAt: userInfo.LastLoginAt,
1010
+ MFAEnabled: userInfo.MFAEnabled,
1011
+ MFAConfig: userInfo.MFAConfig,
1012
+ RecoveryEmail: userInfo.RecoveryEmail,
1013
+ FailedLoginAttemptCount: userInfo.FailedLoginAttemptCount,
1014
+ LastFailedLoginAt: userInfo.LastFailedLoginAt,
1015
+ LastPasswordChangedAt: userInfo.LastPasswordChangedAt,
1016
+ NeedToChangePasswordYN: userInfo.NeedToChangePasswordYN,
1017
+ CreatedById: userInfo.CreatedById,
1018
+ CreatedAt: userInfo.CreatedAt,
1019
+ UpdatedById: userInfo.UpdatedById,
1020
+ UpdatedAt: userInfo.UpdatedAt,
1021
+ }, {
1022
+ transaction: dbTransaction,
1023
+ });
1024
+ userInfo.UserId = newUser.UserId;
1025
+ const userToBeCreated = new User(loginUser.SessionService, dbTransaction, userInfo);
1026
+ const activity = new activity_history_1.Activity();
1027
+ activity.ActivityId = activity.createId();
1028
+ activity.Action = activity_history_1.ActionEnum.CREATE;
1029
+ activity.Description = 'Create User';
1030
+ activity.EntityType = 'LoginUser';
1031
+ activity.EntityId = newUser.UserId.toString();
1032
+ activity.EntityValueBefore = JSON.stringify({});
1033
+ activity.EntityValueAfter = JSON.stringify(newUser.get({ plain: true }));
1034
+ yield activity.create(loginUser.ObjectId, dbTransaction);
1035
+ return userToBeCreated;
1036
+ }
1037
+ catch (error) {
1038
+ throw error;
1039
+ }
1040
+ });
1041
+ }
1042
+ incrementFailedLoginAttemptCount(dbTransaction) {
1043
+ return __awaiter(this, void 0, void 0, function* () {
1044
+ const maxFailedLoginAttempts = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'maxFailedLoginAttempts');
1045
+ const autoReleaseYN = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'autoReleaseYN');
1046
+ if (!maxFailedLoginAttempts || !autoReleaseYN) {
1047
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Missing maxFailedLoginAttempts and or autoReleaseYN. Please set in config file.');
1048
+ }
1049
+ const FailedLoginAttemptCount = this.FailedLoginAttemptCount + 1;
1050
+ const LastFailedLoginAt = new Date();
1051
+ if (FailedLoginAttemptCount > maxFailedLoginAttempts) {
1052
+ this.Status = enum_1.UserStatus.LOCKED;
1053
+ }
1054
+ yield User._Repository.update({
1055
+ FailedLoginAttemptCount: FailedLoginAttemptCount,
1056
+ LastFailedLoginAt: LastFailedLoginAt,
1057
+ Status: this.Status,
1058
+ }, {
1059
+ where: {
1060
+ UserId: this.UserId,
1061
+ },
1062
+ transaction: dbTransaction,
1063
+ });
1064
+ if (this.Status === enum_1.UserStatus.LOCKED && autoReleaseYN === 'Y') {
1065
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Your account has been temporarily locked due to too many failed login attempts, please try again later.');
1066
+ }
1067
+ if (this.Status === enum_1.UserStatus.LOCKED && autoReleaseYN === 'N') {
1068
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Your account has been locked due to too many failed login attempts, please contact IT Support for instructions on how to unlock your account');
1069
+ }
1070
+ if (this.Status == enum_1.UserStatus.LOCKED) {
1071
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid credentials.');
1072
+ }
1073
+ });
1074
+ }
1075
+ static shouldReleaseLock(LastFailedLoginAt) {
1076
+ const minuteToAutoRelease = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'minuteToAutoRelease');
1077
+ const autoReleaseYN = config_1.ComponentConfig.getComponentConfigValue('@tomei/sso', 'autoReleaseYN');
1078
+ if (!minuteToAutoRelease || !autoReleaseYN) {
1079
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Missing minuteToAutoRelease and or autoReleaseYN. Please set in config file.');
1080
+ }
1081
+ if (autoReleaseYN === 'Y') {
1082
+ const lastFailedDate = new Date(LastFailedLoginAt);
1083
+ const currentDate = new Date();
1084
+ const timeDifferenceInMillis = currentDate.getTime() - lastFailedDate.getTime();
1085
+ const timeDifferenceInMinutes = timeDifferenceInMillis / (1000 * 60);
1086
+ if (timeDifferenceInMinutes > +minuteToAutoRelease) {
1087
+ return true;
1088
+ }
1089
+ else {
1090
+ return false;
1091
+ }
1092
+ }
1093
+ else if (autoReleaseYN === 'N') {
1094
+ return false;
1095
+ }
1096
+ }
1097
+ static releaseLock(UserId, dbTransaction) {
1098
+ this._Repository.update({
1099
+ FailedLoginAttemptCount: 0,
1100
+ Status: enum_1.UserStatus.ACTIVE,
1101
+ }, {
1102
+ where: {
1103
+ UserId: UserId,
1104
+ },
1105
+ transaction: dbTransaction,
1106
+ });
1107
+ }
1108
+ static getGroups(loginUser, dbTransaction) {
1109
+ return __awaiter(this, void 0, void 0, function* () {
1110
+ const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1111
+ const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'UserGroup - List Own');
1112
+ if (!isPrivileged) {
1113
+ throw new Error('You do not have permission to list UserGroup.');
1114
+ }
1115
+ const userGroups = yield User._UserGroupRepo.findAll({
1116
+ where: {
1117
+ UserId: loginUser.ObjectId,
1118
+ Status: 'Active',
1119
+ },
1120
+ include: [{ model: user_entity_1.default, as: 'User' }, { model: group_entity_1.default }],
1121
+ transaction: dbTransaction,
1122
+ });
1123
+ return userGroups;
1124
+ });
1125
+ }
1126
+ static getInheritedSystemAccess(dbTransaction, group) {
1127
+ return __awaiter(this, void 0, void 0, function* () {
1128
+ const dataSystemAccesses = yield User._GroupSystemAccessRepo.findAll({
1129
+ where: {
1130
+ GroupCode: group.GroupCode,
1131
+ Status: 'Active',
1132
+ },
1133
+ include: [{ model: system_entity_1.default }],
1134
+ transaction: dbTransaction,
1135
+ });
1136
+ let systemAccesses = dataSystemAccesses;
1137
+ if (group.InheritParentPrivilegeYN === 'Y' && group.ParentGroupCode) {
1138
+ const GroupCode = group.ParentGroupCode;
1139
+ const parentGroup = yield User._GroupRepo.findByPk(GroupCode, dbTransaction);
1140
+ const dataParentSystemAccesses = yield User.getInheritedSystemAccess(dbTransaction, parentGroup);
1141
+ const parentSystemAccesses = dataParentSystemAccesses;
1142
+ systemAccesses = systemAccesses.concat(parentSystemAccesses);
1143
+ }
1144
+ return systemAccesses;
1145
+ });
1146
+ }
1147
+ static combineSystemAccess(loginUser, dbTransaction, groups) {
1148
+ return __awaiter(this, void 0, void 0, function* () {
1149
+ const userAccess = yield User._UserSystemAccessRepo.findAll({
1150
+ where: {
1151
+ UserId: loginUser.ObjectId,
1152
+ Status: 'Active',
1153
+ },
1154
+ include: [{ model: system_entity_1.default }],
1155
+ transaction: dbTransaction,
1156
+ });
1157
+ const groupAccessPromises = groups.map((e) => __awaiter(this, void 0, void 0, function* () {
1158
+ if (e.InheritParentSystemAccessYN) {
1159
+ return yield this.getInheritedSystemAccess(dbTransaction, e);
1160
+ }
1161
+ else {
1162
+ return [];
1163
+ }
1164
+ }));
1165
+ const groupAccess = (yield Promise.all(groupAccessPromises)).flat();
1166
+ const allAccess = userAccess.concat(groupAccess);
1167
+ const uniqueAccess = new Set(allAccess.filter((value, index, self) => {
1168
+ return self.some((prev) => prev.SystemCode === value.SystemCode);
1169
+ }));
1170
+ return Array.from(uniqueAccess);
1171
+ });
1172
+ }
1173
+ static getSystems(loginUser, dbTransaction) {
1174
+ return __awaiter(this, void 0, void 0, function* () {
1175
+ const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1176
+ const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'System – List Own');
1177
+ if (!isPrivileged) {
1178
+ throw new Error('You do not have permission to list UserGroup.');
1179
+ }
1180
+ const groups = yield User.getGroups(loginUser, dbTransaction);
1181
+ const systemAccess = yield User.combineSystemAccess(loginUser, dbTransaction, groups);
1182
+ const output = [];
1183
+ if (systemAccess) {
1184
+ for (let i = 0; i < systemAccess.length; i++) {
1185
+ const system = yield User._SystemRepository.findOne({
1186
+ where: {
1187
+ SystemCode: systemAccess[i].SystemCode,
1188
+ Status: 'Active',
1189
+ },
1190
+ });
1191
+ output.push({
1192
+ UserSystemAccessId: systemAccess[i].UserSystemAccessId,
1193
+ UserId: systemAccess[i].UserId,
1194
+ SystemCode: systemAccess[i].SystemCode,
1195
+ Status: systemAccess[i].Status,
1196
+ CreatedById: systemAccess[i].CreatedById,
1197
+ UpdatedById: systemAccess[i].UpdatedById,
1198
+ CreatedAt: systemAccess[i].CreatedAt,
1199
+ UpdatedAt: systemAccess[i].UpdatedAt,
1200
+ System: system,
1201
+ });
1202
+ }
1203
+ }
1204
+ return output;
1205
+ });
1206
+ }
1207
+ static check2FA(loginUser, dbTransaction) {
1208
+ return __awaiter(this, void 0, void 0, function* () {
1209
+ try {
1210
+ const user = yield User._Repository.findOne({
1211
+ where: {
1212
+ UserId: loginUser.UserId,
1213
+ },
1214
+ transaction: dbTransaction,
1215
+ });
1216
+ if (user.MFAEnabled === 1) {
1217
+ return true;
1218
+ }
1219
+ return false;
1220
+ }
1221
+ catch (error) {
1222
+ throw error;
1223
+ }
1224
+ });
1225
+ }
1226
+ static setup2FA(userId, dbTransaction) {
1227
+ return __awaiter(this, void 0, void 0, function* () {
1228
+ var _a, _b, _c, _d;
1229
+ const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1230
+ const user = yield User._Repository.findOne({
1231
+ where: {
1232
+ UserId: userId,
1233
+ },
1234
+ });
1235
+ if (!user) {
1236
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Credentials');
1237
+ }
1238
+ const secretCode = speakeasy.generateSecret({ name: 'Tomei SSO' });
1239
+ let userMFAConfig = null;
1240
+ if ((user === null || user === void 0 ? void 0 : user.MFAConfig) !== null && typeof (user === null || user === void 0 ? void 0 : user.MFAConfig) === 'string') {
1241
+ try {
1242
+ userMFAConfig = JSON.parse(user === null || user === void 0 ? void 0 : user.MFAConfig);
1243
+ }
1244
+ catch (error) {
1245
+ console.error('Invalid JSON string on MFAConfig:', error);
1246
+ }
1247
+ }
1248
+ const MFAConfig = {
1249
+ totp: {
1250
+ enabled: true,
1251
+ secret: secretCode.base32,
1252
+ issuer: systemCode,
1253
+ },
1254
+ sms: {
1255
+ enabled: ((_a = userMFAConfig === null || userMFAConfig === void 0 ? void 0 : userMFAConfig.sms) === null || _a === void 0 ? void 0 : _a.enable) || false,
1256
+ phoneNumber: ((_b = userMFAConfig === null || userMFAConfig === void 0 ? void 0 : userMFAConfig.sms) === null || _b === void 0 ? void 0 : _b.phoneNumber) || '',
1257
+ },
1258
+ email: {
1259
+ enabled: ((_c = userMFAConfig === null || userMFAConfig === void 0 ? void 0 : userMFAConfig.email) === null || _c === void 0 ? void 0 : _c.enable) || false,
1260
+ emailAddress: ((_d = userMFAConfig === null || userMFAConfig === void 0 ? void 0 : userMFAConfig.email) === null || _d === void 0 ? void 0 : _d.emailAddress) || '',
1261
+ },
1262
+ };
1263
+ user.MFAEnabled = 0;
1264
+ user.MFAConfig = JSON.stringify(MFAConfig);
1265
+ yield User._Repository.update({
1266
+ MFAEnabled: user.MFAEnabled,
1267
+ MFAConfig: user.MFAConfig,
1268
+ }, {
1269
+ where: {
1270
+ UserId: userId,
1271
+ },
1272
+ transaction: dbTransaction,
1273
+ });
1274
+ return secretCode.otpauth_url;
1275
+ });
1276
+ }
1277
+ verify2FASetup(userId, mfaToken, systemCode, dbTransaction) {
1278
+ return __awaiter(this, void 0, void 0, function* () {
1279
+ const user = yield User._Repository.findOne({
1280
+ where: {
1281
+ UserId: userId,
1282
+ },
1283
+ });
1284
+ if (!user) {
1285
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Credentials');
1286
+ }
1287
+ let userMFAConfig = null;
1288
+ if ((user === null || user === void 0 ? void 0 : user.MFAConfig) !== null && typeof (user === null || user === void 0 ? void 0 : user.MFAConfig) === 'string') {
1289
+ try {
1290
+ userMFAConfig = JSON.parse(user === null || user === void 0 ? void 0 : user.MFAConfig);
1291
+ }
1292
+ catch (error) {
1293
+ console.error('Invalid JSON string on MFAConfig:', error);
1294
+ }
1295
+ }
1296
+ const isVerified = yield speakeasy.totp.verify({
1297
+ secret: userMFAConfig.totp.secret,
1298
+ encoding: 'base32',
1299
+ token: mfaToken,
1300
+ });
1301
+ if (!isVerified) {
1302
+ return false;
1303
+ }
1304
+ user.MFAEnabled = 1;
1305
+ yield user.save({ transaction: dbTransaction });
1306
+ const userSession = yield this._SessionService.retrieveUserSession(`${userId}`);
1307
+ if (!systemCode) {
1308
+ systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1309
+ }
1310
+ const systemLogin = userSession.systemLogins.find((e) => e.code === systemCode);
1311
+ return `${userId}:${systemLogin.sessionId}`;
1312
+ });
1313
+ }
1314
+ verify2FACode(userId, mfaToken, systemCode, dbTransaction) {
1315
+ return __awaiter(this, void 0, void 0, function* () {
1316
+ const user = yield User._Repository.findOne({
1317
+ where: {
1318
+ UserId: userId,
1319
+ },
1320
+ transaction: dbTransaction,
1321
+ });
1322
+ if (!user) {
1323
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Credentials');
1324
+ }
1325
+ let userMFAConfig = null;
1326
+ if ((user === null || user === void 0 ? void 0 : user.MFAConfig) !== null && typeof (user === null || user === void 0 ? void 0 : user.MFAConfig) === 'string') {
1327
+ try {
1328
+ userMFAConfig = JSON.parse(user === null || user === void 0 ? void 0 : user.MFAConfig);
1329
+ }
1330
+ catch (error) {
1331
+ console.error('Invalid JSON string on MFAConfig:', error);
1332
+ }
1333
+ }
1334
+ const isVerified = yield speakeasy.totp.verify({
1335
+ secret: userMFAConfig.totp.secret,
1336
+ encoding: 'base32',
1337
+ token: mfaToken,
1338
+ });
1339
+ if (!isVerified) {
1340
+ return false;
1341
+ }
1342
+ const userSession = yield this._SessionService.retrieveUserSession(`${userId}`);
1343
+ if (!systemCode) {
1344
+ systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1345
+ }
1346
+ const systemLogin = userSession.systemLogins.find((e) => e.code === systemCode);
1347
+ return `${userId}:${systemLogin.sessionId}`;
1348
+ });
1349
+ }
1350
+ bypass2FA(systemCode, dbTransaction) {
1351
+ return __awaiter(this, void 0, void 0, function* () {
1352
+ try {
1353
+ const user = yield User._Repository.findOne({
1354
+ where: {
1355
+ UserId: this.UserId,
1356
+ },
1357
+ transaction: dbTransaction,
1358
+ });
1359
+ if (user.MFAEnabled === 1) {
1360
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Cannot bypass 2FA as it is enabled');
1361
+ }
1362
+ const userSession = yield this._SessionService.retrieveUserSession(`${this.UserId}`);
1363
+ if (!systemCode) {
1364
+ systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1365
+ }
1366
+ const systemLogin = userSession.systemLogins.find((e) => e.code === systemCode);
1367
+ return `${this.UserId}:${systemLogin.sessionId}`;
1368
+ }
1369
+ catch (error) {
1370
+ throw error;
1371
+ }
1372
+ });
1373
+ }
1374
+ addUserGroup(GroupCode, loginUser, dbTransaction) {
1375
+ return __awaiter(this, void 0, void 0, function* () {
1376
+ const group = yield User._GroupRepo.findOne({
1377
+ where: {
1378
+ GroupCode,
1379
+ },
1380
+ transaction: dbTransaction,
1381
+ });
1382
+ if (!group) {
1383
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Group Code');
1384
+ }
1385
+ const entityValueAfter = {
1386
+ UserId: this.UserId,
1387
+ GroupCode: group.GroupCode,
1388
+ CreatedAt: new Date(),
1389
+ CreatedById: loginUser.UserId,
1390
+ UpdatedAt: new Date(),
1391
+ UpdatedById: loginUser.UserId,
1392
+ };
1393
+ yield User._UserGroupRepo.create(entityValueAfter, {
1394
+ transaction: dbTransaction,
1395
+ });
1396
+ const activity = new activity_history_1.Activity();
1397
+ activity.ActivityId = activity.createId();
1398
+ activity.Action = activity_history_1.ActionEnum.CREATE;
1399
+ activity.Description = 'Add User Group';
1400
+ activity.EntityType = 'UserGroup';
1401
+ activity.EntityId = group.GroupCode;
1402
+ activity.EntityValueBefore = JSON.stringify({});
1403
+ activity.EntityValueAfter = JSON.stringify(entityValueAfter);
1404
+ yield activity.create(loginUser.ObjectId, dbTransaction);
1405
+ });
1406
+ }
1407
+ update(data, loginUser, dbTransaction) {
1408
+ return __awaiter(this, void 0, void 0, function* () {
1409
+ const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1410
+ const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'User - Update');
1411
+ if (!isPrivileged) {
1412
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'You do not have the privilege to update user');
1413
+ }
1414
+ if (!this.UserId) {
1415
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'UserId is required');
1416
+ }
1417
+ if (data.Email !== this.Email) {
1418
+ yield User.checkUserInfoDuplicated(dbTransaction, {
1419
+ UserName: data.UserName,
1420
+ });
1421
+ }
1422
+ if (data.UserName !== this.UserName) {
1423
+ yield User.checkUserInfoDuplicated(dbTransaction, {
1424
+ UserName: data.UserName,
1425
+ });
1426
+ }
1427
+ if (data.BuildingCode) {
1428
+ const building = yield group_entity_1.default.findOne({
1429
+ where: {
1430
+ Type: 'Building',
1431
+ GroupCode: data.BuildingCode,
1432
+ },
1433
+ transaction: dbTransaction,
1434
+ });
1435
+ if (!building) {
1436
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Building Code');
1437
+ }
1438
+ const userBuilding = yield User._UserGroupRepo.findOne({
1439
+ where: {
1440
+ UserId: this.UserId,
1441
+ },
1442
+ include: [
1443
+ {
1444
+ model: group_entity_1.default,
1445
+ where: {
1446
+ Type: 'Building',
1447
+ },
1448
+ },
1449
+ ],
1450
+ transaction: dbTransaction,
1451
+ });
1452
+ if (userBuilding) {
1453
+ yield User._UserGroupRepo.update({
1454
+ GroupCode: data.BuildingCode,
1455
+ UpdatedAt: new Date(),
1456
+ UpdatedById: loginUser.UserId,
1457
+ }, {
1458
+ where: {
1459
+ UserId: this.UserId,
1460
+ GroupCode: userBuilding.GroupCode,
1461
+ },
1462
+ transaction: dbTransaction,
1463
+ });
1464
+ }
1465
+ else {
1466
+ yield User._UserGroupRepo.create({
1467
+ UserId: this.UserId,
1468
+ GroupCode: data.BuildingCode,
1469
+ CreatedAt: new Date(),
1470
+ CreatedById: loginUser.UserId,
1471
+ UpdatedAt: new Date(),
1472
+ UpdatedById: loginUser.UserId,
1473
+ }, {
1474
+ transaction: dbTransaction,
1475
+ });
1476
+ }
1477
+ }
1478
+ if (data.CompanyCode) {
1479
+ const company = yield group_entity_1.default.findOne({
1480
+ where: {
1481
+ Type: 'Company',
1482
+ GroupCode: data.CompanyCode,
1483
+ },
1484
+ transaction: dbTransaction,
1485
+ });
1486
+ if (!company) {
1487
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Company Code');
1488
+ }
1489
+ const userCompany = yield User._UserGroupRepo.findOne({
1490
+ where: {
1491
+ UserId: this.UserId,
1492
+ },
1493
+ include: [
1494
+ {
1495
+ model: group_entity_1.default,
1496
+ where: {
1497
+ Type: 'Company',
1498
+ },
1499
+ },
1500
+ ],
1501
+ transaction: dbTransaction,
1502
+ });
1503
+ if (userCompany) {
1504
+ yield User._UserGroupRepo.update({
1505
+ GroupCode: data.CompanyCode,
1506
+ UpdatedAt: new Date(),
1507
+ UpdatedById: loginUser.UserId,
1508
+ }, {
1509
+ where: {
1510
+ UserId: this.UserId,
1511
+ GroupCode: userCompany.GroupCode,
1512
+ },
1513
+ transaction: dbTransaction,
1514
+ });
1515
+ }
1516
+ else {
1517
+ yield User._UserGroupRepo.create({
1518
+ UserId: this.UserId,
1519
+ GroupCode: data.CompanyCode,
1520
+ CreatedAt: new Date(),
1521
+ CreatedById: loginUser.UserId,
1522
+ UpdatedAt: new Date(),
1523
+ UpdatedById: loginUser.UserId,
1524
+ }, {
1525
+ transaction: dbTransaction,
1526
+ });
1527
+ }
1528
+ }
1529
+ if (data.DepartmentCode) {
1530
+ const department = yield group_entity_1.default.findOne({
1531
+ where: {
1532
+ Type: 'Department',
1533
+ GroupCode: data.DepartmentCode,
1534
+ },
1535
+ transaction: dbTransaction,
1536
+ });
1537
+ if (!department) {
1538
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'Invalid Department Code');
1539
+ }
1540
+ const userDepartment = yield User._UserGroupRepo.findOne({
1541
+ where: {
1542
+ UserId: this.UserId,
1543
+ },
1544
+ include: [
1545
+ {
1546
+ model: group_entity_1.default,
1547
+ where: {
1548
+ Type: 'Department',
1549
+ },
1550
+ },
1551
+ ],
1552
+ transaction: dbTransaction,
1553
+ });
1554
+ if (userDepartment) {
1555
+ yield User._UserGroupRepo.update({
1556
+ GroupCode: data.DepartmentCode,
1557
+ UpdatedAt: new Date(),
1558
+ UpdatedById: loginUser.UserId,
1559
+ }, {
1560
+ where: {
1561
+ UserId: this.UserId,
1562
+ GroupCode: userDepartment.GroupCode,
1563
+ },
1564
+ transaction: dbTransaction,
1565
+ });
1566
+ }
1567
+ else {
1568
+ yield User._UserGroupRepo.create({
1569
+ UserId: this.UserId,
1570
+ GroupCode: data.DepartmentCode,
1571
+ CreatedAt: new Date(),
1572
+ CreatedById: loginUser.UserId,
1573
+ UpdatedAt: new Date(),
1574
+ UpdatedById: loginUser.UserId,
1575
+ }, {
1576
+ transaction: dbTransaction,
1577
+ });
1578
+ }
1579
+ }
1580
+ const entityValueBefore = {
1581
+ UserId: this.UserId,
1582
+ UserName: this.UserName,
1583
+ Email: this.Email,
1584
+ Password: this.Password,
1585
+ Status: this.Status,
1586
+ DefaultPasswordChangedYN: this.DefaultPasswordChangedYN,
1587
+ FirstLoginAt: this.FirstLoginAt,
1588
+ LastLoginAt: this.LastLoginAt,
1589
+ MFAEnabled: this.MFAEnabled,
1590
+ MFAConfig: this.MFAConfig,
1591
+ RecoveryEmail: this.RecoveryEmail,
1592
+ FailedLoginAttemptCount: this.FailedLoginAttemptCount,
1593
+ LastFailedLoginAt: this.LastFailedLoginAt,
1594
+ LastPasswordChangedAt: this.LastPasswordChangedAt,
1595
+ NeedToChangePasswordYN: this.NeedToChangePasswordYN,
1596
+ CreatedById: this.CreatedById,
1597
+ CreatedAt: this.CreatedAt,
1598
+ UpdatedById: this.UpdatedById,
1599
+ UpdatedAt: this.UpdatedAt,
1600
+ };
1601
+ this.UserName = data.UserName;
1602
+ this.Email = data.Email;
1603
+ this.Status = data.Status;
1604
+ this.RecoveryEmail = data.RecoveryEmail;
1605
+ this.UpdatedAt = new Date();
1606
+ this.UpdatedById = loginUser.UserId;
1607
+ yield User._Repository.update({
1608
+ UserName: this.UserName,
1609
+ Email: this.Email,
1610
+ Status: this.Status,
1611
+ RecoveryEmail: this.RecoveryEmail,
1612
+ UpdatedById: this.UpdatedById,
1613
+ UpdatedAt: this.UpdatedAt,
1614
+ }, {
1615
+ where: {
1616
+ UserId: this.UserId,
1617
+ },
1618
+ transaction: dbTransaction,
1619
+ });
1620
+ const entityValueAfter = {
1621
+ UserId: this.UserId,
1622
+ UserName: this.UserName,
1623
+ Email: this.Email,
1624
+ Password: this.Password,
1625
+ Status: this.Status,
1626
+ DefaultPasswordChangedYN: this.DefaultPasswordChangedYN,
1627
+ FirstLoginAt: this.FirstLoginAt,
1628
+ LastLoginAt: this.LastLoginAt,
1629
+ MFAEnabled: this.MFAEnabled,
1630
+ MFAConfig: this.MFAConfig,
1631
+ RecoveryEmail: this.RecoveryEmail,
1632
+ FailedLoginAttemptCount: this.FailedLoginAttemptCount,
1633
+ LastFailedLoginAt: this.LastFailedLoginAt,
1634
+ LastPasswordChangedAt: this.LastPasswordChangedAt,
1635
+ NeedToChangePasswordYN: this.NeedToChangePasswordYN,
1636
+ CreatedById: this.CreatedById,
1637
+ CreatedAt: this.CreatedAt,
1638
+ UpdatedById: this.UpdatedById,
1639
+ UpdatedAt: this.UpdatedAt,
1640
+ };
1641
+ const activity = new activity_history_1.Activity();
1642
+ activity.ActivityId = activity.createId();
1643
+ activity.Action = activity_history_1.ActionEnum.UPDATE;
1644
+ activity.Description = 'Update User';
1645
+ activity.EntityType = 'LoginUser';
1646
+ activity.EntityId = this.UserId.toString();
1647
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
1648
+ activity.EntityValueAfter = JSON.stringify(entityValueAfter);
1649
+ yield activity.create(loginUser.ObjectId, dbTransaction);
1650
+ return this;
1651
+ });
1652
+ }
1653
+ static findById(loginUser, dbTransaction, UserId) {
1654
+ return __awaiter(this, void 0, void 0, function* () {
1655
+ const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1656
+ const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'USER_VIEW');
1657
+ if (!isPrivileged) {
1658
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'You do not have the privilege to find user');
1659
+ }
1660
+ const user = yield User._Repository.findOne({
1661
+ where: {
1662
+ UserId: UserId,
1663
+ Status: 'Active',
1664
+ },
1665
+ transaction: dbTransaction,
1666
+ });
1667
+ const userAttr = {
1668
+ UserId: user.UserId,
1669
+ UserName: user.UserName,
1670
+ FullName: (user === null || user === void 0 ? void 0 : user.FullName) || null,
1671
+ IDNo: (user === null || user === void 0 ? void 0 : user.IdNo) || null,
1672
+ IDType: (user === null || user === void 0 ? void 0 : user.IdType) || null,
1673
+ ContactNo: (user === null || user === void 0 ? void 0 : user.ContactNo) || null,
1674
+ Email: user.Email,
1675
+ Password: user.Password,
1676
+ Status: user.Status,
1677
+ DefaultPasswordChangedYN: user.DefaultPasswordChangedYN,
1678
+ FirstLoginAt: user.FirstLoginAt,
1679
+ LastLoginAt: user.LastLoginAt,
1680
+ MFAEnabled: user.MFAEnabled,
1681
+ MFAConfig: user.MFAConfig,
1682
+ RecoveryEmail: user.RecoveryEmail,
1683
+ FailedLoginAttemptCount: user.FailedLoginAttemptCount,
1684
+ LastFailedLoginAt: user.LastFailedLoginAt,
1685
+ LastPasswordChangedAt: user.LastPasswordChangedAt,
1686
+ NeedToChangePasswordYN: user.NeedToChangePasswordYN,
1687
+ CreatedById: user.CreatedById,
1688
+ CreatedAt: user.CreatedAt,
1689
+ UpdatedById: user.UpdatedById,
1690
+ UpdatedAt: user.UpdatedAt,
1691
+ staffs: (user === null || user === void 0 ? void 0 : user.Staff) || null,
1692
+ };
1693
+ return new User(null, dbTransaction, userAttr);
1694
+ });
1695
+ }
1696
+ static getFullName(dbTransaction, UserId) {
1697
+ return __awaiter(this, void 0, void 0, function* () {
1698
+ try {
1699
+ const user = yield User._Repository.findOne({
1700
+ where: {
1701
+ UserId: UserId,
1702
+ },
1703
+ transaction: dbTransaction,
1704
+ });
1705
+ if (!user) {
1706
+ throw new general_1.ClassError('User', 'UserErrMsg0X', 'No user found.');
1707
+ }
1708
+ if (user === null || user === void 0 ? void 0 : user.FullName) {
1709
+ return user === null || user === void 0 ? void 0 : user.FullName;
1710
+ }
1711
+ else if (user === null || user === void 0 ? void 0 : user.UserName) {
1712
+ return user === null || user === void 0 ? void 0 : user.UserName;
1713
+ }
1714
+ else {
1715
+ return '';
1716
+ }
1717
+ }
1718
+ catch (error) {
1719
+ throw error;
1720
+ }
1721
+ });
1722
+ }
1723
+ static findByEmail(loginUser, dbTransaction, Email) {
1724
+ return __awaiter(this, void 0, void 0, function* () {
1725
+ try {
1726
+ const systemCode = config_1.ApplicationConfig.getComponentConfigValue('system-code');
1727
+ const isPrivileged = yield loginUser.checkPrivileges(systemCode, 'USER_VIEW');
1728
+ if (!isPrivileged) {
1729
+ throw new general_1.ClassError('LoginUser', 'LoginUserErrMsg0X', 'You do not have the privilege to find user');
1730
+ }
1731
+ const user = yield User._Repository.findOne({
1732
+ where: {
1733
+ Email: Email,
1734
+ },
1735
+ include: [
1736
+ {
1737
+ model: staff_entity_1.default,
1738
+ },
1739
+ ],
1740
+ transaction: dbTransaction,
1741
+ });
1742
+ if (!user) {
1743
+ throw new general_1.ClassError('User', 'UserErrMsg0X', 'User not found.');
1744
+ }
1745
+ const userAttr = {
1746
+ UserId: user.UserId,
1747
+ UserName: user.UserName,
1748
+ FullName: (user === null || user === void 0 ? void 0 : user.FullName) || null,
1749
+ IDNo: (user === null || user === void 0 ? void 0 : user.IdNo) || null,
1750
+ IDType: (user === null || user === void 0 ? void 0 : user.IdType) || null,
1751
+ ContactNo: (user === null || user === void 0 ? void 0 : user.ContactNo) || null,
1752
+ Email: user.Email,
1753
+ Password: user.Password,
1754
+ Status: user.Status,
1755
+ DefaultPasswordChangedYN: user.DefaultPasswordChangedYN,
1756
+ FirstLoginAt: user.FirstLoginAt,
1757
+ LastLoginAt: user.LastLoginAt,
1758
+ MFAEnabled: user.MFAEnabled,
1759
+ MFAConfig: user.MFAConfig,
1760
+ RecoveryEmail: user.RecoveryEmail,
1761
+ FailedLoginAttemptCount: user.FailedLoginAttemptCount,
1762
+ LastFailedLoginAt: user.LastFailedLoginAt,
1763
+ LastPasswordChangedAt: user.LastPasswordChangedAt,
1764
+ NeedToChangePasswordYN: user.NeedToChangePasswordYN,
1765
+ CreatedById: user.CreatedById,
1766
+ CreatedAt: user.CreatedAt,
1767
+ UpdatedById: user.UpdatedById,
1768
+ UpdatedAt: user.UpdatedAt,
1769
+ staffs: user === null || user === void 0 ? void 0 : user.Staff,
1770
+ };
1771
+ const sessionService = yield session_service_1.SessionService.init(undefined);
1772
+ const usr = new User(sessionService, undefined, userAttr);
1773
+ return usr;
1774
+ }
1775
+ catch (error) {
1776
+ throw error;
1777
+ }
1778
+ });
1779
+ }
1780
+ }
1781
+ exports.User = User;
1782
+ User._Repository = new user_repository_1.UserRepository();
1783
+ User._LoginHistoryRepository = new login_history_repository_1.LoginHistoryRepository();
1784
+ User._UserGroupRepo = new user_group_repository_1.UserGroupRepository();
1785
+ User._UserPrivilegeRepo = new user_privilege_repository_1.UserPrivilegeRepository();
1786
+ User._UserObjectPrivilegeRepo = new user_object_privilege_repository_1.UserObjectPrivilegeRepository();
1787
+ User._GroupObjectPrivilegeRepo = new group_object_privilege_repository_1.GroupObjectPrivilegeRepository();
1788
+ User._SystemRepository = new system_repository_1.SystemRepository();
1789
+ User._UserSystemAccessRepo = new user_system_access_repository_1.UserSystemAccessRepository();
1790
+ User._GroupSystemAccessRepo = new group_system_access_repository_1.GroupSystemAccessRepository();
1791
+ User._GroupRepo = new group_repository_1.GroupRepository();
1792
1792
  //# sourceMappingURL=user.js.map