@flusys/nestjs-auth 7.1.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/README.md +1 -1
  2. package/config/index.d.ts +3 -3
  3. package/config/message-keys.d.ts +4 -0
  4. package/controllers/authentication.controller.d.ts +5 -5
  5. package/controllers/branch.controller.d.ts +2 -2
  6. package/controllers/company-selection.controller.d.ts +4 -4
  7. package/controllers/company.controller.d.ts +2 -2
  8. package/controllers/email-verification.controller.d.ts +6 -6
  9. package/controllers/index.d.ts +9 -9
  10. package/controllers/social-auth-config.controller.d.ts +2 -2
  11. package/controllers/social-auth.controller.d.ts +3 -3
  12. package/controllers/user-permission.controller.d.ts +7 -4
  13. package/controllers/user.controller.d.ts +7 -7
  14. package/docs/auth-swagger.config.d.ts +2 -2
  15. package/docs/index.d.ts +1 -1
  16. package/dtos/index.d.ts +6 -6
  17. package/dtos/social-auth.dto.d.ts +1 -1
  18. package/dtos/user-permission.dto.d.ts +30 -0
  19. package/entities/company-branch.entity.d.ts +1 -1
  20. package/entities/company.entity.d.ts +1 -1
  21. package/entities/index.d.ts +14 -14
  22. package/entities/pending-registration.entity.d.ts +1 -1
  23. package/entities/user-company-permission.entity.d.ts +4 -4
  24. package/enums/index.d.ts +2 -2
  25. package/fesm/118.js +1404 -0
  26. package/fesm/120.js +2265 -0
  27. package/fesm/24.js +4422 -0
  28. package/fesm/370.js +1163 -0
  29. package/fesm/446.js +877 -0
  30. package/fesm/chunks/117.js +69 -0
  31. package/fesm/config/index.js +246 -3
  32. package/fesm/controllers/index.js +27 -9
  33. package/fesm/docs/index.js +479 -1
  34. package/fesm/dtos/index.js +135 -6
  35. package/fesm/entities/index.js +68 -22
  36. package/fesm/enums/index.js +53 -2
  37. package/fesm/helpers/index.js +115 -2
  38. package/fesm/index.js +1455 -13
  39. package/fesm/interceptors/index.js +510 -2
  40. package/fesm/interfaces/index.js +75 -8
  41. package/fesm/modules/index.js +546 -1
  42. package/fesm/runtime.js +134 -0
  43. package/fesm/services/index.js +67 -11
  44. package/helpers/auth-response.mapper.d.ts +3 -3
  45. package/helpers/index.d.ts +2 -2
  46. package/helpers/token.helper.d.ts +2 -2
  47. package/index.d.ts +13 -13
  48. package/interceptors/clear-token.interceptor.d.ts +2 -2
  49. package/interceptors/index.d.ts +2 -2
  50. package/interceptors/set-token.interceptor.d.ts +2 -2
  51. package/interfaces/auth-module-options.interface.d.ts +3 -3
  52. package/interfaces/authentication.interface.d.ts +3 -3
  53. package/interfaces/company-branch.interface.d.ts +2 -2
  54. package/interfaces/company.interface.d.ts +1 -1
  55. package/interfaces/index.d.ts +8 -8
  56. package/interfaces/social-auth.interface.d.ts +2 -2
  57. package/interfaces/user-enricher.interface.d.ts +3 -3
  58. package/modules/auth.module.d.ts +4 -4
  59. package/modules/index.d.ts +1 -1
  60. package/package.json +32 -39
  61. package/providers/facebook.social-provider.d.ts +2 -2
  62. package/providers/google.social-provider.d.ts +2 -2
  63. package/providers/index.d.ts +1 -1
  64. package/providers/linkedin.social-provider.d.ts +2 -2
  65. package/providers/microsoft.social-provider.d.ts +2 -2
  66. package/providers/social-provider.registry.d.ts +2 -2
  67. package/services/auth-config.service.d.ts +3 -3
  68. package/services/auth-datasource.provider.d.ts +3 -3
  69. package/services/auth-email.service.d.ts +3 -3
  70. package/services/authentication.service.d.ts +12 -12
  71. package/services/branch.service.d.ts +7 -7
  72. package/services/company.service.d.ts +6 -6
  73. package/services/index.d.ts +11 -11
  74. package/services/social-auth-config.service.d.ts +6 -6
  75. package/services/social-auth.service.d.ts +5 -5
  76. package/services/user-permission.service.d.ts +10 -4
  77. package/services/user.service.d.ts +7 -7
  78. package/strategies/jwt.strategy.d.ts +4 -4
  79. package/validators/password.validator.d.ts +1 -1
  80. package/cjs/config/auth.constants.js +0 -49
  81. package/cjs/config/event-actions.js +0 -47
  82. package/cjs/config/index.js +0 -20
  83. package/cjs/config/message-keys.js +0 -135
  84. package/cjs/controllers/authentication.controller.js +0 -427
  85. package/cjs/controllers/authentication.controller.spec.js +0 -219
  86. package/cjs/controllers/branch.controller.js +0 -102
  87. package/cjs/controllers/branch.controller.spec.js +0 -134
  88. package/cjs/controllers/company-selection.controller.js +0 -198
  89. package/cjs/controllers/company-selection.controller.spec.js +0 -84
  90. package/cjs/controllers/company.controller.js +0 -102
  91. package/cjs/controllers/company.controller.spec.js +0 -131
  92. package/cjs/controllers/email-verification.controller.js +0 -224
  93. package/cjs/controllers/email-verification.controller.spec.js +0 -142
  94. package/cjs/controllers/index.js +0 -26
  95. package/cjs/controllers/social-auth-config.controller.js +0 -107
  96. package/cjs/controllers/social-auth.controller.js +0 -175
  97. package/cjs/controllers/social-auth.controller.spec.js +0 -79
  98. package/cjs/controllers/user-permission.controller.js +0 -223
  99. package/cjs/controllers/user-permission.controller.spec.js +0 -138
  100. package/cjs/controllers/user.controller.js +0 -438
  101. package/cjs/controllers/user.controller.spec.js +0 -204
  102. package/cjs/docs/auth-swagger.config.js +0 -461
  103. package/cjs/docs/auth-swagger.config.spec.js +0 -130
  104. package/cjs/docs/index.js +0 -18
  105. package/cjs/dtos/authentication.dto.js +0 -755
  106. package/cjs/dtos/company-branch.dto.js +0 -294
  107. package/cjs/dtos/company.dto.js +0 -298
  108. package/cjs/dtos/index.js +0 -23
  109. package/cjs/dtos/social-auth.dto.js +0 -318
  110. package/cjs/dtos/user-permission.dto.js +0 -358
  111. package/cjs/dtos/user.dto.js +0 -413
  112. package/cjs/entities/app-user.entity.js +0 -25
  113. package/cjs/entities/company-branch.entity.js +0 -163
  114. package/cjs/entities/company.entity.js +0 -146
  115. package/cjs/entities/index.js +0 -67
  116. package/cjs/entities/index.spec.js +0 -84
  117. package/cjs/entities/pending-registration.entity.js +0 -135
  118. package/cjs/entities/social-auth-config.entity.js +0 -102
  119. package/cjs/entities/user-company-permission.entity.js +0 -153
  120. package/cjs/entities/user-token.entity.js +0 -120
  121. package/cjs/enums/index.js +0 -19
  122. package/cjs/enums/social-provider-type.enum.js +0 -17
  123. package/cjs/enums/user-org-permission-type.enum.js +0 -15
  124. package/cjs/helpers/auth-response.mapper.js +0 -46
  125. package/cjs/helpers/auth-response.mapper.spec.js +0 -139
  126. package/cjs/helpers/index.js +0 -19
  127. package/cjs/helpers/token.helper.js +0 -58
  128. package/cjs/helpers/token.helper.spec.js +0 -86
  129. package/cjs/index.js +0 -30
  130. package/cjs/interceptors/clear-token.interceptor.js +0 -73
  131. package/cjs/interceptors/clear-token.interceptor.spec.js +0 -107
  132. package/cjs/interceptors/index.js +0 -19
  133. package/cjs/interceptors/set-token.interceptor.js +0 -107
  134. package/cjs/interceptors/set-token.interceptor.spec.js +0 -165
  135. package/cjs/interfaces/auth-email-provider.interface.js +0 -45
  136. package/cjs/interfaces/auth-module-options.interface.js +0 -4
  137. package/cjs/interfaces/authentication.interface.js +0 -4
  138. package/cjs/interfaces/company-branch.interface.js +0 -4
  139. package/cjs/interfaces/company.interface.js +0 -4
  140. package/cjs/interfaces/index.js +0 -25
  141. package/cjs/interfaces/social-auth.interface.js +0 -4
  142. package/cjs/interfaces/user-enricher.interface.js +0 -4
  143. package/cjs/interfaces/user.interface.js +0 -4
  144. package/cjs/modules/auth.module.js +0 -208
  145. package/cjs/modules/auth.module.spec.js +0 -258
  146. package/cjs/modules/index.js +0 -18
  147. package/cjs/providers/facebook.social-provider.js +0 -73
  148. package/cjs/providers/google.social-provider.js +0 -68
  149. package/cjs/providers/index.js +0 -18
  150. package/cjs/providers/linkedin.social-provider.js +0 -66
  151. package/cjs/providers/microsoft.social-provider.js +0 -78
  152. package/cjs/providers/oauth-http.util.js +0 -107
  153. package/cjs/providers/social-provider.registry.js +0 -24
  154. package/cjs/providers/social-provider.registry.spec.js +0 -135
  155. package/cjs/services/auth-config.service.js +0 -113
  156. package/cjs/services/auth-config.service.spec.js +0 -100
  157. package/cjs/services/auth-datasource.provider.js +0 -138
  158. package/cjs/services/auth-datasource.provider.spec.js +0 -191
  159. package/cjs/services/auth-email.service.js +0 -539
  160. package/cjs/services/auth-email.service.spec.js +0 -456
  161. package/cjs/services/authentication.service.js +0 -1203
  162. package/cjs/services/authentication.service.spec.js +0 -1020
  163. package/cjs/services/branch.service.js +0 -153
  164. package/cjs/services/branch.service.spec.js +0 -169
  165. package/cjs/services/company-selection-session.service.js +0 -121
  166. package/cjs/services/company-selection-session.service.spec.js +0 -90
  167. package/cjs/services/company.service.js +0 -140
  168. package/cjs/services/company.service.spec.js +0 -127
  169. package/cjs/services/index.js +0 -28
  170. package/cjs/services/social-auth-config.service.js +0 -103
  171. package/cjs/services/social-auth-config.service.spec.js +0 -71
  172. package/cjs/services/social-auth.service.js +0 -310
  173. package/cjs/services/social-auth.service.spec.js +0 -310
  174. package/cjs/services/user-permission.service.js +0 -236
  175. package/cjs/services/user-permission.service.spec.js +0 -254
  176. package/cjs/services/user.service.js +0 -671
  177. package/cjs/services/user.service.spec.js +0 -718
  178. package/cjs/strategies/jwt.strategy.js +0 -140
  179. package/cjs/strategies/jwt.strategy.spec.js +0 -166
  180. package/cjs/validators/password.validator.js +0 -45
  181. package/cjs/validators/password.validator.spec.js +0 -161
  182. package/fesm/config/auth.constants.js +0 -14
  183. package/fesm/config/event-actions.js +0 -26
  184. package/fesm/config/message-keys.js +0 -99
  185. package/fesm/controllers/authentication.controller.js +0 -417
  186. package/fesm/controllers/authentication.controller.spec.js +0 -215
  187. package/fesm/controllers/branch.controller.js +0 -92
  188. package/fesm/controllers/branch.controller.spec.js +0 -130
  189. package/fesm/controllers/company-selection.controller.js +0 -188
  190. package/fesm/controllers/company-selection.controller.spec.js +0 -80
  191. package/fesm/controllers/company.controller.js +0 -92
  192. package/fesm/controllers/company.controller.spec.js +0 -127
  193. package/fesm/controllers/email-verification.controller.js +0 -214
  194. package/fesm/controllers/email-verification.controller.spec.js +0 -138
  195. package/fesm/controllers/social-auth-config.controller.js +0 -97
  196. package/fesm/controllers/social-auth.controller.js +0 -165
  197. package/fesm/controllers/social-auth.controller.spec.js +0 -75
  198. package/fesm/controllers/user-permission.controller.js +0 -213
  199. package/fesm/controllers/user-permission.controller.spec.js +0 -134
  200. package/fesm/controllers/user.controller.js +0 -428
  201. package/fesm/controllers/user.controller.spec.js +0 -200
  202. package/fesm/docs/auth-swagger.config.js +0 -454
  203. package/fesm/docs/auth-swagger.config.spec.js +0 -126
  204. package/fesm/dtos/authentication.dto.js +0 -683
  205. package/fesm/dtos/company-branch.dto.js +0 -279
  206. package/fesm/dtos/company.dto.js +0 -283
  207. package/fesm/dtos/social-auth.dto.js +0 -282
  208. package/fesm/dtos/user-permission.dto.js +0 -339
  209. package/fesm/dtos/user.dto.js +0 -391
  210. package/fesm/entities/app-user.entity.js +0 -15
  211. package/fesm/entities/company-branch.entity.js +0 -153
  212. package/fesm/entities/company.entity.js +0 -136
  213. package/fesm/entities/index.spec.js +0 -80
  214. package/fesm/entities/pending-registration.entity.js +0 -125
  215. package/fesm/entities/social-auth-config.entity.js +0 -92
  216. package/fesm/entities/user-company-permission.entity.js +0 -136
  217. package/fesm/entities/user-token.entity.js +0 -104
  218. package/fesm/enums/social-provider-type.enum.js +0 -7
  219. package/fesm/enums/user-org-permission-type.enum.js +0 -5
  220. package/fesm/helpers/auth-response.mapper.js +0 -25
  221. package/fesm/helpers/auth-response.mapper.spec.js +0 -135
  222. package/fesm/helpers/token.helper.js +0 -40
  223. package/fesm/helpers/token.helper.spec.js +0 -82
  224. package/fesm/interceptors/clear-token.interceptor.js +0 -63
  225. package/fesm/interceptors/clear-token.interceptor.spec.js +0 -103
  226. package/fesm/interceptors/set-token.interceptor.js +0 -98
  227. package/fesm/interceptors/set-token.interceptor.spec.js +0 -161
  228. package/fesm/interfaces/auth-email-provider.interface.js +0 -38
  229. package/fesm/interfaces/auth-module-options.interface.js +0 -3
  230. package/fesm/interfaces/authentication.interface.js +0 -1
  231. package/fesm/interfaces/company-branch.interface.js +0 -1
  232. package/fesm/interfaces/company.interface.js +0 -1
  233. package/fesm/interfaces/social-auth.interface.js +0 -1
  234. package/fesm/interfaces/user-enricher.interface.js +0 -4
  235. package/fesm/interfaces/user.interface.js +0 -1
  236. package/fesm/modules/auth.module.js +0 -198
  237. package/fesm/modules/auth.module.spec.js +0 -254
  238. package/fesm/providers/facebook.social-provider.js +0 -63
  239. package/fesm/providers/google.social-provider.js +0 -58
  240. package/fesm/providers/index.js +0 -1
  241. package/fesm/providers/linkedin.social-provider.js +0 -56
  242. package/fesm/providers/microsoft.social-provider.js +0 -68
  243. package/fesm/providers/oauth-http.util.js +0 -77
  244. package/fesm/providers/social-provider.registry.js +0 -14
  245. package/fesm/providers/social-provider.registry.spec.js +0 -131
  246. package/fesm/services/auth-config.service.js +0 -103
  247. package/fesm/services/auth-config.service.spec.js +0 -96
  248. package/fesm/services/auth-datasource.provider.js +0 -87
  249. package/fesm/services/auth-datasource.provider.spec.js +0 -187
  250. package/fesm/services/auth-email.service.js +0 -488
  251. package/fesm/services/auth-email.service.spec.js +0 -411
  252. package/fesm/services/authentication.service.js +0 -1152
  253. package/fesm/services/authentication.service.spec.js +0 -975
  254. package/fesm/services/branch.service.js +0 -143
  255. package/fesm/services/branch.service.spec.js +0 -165
  256. package/fesm/services/company-selection-session.service.js +0 -111
  257. package/fesm/services/company-selection-session.service.spec.js +0 -86
  258. package/fesm/services/company.service.js +0 -130
  259. package/fesm/services/company.service.spec.js +0 -123
  260. package/fesm/services/social-auth-config.service.js +0 -93
  261. package/fesm/services/social-auth-config.service.spec.js +0 -67
  262. package/fesm/services/social-auth.service.js +0 -300
  263. package/fesm/services/social-auth.service.spec.js +0 -265
  264. package/fesm/services/user-permission.service.js +0 -226
  265. package/fesm/services/user-permission.service.spec.js +0 -250
  266. package/fesm/services/user.service.js +0 -620
  267. package/fesm/services/user.service.spec.js +0 -673
  268. package/fesm/strategies/jwt.strategy.js +0 -130
  269. package/fesm/strategies/jwt.strategy.spec.js +0 -162
  270. package/fesm/validators/password.validator.js +0 -48
  271. package/fesm/validators/password.validator.spec.js +0 -157
package/fesm/24.js ADDED
@@ -0,0 +1,4422 @@
1
+ import * as __rspack_external__flusys_nestjs_shared_classes_6076a329 from "@flusys/nestjs-shared/classes";
2
+ import * as __rspack_external__flusys_nestjs_shared_constants_81f33d5b from "@flusys/nestjs-shared/constants";
3
+ import * as __rspack_external__flusys_nestjs_shared_interfaces_413f2706 from "@flusys/nestjs-shared/interfaces";
4
+ import * as __rspack_external__flusys_nestjs_shared_modules_24702bee from "@flusys/nestjs-shared/modules";
5
+ import * as __rspack_external__flusys_nestjs_shared_utils_9125c1f1 from "@flusys/nestjs-shared/utils";
6
+ import * as __rspack_external__nestjs_common_a04939da from "@nestjs/common";
7
+ import * as __rspack_external__nestjs_core_d7b00a1a from "@nestjs/core";
8
+ import * as __rspack_external__nestjs_jwt_50c0e0ae from "@nestjs/jwt";
9
+ import * as __rspack_external_bcrypt from "bcrypt";
10
+ import * as __rspack_external_crypto from "crypto";
11
+ import * as __rspack_external__flusys_nestjs_core_config_197fa0a9 from "@flusys/nestjs-core/config";
12
+ import * as __rspack_external__flusys_nestjs_shared_enums_327421f8 from "@flusys/nestjs-shared/enums";
13
+ export const __rspack_esm_id = 24;
14
+ export const __rspack_esm_ids = [24];
15
+ export const __webpack_modules__ = {
16
+ 5588(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
17
+ // Injection Tokens
18
+ const AUTH_MODULE_OPTIONS = 'AUTH_MODULE_OPTIONS';
19
+ const USER_ENRICHER = 'USER_ENRICHER';
20
+ // Security
21
+ const BCRYPT_SALT_ROUNDS = 12;
22
+ // Cookie
23
+ const DEFAULT_COOKIE_NAME = 'fsn_refresh_token';
24
+ const MAX_COOKIE_BYTES = 3500;
25
+ // Cache Key Prefixes
26
+ const SESSION_CACHE_PREFIX = 'auth:session';
27
+ const TOKEN_REVOKED_PREFIX = 'auth:revoked';
28
+ const SOCIAL_STATE_PREFIX = 'auth:social:state';
29
+ // Social Login
30
+ const SOCIAL_STATE_TTL_MS = 10 * 60 * 1000; // 10 minutes
31
+
32
+ __webpack_require__.d(__webpack_exports__, {
33
+ }, {
34
+ EV: TOKEN_REVOKED_PREFIX,
35
+ PR: SOCIAL_STATE_PREFIX,
36
+ Vl: SESSION_CACHE_PREFIX,
37
+ jt: USER_ENRICHER,
38
+ rv: DEFAULT_COOKIE_NAME,
39
+ xe: AUTH_MODULE_OPTIONS
40
+ });
41
+
42
+
43
+ },
44
+ 7987(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
45
+ /**
46
+ * Domain event actions published by the auth module, alongside the CRUD
47
+ * lifecycle actions every ApiService emits.
48
+ */ const AUTH_EVENT_ACTIONS = {
49
+ LOGGED_IN: 'logged-in',
50
+ LOGGED_OUT: 'logged-out',
51
+ TOKEN_REFRESHED: 'token-refreshed',
52
+ COMPANY_SWITCHED: 'company-switched',
53
+ REGISTERED: 'registered',
54
+ PASSWORD_CHANGED: 'password-changed',
55
+ PASSWORD_RESET_REQUESTED: 'password-reset-requested',
56
+ PASSWORD_RESET: 'password-reset',
57
+ EMAIL_VERIFIED: 'email-verified',
58
+ PERMISSION_GRANTED: 'permission-granted',
59
+ PERMISSION_REVOKED: 'permission-revoked',
60
+ SOCIAL_LOGGED_IN: 'social-logged-in'
61
+ };
62
+ /** Every entity the auth module publishes under, ApiService backed or not */ const AUTH_EVENT_ENTITIES = {
63
+ USER: 'appuser',
64
+ COMPANY: 'company',
65
+ COMPANY_BRANCH: 'company_branch',
66
+ SESSION: 'session',
67
+ USER_PERMISSION: 'user_company_permission',
68
+ SOCIAL_AUTH_CONFIG: 'social_auth_config'
69
+ };
70
+ const AUTH_EVENT_MODULE = 'auth';
71
+
72
+ __webpack_require__.d(__webpack_exports__, {
73
+ }, {
74
+ g: AUTH_EVENT_ENTITIES,
75
+ o: AUTH_EVENT_ACTIONS
76
+ });
77
+
78
+
79
+ },
80
+ 5363(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
81
+ // ==================== AUTH MODULE MESSAGE KEYS ====================
82
+ const AUTH_MESSAGES = {
83
+ LOGIN_SUCCESS: 'auth.login.success',
84
+ LOGIN_REQUIRES_SELECTION: 'auth.login.requires.selection',
85
+ LOGIN_INVALID_CREDENTIALS: 'auth.login.invalid.credentials',
86
+ LOGIN_EMAIL_NOT_VERIFIED: 'auth.login.email.not.verified',
87
+ LOGIN_ACCOUNT_DEACTIVATED: 'auth.login.account.deactivated',
88
+ LOGOUT_SUCCESS: 'auth.logout.success',
89
+ REGISTER_SUCCESS: 'auth.register.success',
90
+ REGISTER_FAILED: 'auth.register.failed',
91
+ REFRESH_SUCCESS: 'auth.refresh.success',
92
+ ME_SUCCESS: 'auth.me.success',
93
+ SELECT_SUCCESS: 'auth.select.success',
94
+ SWITCH_COMPANY_SUCCESS: 'auth.switch.company.success',
95
+ REGISTER_EMAIL_EXISTS: 'auth.register.email.exists',
96
+ REGISTER_ACCOUNT_DELETED: 'auth.register.account.deleted',
97
+ REGISTER_COMPANY_ALREADY_ASSIGNED: 'auth.register.company.already.assigned',
98
+ REGISTER_SIGNUP_DISABLED: 'auth.register.signup.disabled',
99
+ PASSWORD_CHANGE_SUCCESS: 'auth.password.change.success',
100
+ PASSWORD_CHANGE_INVALID_CURRENT: 'auth.password.change.invalid.current',
101
+ PASSWORD_CHANGE_CURRENT_REQUIRED: 'auth.password.change.current.required',
102
+ PASSWORD_RESET_EMAIL_SENT: 'auth.password.reset.email.sent',
103
+ PASSWORD_RESET_SUCCESS: 'auth.password.reset.success',
104
+ TOKEN_REQUIRED: 'auth.token.required',
105
+ TOKEN_INVALID: 'auth.token.invalid',
106
+ TOKEN_EXPIRED: 'auth.token.expired',
107
+ TOKEN_REVOKED: 'auth.token.revoked',
108
+ TOKEN_TOO_LARGE: 'auth.token.too.large',
109
+ COMPANY_LIST_SUCCESS: 'auth.company.list.success',
110
+ COMPANY_NO_ACCESS: 'auth.company.no.access',
111
+ COMPANY_NOT_FOUND: 'auth.company.not.found',
112
+ COMPANY_REQUIRED: 'auth.company.required',
113
+ COMPANY_FEATURE_NOT_ENABLED: 'auth.company.feature.not.enabled',
114
+ BRANCH_LIST_SUCCESS: 'auth.branch.list.success',
115
+ BRANCH_NO_ACCESS: 'auth.branch.no.access',
116
+ BRANCH_NOT_FOUND: 'auth.branch.not.found',
117
+ EMAIL_NOT_CONFIGURED: 'auth.email.not.configured',
118
+ EMAIL_SEND_FAILED: 'auth.email.send.failed',
119
+ SESSION_INVALID: 'auth.session.invalid',
120
+ SESSION_NOT_AVAILABLE: 'auth.session.not.available',
121
+ PROFILE_ACCESS_DENIED: 'auth.profile.access.denied',
122
+ PROFILE_SECTIONS_NOT_SUPPORTED: 'auth.profile.sections.not.supported',
123
+ LOGOUT_SERVICE_UNAVAILABLE: 'auth.logout.service.unavailable',
124
+ PASSWORD_RESET_TOKEN_EXPIRED: 'auth.password.reset.token.expired',
125
+ PASSWORD_RESET_TOKEN_USED: 'auth.password.reset.token.used'
126
+ };
127
+ const EMAIL_VERIFICATION_MESSAGES = {
128
+ VERIFICATION_SENT: 'email.verification.sent',
129
+ VERIFICATION_SUCCESS: 'email.verification.success',
130
+ VERIFICATION_TOKEN_INVALID: 'email.verification.token.invalid',
131
+ VERIFICATION_TOKEN_EXPIRED: 'email.verification.token.expired',
132
+ VERIFICATION_NOT_ENABLED: 'email.verification.not.enabled',
133
+ RESEND_SUCCESS: 'email.verification.resend.success'
134
+ };
135
+ const SOCIAL_AUTH_MESSAGES = {
136
+ PROVIDERS_SUCCESS: 'auth.social.providers.success',
137
+ AUTHORIZE_SUCCESS: 'auth.social.authorize.success',
138
+ LOGIN_SUCCESS: 'auth.social.login.success',
139
+ PROVIDER_DISABLED: 'auth.social.provider.disabled',
140
+ PROVIDER_NOT_CONFIGURED: 'auth.social.provider.not.configured',
141
+ STATE_INVALID: 'auth.social.state.invalid',
142
+ REDIRECT_URI_MISMATCH: 'auth.social.redirect.uri.mismatch',
143
+ EXCHANGE_FAILED: 'auth.social.exchange.failed',
144
+ PROFILE_INCOMPLETE: 'auth.social.profile.incomplete',
145
+ ACCOUNT_NOT_LINKED: 'auth.social.account.not.linked',
146
+ COMPANY_REQUIRED: 'auth.social.company.required',
147
+ EMAIL_REQUIRED: 'auth.social.email.required',
148
+ EMAIL_NOT_VERIFIED: 'auth.social.email.not.verified',
149
+ ACCOUNT_DELETED: 'auth.social.account.deleted'
150
+ };
151
+ const SOCIAL_AUTH_CONFIG_MESSAGES = {
152
+ PROVIDER_ALREADY_CONFIGURED: 'social.config.provider.already.configured'
153
+ };
154
+ const USER_MESSAGES = {
155
+ NOT_FOUND: 'user.not.found',
156
+ PROFILE_UPDATE_SUCCESS: 'user.profile.update.success',
157
+ PROFILE_EXTRAS_SUCCESS: 'user.profile.extras.success',
158
+ PROFILE_SECTIONS_SUCCESS: 'user.profile.sections.success',
159
+ PROFILE_SECTION_DATA_SUCCESS: 'user.profile.section.data.success',
160
+ PROFILE_SECTION_UPDATE_SUCCESS: 'user.profile.section.update.success',
161
+ PROFILE_COMPLETION_SUCCESS: 'user.profile.completion.success',
162
+ EMAIL_VERIFY_SUCCESS: 'user.email.verify.success',
163
+ PHONE_VERIFY_SUCCESS: 'user.phone.verify.success',
164
+ STATUS_UPDATE_SUCCESS: 'user.status.update.success',
165
+ LOOKUP_SUCCESS: 'user.lookup.success'
166
+ };
167
+ const COMPANY_MESSAGES = {
168
+ READONLY_DELETE_FORBIDDEN: 'company.readonly.delete.forbidden'
169
+ };
170
+ const BRANCH_MESSAGES = {
171
+ READONLY_DELETE_FORBIDDEN: 'branch.readonly.delete.forbidden'
172
+ };
173
+ const USER_PERMISSION_MESSAGES = {
174
+ COMPANY_LIST_SUCCESS: 'user.permission.company.list.success',
175
+ BRANCH_LIST_SUCCESS: 'user.permission.branch.list.success',
176
+ COMPANY_USERS_SUCCESS: 'user.permission.company.users.success',
177
+ BRANCH_USERS_SUCCESS: 'user.permission.branch.users.success',
178
+ BATCH_SUCCESS: 'user.permission.batch.success',
179
+ ALREADY_ASSIGNED: 'user.permission.already.assigned',
180
+ PERMISSION_NOT_FOUND: 'user.permission.not.found',
181
+ COMPANY_NO_ACCESS: 'user.permission.company.no.access',
182
+ BRANCH_NO_ACCESS: 'user.permission.branch.no.access'
183
+ };
184
+
185
+ __webpack_require__.d(__webpack_exports__, {
186
+ }, {
187
+ HZ: SOCIAL_AUTH_CONFIG_MESSAGES,
188
+ OF: SOCIAL_AUTH_MESSAGES,
189
+ W1: BRANCH_MESSAGES,
190
+ hg: COMPANY_MESSAGES,
191
+ jz: USER_PERMISSION_MESSAGES,
192
+ mK: AUTH_MESSAGES,
193
+ ny: USER_MESSAGES,
194
+ sv: EMAIL_VERIFICATION_MESSAGES
195
+ });
196
+
197
+
198
+ },
199
+ 2295(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
200
+ function toUserInfo(user) {
201
+ return {
202
+ id: user.id,
203
+ email: user.email,
204
+ name: user.name ?? undefined,
205
+ phone: user.phone ?? null,
206
+ profilePictureId: user.profilePictureId ?? null
207
+ };
208
+ }
209
+ function toCompanyInfo(company) {
210
+ return {
211
+ id: company.id,
212
+ name: company.name,
213
+ slug: company.slug,
214
+ logoId: company.logoId ?? null
215
+ };
216
+ }
217
+ function toBranchInfo(branch) {
218
+ return {
219
+ id: branch.id,
220
+ name: branch.name,
221
+ slug: branch.slug,
222
+ logoId: branch.logoId ?? null
223
+ };
224
+ }
225
+
226
+ __webpack_require__.d(__webpack_exports__, {
227
+ $C: () => (toCompanyInfo),
228
+ FV: () => (toUserInfo),
229
+ QH: () => (toBranchInfo)
230
+ });
231
+
232
+
233
+ },
234
+ 1379(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
235
+ function generateTokens(jwtService, authConfig, payload) {
236
+ const accessToken = jwtService.sign({
237
+ ...payload,
238
+ type: 'access'
239
+ }, {
240
+ secret: authConfig.getJwtSecret(),
241
+ expiresIn: authConfig.getJwtExpiration(),
242
+ algorithm: 'HS256'
243
+ });
244
+ const refreshToken = jwtService.sign({
245
+ ...payload,
246
+ type: 'refresh'
247
+ }, {
248
+ secret: authConfig.getRefreshTokenSecret(),
249
+ expiresIn: authConfig.getRefreshTokenExpiration(),
250
+ algorithm: 'HS256'
251
+ });
252
+ return {
253
+ accessToken,
254
+ refreshToken
255
+ };
256
+ }
257
+ function parseExpiryToMs(expiry) {
258
+ const match = expiry.match(/^(\d+)([smhd])$/);
259
+ if (!match) return 7 * 24 * 60 * 60 * 1000;
260
+ const value = parseInt(match[1], 10);
261
+ const unit = match[2];
262
+ switch(unit){
263
+ case 's':
264
+ return value * 1000;
265
+ case 'm':
266
+ return value * 60 * 1000;
267
+ case 'h':
268
+ return value * 60 * 60 * 1000;
269
+ case 'd':
270
+ return value * 24 * 60 * 60 * 1000;
271
+ default:
272
+ return 7 * 24 * 60 * 60 * 1000;
273
+ }
274
+ }
275
+
276
+ __webpack_require__.d(__webpack_exports__, {
277
+ e: () => (generateTokens),
278
+ o: () => (parseExpiryToMs)
279
+ });
280
+
281
+
282
+ },
283
+ 9125(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
284
+ /**
285
+ * Auth Email Provider Interface
286
+ *
287
+ * This interface defines the contract for email sending in the auth module.
288
+ * It allows auth to work independently of the email module.
289
+ *
290
+ * To use email features in auth:
291
+ * 1. Provide AUTH_EMAIL_PROVIDER in your app module
292
+ * 2. Implement IAuthEmailProvider using EmailSendService from nestjs-email
293
+ *
294
+ * @example
295
+ * ```typescript
296
+ * // In app.module.ts or a provider file
297
+ * {
298
+ * provide: AUTH_EMAIL_PROVIDER,
299
+ * useFactory: (emailSendService: EmailSendService) => ({
300
+ * sendPasswordResetEmail: async (email, token, resetUrl) => {
301
+ * await emailSendService.sendTemplateEmail({
302
+ * templateSlug: 'password-reset',
303
+ * to: email,
304
+ * variables: { resetUrl, token },
305
+ * });
306
+ * },
307
+ * sendVerificationEmail: async (email, token, verifyUrl) => {
308
+ * await emailSendService.sendTemplateEmail({
309
+ * templateSlug: 'email-verification',
310
+ * to: email,
311
+ * variables: { verifyUrl, token },
312
+ * });
313
+ * },
314
+ * }),
315
+ * inject: [EmailSendService],
316
+ * }
317
+ * ```
318
+ */ /**
319
+ * Injection token for auth email provider
320
+ * Use this to provide the email implementation
321
+ */ const AUTH_EMAIL_PROVIDER = 'AUTH_EMAIL_PROVIDER';
322
+
323
+ __webpack_require__.d(__webpack_exports__, {
324
+ }, {
325
+ C: AUTH_EMAIL_PROVIDER
326
+ });
327
+
328
+
329
+ },
330
+ 6928(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
331
+
332
+ // EXPORTS
333
+ __webpack_require__.d(__webpack_exports__, {
334
+ V: () => (/* binding */ getSocialProvider)
335
+ });
336
+
337
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/enums/social-provider-type.enum.ts
338
+ var social_provider_type_enum = __webpack_require__(5142);
339
+ // EXTERNAL MODULE: external "@nestjs/common"
340
+ var common_ = __webpack_require__(6157);
341
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/config/message-keys.ts
342
+ var message_keys = __webpack_require__(5363);
343
+ ;// CONCATENATED MODULE: ./projects/nestjs-auth/src/providers/oauth-http.util.ts
344
+
345
+
346
+ const OAUTH_HTTP_TIMEOUT_MS = 10_000;
347
+ function failExchange(provider, detail) {
348
+ throw new common_.UnauthorizedException({
349
+ message: `Social sign-in with ${provider} failed: ${detail}`,
350
+ messageKey: message_keys/* .SOCIAL_AUTH_MESSAGES.EXCHANGE_FAILED */.OF.EXCHANGE_FAILED,
351
+ messageVariables: {
352
+ provider
353
+ }
354
+ });
355
+ }
356
+ async function fetchWithTimeout(provider, url, init) {
357
+ try {
358
+ return await fetch(url, {
359
+ ...init,
360
+ signal: AbortSignal.timeout(OAUTH_HTTP_TIMEOUT_MS)
361
+ });
362
+ } catch (error) {
363
+ if (error instanceof Error && error.name === 'TimeoutError') {
364
+ failExchange(provider, 'request timed out');
365
+ }
366
+ throw error;
367
+ }
368
+ }
369
+ async function readJson(provider, response) {
370
+ const body = await response.text();
371
+ if (!response.ok) {
372
+ failExchange(provider, `${response.status} ${body.slice(0, 200)}`);
373
+ }
374
+ try {
375
+ return JSON.parse(body);
376
+ } catch {
377
+ return failExchange(provider, 'response was not JSON');
378
+ }
379
+ }
380
+ async function postForm(provider, url, form) {
381
+ const response = await fetchWithTimeout(provider, url, {
382
+ method: 'POST',
383
+ headers: {
384
+ 'Content-Type': 'application/x-www-form-urlencoded',
385
+ Accept: 'application/json'
386
+ },
387
+ body: new URLSearchParams(form).toString()
388
+ });
389
+ return readJson(provider, response);
390
+ }
391
+ async function getJson(provider, url, accessToken) {
392
+ const response = await fetchWithTimeout(provider, url, {
393
+ headers: {
394
+ Authorization: `Bearer ${accessToken}`,
395
+ Accept: 'application/json'
396
+ }
397
+ });
398
+ return readJson(provider, response);
399
+ }
400
+ function readAccessToken(provider, token) {
401
+ const accessToken = token['access_token'];
402
+ if (typeof accessToken !== 'string' || !accessToken) {
403
+ failExchange(provider, 'no access token returned');
404
+ }
405
+ return accessToken;
406
+ }
407
+ function readString(source, key) {
408
+ const value = source[key];
409
+ return typeof value === 'string' && value ? value : null;
410
+ }
411
+ function buildQuery(params) {
412
+ const query = new URLSearchParams();
413
+ for (const [key, value] of Object.entries(params)){
414
+ if (value) query.append(key, value);
415
+ }
416
+ return query.toString();
417
+ }
418
+ function resolveScopes(credentials, defaults, separator = ' ') {
419
+ return (credentials.scopes?.length ? credentials.scopes : defaults).join(separator);
420
+ }
421
+
422
+ ;// CONCATENATED MODULE: ./projects/nestjs-auth/src/providers/facebook.social-provider.ts
423
+
424
+
425
+ const GRAPH_VERSION = 'v21.0';
426
+ const AUTHORIZE_URL = `https://www.facebook.com/${GRAPH_VERSION}/dialog/oauth`;
427
+ const TOKEN_URL = `https://graph.facebook.com/${GRAPH_VERSION}/oauth/access_token`;
428
+ const PROFILE_URL = `https://graph.facebook.com/${GRAPH_VERSION}/me?fields=id,name,email,picture.type(large)`;
429
+ function readAvatarUrl(profile) {
430
+ const picture = profile['picture'];
431
+ if (typeof picture !== 'object' || picture === null) return null;
432
+ const data = picture['data'];
433
+ if (typeof data !== 'object' || data === null) return null;
434
+ return readString(data, 'url');
435
+ }
436
+ let FacebookSocialProvider = class FacebookSocialProvider {
437
+ provider = social_provider_type_enum/* .SocialProviderTypeEnum.FACEBOOK */.u.FACEBOOK;
438
+ defaultScopes = [
439
+ 'email',
440
+ 'public_profile'
441
+ ];
442
+ buildAuthorizationUrl(credentials, state) {
443
+ const query = buildQuery({
444
+ client_id: credentials.clientId,
445
+ redirect_uri: credentials.redirectUri,
446
+ response_type: 'code',
447
+ scope: resolveScopes(credentials, this.defaultScopes, ','),
448
+ state
449
+ });
450
+ return `${AUTHORIZE_URL}?${query}`;
451
+ }
452
+ async fetchProfile(credentials, code) {
453
+ const token = await postForm(this.provider, TOKEN_URL, {
454
+ code,
455
+ client_id: credentials.clientId,
456
+ client_secret: credentials.clientSecret,
457
+ redirect_uri: credentials.redirectUri
458
+ });
459
+ const profile = await getJson(this.provider, PROFILE_URL, readAccessToken(this.provider, token));
460
+ const email = readString(profile, 'email');
461
+ return {
462
+ providerUserId: readString(profile, 'id') ?? '',
463
+ email,
464
+ emailVerified: !!email,
465
+ name: readString(profile, 'name'),
466
+ avatarUrl: readAvatarUrl(profile)
467
+ };
468
+ }
469
+ };
470
+ const facebookSocialProvider = new FacebookSocialProvider();
471
+
472
+ ;// CONCATENATED MODULE: ./projects/nestjs-auth/src/providers/google.social-provider.ts
473
+
474
+
475
+ const google_social_provider_AUTHORIZE_URL = 'https://accounts.google.com/o/oauth2/v2/auth';
476
+ const google_social_provider_TOKEN_URL = 'https://oauth2.googleapis.com/token';
477
+ const USERINFO_URL = 'https://openidconnect.googleapis.com/v1/userinfo';
478
+ let GoogleSocialProvider = class GoogleSocialProvider {
479
+ provider = social_provider_type_enum/* .SocialProviderTypeEnum.GOOGLE */.u.GOOGLE;
480
+ defaultScopes = [
481
+ 'openid',
482
+ 'email',
483
+ 'profile'
484
+ ];
485
+ buildAuthorizationUrl(credentials, state) {
486
+ const query = buildQuery({
487
+ client_id: credentials.clientId,
488
+ redirect_uri: credentials.redirectUri,
489
+ response_type: 'code',
490
+ scope: resolveScopes(credentials, this.defaultScopes),
491
+ state,
492
+ access_type: 'online',
493
+ prompt: 'select_account'
494
+ });
495
+ return `${google_social_provider_AUTHORIZE_URL}?${query}`;
496
+ }
497
+ async fetchProfile(credentials, code) {
498
+ const token = await postForm(this.provider, google_social_provider_TOKEN_URL, {
499
+ code,
500
+ client_id: credentials.clientId,
501
+ client_secret: credentials.clientSecret,
502
+ redirect_uri: credentials.redirectUri,
503
+ grant_type: 'authorization_code'
504
+ });
505
+ const profile = await getJson(this.provider, USERINFO_URL, readAccessToken(this.provider, token));
506
+ return {
507
+ providerUserId: readString(profile, 'sub') ?? '',
508
+ email: readString(profile, 'email'),
509
+ emailVerified: profile['email_verified'] === true,
510
+ name: readString(profile, 'name'),
511
+ avatarUrl: readString(profile, 'picture')
512
+ };
513
+ }
514
+ };
515
+ const googleSocialProvider = new GoogleSocialProvider();
516
+
517
+ ;// CONCATENATED MODULE: ./projects/nestjs-auth/src/providers/linkedin.social-provider.ts
518
+
519
+
520
+ const linkedin_social_provider_AUTHORIZE_URL = 'https://www.linkedin.com/oauth/v2/authorization';
521
+ const linkedin_social_provider_TOKEN_URL = 'https://www.linkedin.com/oauth/v2/accessToken';
522
+ const linkedin_social_provider_USERINFO_URL = 'https://api.linkedin.com/v2/userinfo';
523
+ let LinkedInSocialProvider = class LinkedInSocialProvider {
524
+ provider = social_provider_type_enum/* .SocialProviderTypeEnum.LINKEDIN */.u.LINKEDIN;
525
+ defaultScopes = [
526
+ 'openid',
527
+ 'profile',
528
+ 'email'
529
+ ];
530
+ buildAuthorizationUrl(credentials, state) {
531
+ const query = buildQuery({
532
+ response_type: 'code',
533
+ client_id: credentials.clientId,
534
+ redirect_uri: credentials.redirectUri,
535
+ scope: resolveScopes(credentials, this.defaultScopes),
536
+ state
537
+ });
538
+ return `${linkedin_social_provider_AUTHORIZE_URL}?${query}`;
539
+ }
540
+ async fetchProfile(credentials, code) {
541
+ const token = await postForm(this.provider, linkedin_social_provider_TOKEN_URL, {
542
+ grant_type: 'authorization_code',
543
+ code,
544
+ client_id: credentials.clientId,
545
+ client_secret: credentials.clientSecret,
546
+ redirect_uri: credentials.redirectUri
547
+ });
548
+ const profile = await getJson(this.provider, linkedin_social_provider_USERINFO_URL, readAccessToken(this.provider, token));
549
+ return {
550
+ providerUserId: readString(profile, 'sub') ?? '',
551
+ email: readString(profile, 'email'),
552
+ emailVerified: profile['email_verified'] === true,
553
+ name: readString(profile, 'name'),
554
+ avatarUrl: readString(profile, 'picture')
555
+ };
556
+ }
557
+ };
558
+ const linkedInSocialProvider = new LinkedInSocialProvider();
559
+
560
+ ;// CONCATENATED MODULE: ./projects/nestjs-auth/src/providers/microsoft.social-provider.ts
561
+
562
+
563
+ const GRAPH_ME_URL = 'https://graph.microsoft.com/v1.0/me';
564
+ const DEFAULT_TENANT = 'common';
565
+ function resolveTenant(credentials) {
566
+ const tenantId = credentials.extraConfig?.['tenantId'];
567
+ return typeof tenantId === 'string' && tenantId ? tenantId : DEFAULT_TENANT;
568
+ }
569
+ function endpoint(credentials, action) {
570
+ return `https://login.microsoftonline.com/${resolveTenant(credentials)}/oauth2/v2.0/${action}`;
571
+ }
572
+ let MicrosoftSocialProvider = class MicrosoftSocialProvider {
573
+ provider = social_provider_type_enum/* .SocialProviderTypeEnum.MICROSOFT */.u.MICROSOFT;
574
+ defaultScopes = [
575
+ 'openid',
576
+ 'profile',
577
+ 'email',
578
+ 'User.Read'
579
+ ];
580
+ buildAuthorizationUrl(credentials, state) {
581
+ const query = buildQuery({
582
+ client_id: credentials.clientId,
583
+ response_type: 'code',
584
+ redirect_uri: credentials.redirectUri,
585
+ response_mode: 'query',
586
+ scope: resolveScopes(credentials, this.defaultScopes),
587
+ state
588
+ });
589
+ return `${endpoint(credentials, 'authorize')}?${query}`;
590
+ }
591
+ async fetchProfile(credentials, code) {
592
+ const token = await postForm(this.provider, endpoint(credentials, 'token'), {
593
+ client_id: credentials.clientId,
594
+ client_secret: credentials.clientSecret,
595
+ code,
596
+ redirect_uri: credentials.redirectUri,
597
+ grant_type: 'authorization_code',
598
+ scope: resolveScopes(credentials, this.defaultScopes)
599
+ });
600
+ const profile = await getJson(this.provider, GRAPH_ME_URL, readAccessToken(this.provider, token));
601
+ // `mail` is Microsoft's confirmed mailbox claim; `userPrincipalName` is a sign-in
602
+ // identifier that is not guaranteed to be a verified, owned mailbox address.
603
+ const verifiedEmail = readString(profile, 'mail');
604
+ return {
605
+ providerUserId: readString(profile, 'id') ?? '',
606
+ email: verifiedEmail ?? readString(profile, 'userPrincipalName'),
607
+ emailVerified: !!verifiedEmail,
608
+ name: readString(profile, 'displayName'),
609
+ avatarUrl: null
610
+ };
611
+ }
612
+ };
613
+ const microsoftSocialProvider = new MicrosoftSocialProvider();
614
+
615
+ ;// CONCATENATED MODULE: ./projects/nestjs-auth/src/providers/social-provider.registry.ts
616
+
617
+
618
+
619
+
620
+
621
+ const PROVIDERS = {
622
+ [social_provider_type_enum/* .SocialProviderTypeEnum.GOOGLE */.u.GOOGLE]: googleSocialProvider,
623
+ [social_provider_type_enum/* .SocialProviderTypeEnum.FACEBOOK */.u.FACEBOOK]: facebookSocialProvider,
624
+ [social_provider_type_enum/* .SocialProviderTypeEnum.LINKEDIN */.u.LINKEDIN]: linkedInSocialProvider,
625
+ [social_provider_type_enum/* .SocialProviderTypeEnum.MICROSOFT */.u.MICROSOFT]: microsoftSocialProvider
626
+ };
627
+ function getSocialProvider(provider) {
628
+ return PROVIDERS[provider];
629
+ }
630
+
631
+
632
+ },
633
+ 6514(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
634
+
635
+ // EXPORTS
636
+ __webpack_require__.d(__webpack_exports__, {
637
+ W: () => (/* binding */ AuthConfigService)
638
+ });
639
+
640
+ ;// CONCATENATED MODULE: external "@flusys/nestjs-core/config"
641
+
642
+ // EXTERNAL MODULE: external "@flusys/nestjs-shared/constants"
643
+ var constants_ = __webpack_require__(9140);
644
+ // EXTERNAL MODULE: external "@nestjs/common"
645
+ var common_ = __webpack_require__(6157);
646
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/config/auth.constants.ts
647
+ var auth_constants = __webpack_require__(5588);
648
+ ;// CONCATENATED MODULE: ./projects/nestjs-auth/src/services/auth-config.service.ts
649
+ function _ts_decorate(decorators, target, key, desc) {
650
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
651
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
652
+ r = Reflect.decorate(decorators, target, key, desc);
653
+ } else {
654
+ for(var i = decorators.length - 1; i >= 0; i--){
655
+ if (d = decorators[i]) {
656
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
657
+ }
658
+ }
659
+ }
660
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
661
+ }
662
+ function _ts_metadata(metadataKey, metadataValue) {
663
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
664
+ return Reflect.metadata(metadataKey, metadataValue);
665
+ }
666
+ }
667
+ function _ts_param(paramIndex, decorator) {
668
+ return function(target, key) {
669
+ decorator(target, key, paramIndex);
670
+ };
671
+ }
672
+
673
+
674
+
675
+
676
+ class AuthConfigService {
677
+ options;
678
+ config;
679
+ constructor(injectedOptions){
680
+ this.options = injectedOptions ?? {
681
+ global: false,
682
+ includeController: true
683
+ };
684
+ this.config = this.options.config ?? {};
685
+ }
686
+ // Database Mode (required by IModuleConfigService)
687
+ getDatabaseMode() {
688
+ return this.options.bootstrapAppConfig?.databaseMode ?? 'single';
689
+ }
690
+ isMultiTenant() {
691
+ return this.getDatabaseMode() === 'multi-tenant';
692
+ }
693
+ // Feature Flags
694
+ isCompanyFeatureEnabled() {
695
+ return this.options.bootstrapAppConfig?.enableCompanyFeature ?? false;
696
+ }
697
+ isEmailVerificationEnabled() {
698
+ return this.options.bootstrapAppConfig?.enableEmailVerification ?? true;
699
+ }
700
+ isSignUpEnabled() {
701
+ return this.options.bootstrapAppConfig?.enableSignUp ?? true;
702
+ }
703
+ isPermissionModeFound() {
704
+ return this.options.bootstrapAppConfig?.permissionMode !== undefined;
705
+ }
706
+ // JWT Configuration
707
+ getJwtSecret() {
708
+ if (!this.config.jwtSecret) {
709
+ throw new common_.InternalServerErrorException({
710
+ message: '[AuthModule] JWT_SECRET is required - set via environment or module config',
711
+ messageKey: constants_.SYSTEM_MESSAGES.CONFIG_REQUIRED
712
+ });
713
+ }
714
+ return this.config.jwtSecret;
715
+ }
716
+ getJwtExpiration() {
717
+ return this.config.jwtExpiration ?? '1h';
718
+ }
719
+ getRefreshTokenSecret() {
720
+ if (this.config.refreshTokenSecret) {
721
+ return this.config.refreshTokenSecret;
722
+ }
723
+ if (__rspack_external__flusys_nestjs_core_config_197fa0a9.envConfig.isProduction()) {
724
+ throw new common_.InternalServerErrorException({
725
+ message: '[AuthModule] REFRESH_TOKEN_SECRET is required in production - using the same secret for access and refresh tokens is a security risk',
726
+ messageKey: constants_.SYSTEM_MESSAGES.CONFIG_REQUIRED
727
+ });
728
+ }
729
+ return this.getJwtSecret();
730
+ }
731
+ getRefreshTokenExpiration() {
732
+ return this.config.refreshTokenExpiration ?? '7d';
733
+ }
734
+ getRefreshTokenCookieName() {
735
+ return this.config.refreshTokenCookieName ?? 'fsn_refresh_token';
736
+ }
737
+ }
738
+ AuthConfigService = _ts_decorate([
739
+ (0,common_.Injectable)(),
740
+ _ts_param(0, (0,common_.Optional)()),
741
+ _ts_param(0, (0,common_.Inject)(auth_constants/* .AUTH_MODULE_OPTIONS */.xe)),
742
+ _ts_metadata("design:type", Function),
743
+ _ts_metadata("design:paramtypes", [
744
+ typeof AuthModuleOptions === "undefined" ? Object : AuthModuleOptions
745
+ ])
746
+ ], AuthConfigService);
747
+
748
+
749
+ },
750
+ 2732(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
751
+ /* import */ var _flusys_nestjs_shared__rspack_import_0 = __webpack_require__(3422);
752
+ /* import */ var _nestjs_common__rspack_import_1 = __webpack_require__(6157);
753
+ /* import */ var _nestjs_core__rspack_import_2 = __webpack_require__(3075);
754
+ /* import */ var _config_auth_constants_js__rspack_import_3 = __webpack_require__(5588);
755
+ function _ts_decorate(decorators, target, key, desc) {
756
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
757
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
758
+ r = Reflect.decorate(decorators, target, key, desc);
759
+ } else {
760
+ for(var i = decorators.length - 1; i >= 0; i--){
761
+ if (d = decorators[i]) {
762
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
763
+ }
764
+ }
765
+ }
766
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
767
+ }
768
+ function _ts_metadata(metadataKey, metadataValue) {
769
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
770
+ return Reflect.metadata(metadataKey, metadataValue);
771
+ }
772
+ }
773
+ function _ts_param(paramIndex, decorator) {
774
+ return function(target, key) {
775
+ decorator(target, key, paramIndex);
776
+ };
777
+ }
778
+
779
+
780
+
781
+
782
+ class AuthDataSourceProvider extends _flusys_nestjs_shared__rspack_import_0.MultiTenantDataSourceService {
783
+ authOptions;
784
+ static tenantConnections = new Map();
785
+ static singleDataSource = null;
786
+ static tenantsRegistry = new Map();
787
+ static initialized = false;
788
+ static connectionLocks = new Map();
789
+ static singleConnectionLock = null;
790
+ constructor(authOptions, request){
791
+ super(AuthDataSourceProvider.buildParentOptions(authOptions), request), this.authOptions = authOptions;
792
+ }
793
+ static buildParentOptions(options) {
794
+ return {
795
+ bootstrapAppConfig: options.bootstrapAppConfig,
796
+ defaultDatabaseConfig: options.config?.defaultDatabaseConfig,
797
+ tenantDefaultDatabaseConfig: options.config?.tenantDefaultDatabaseConfig,
798
+ tenants: options.config?.tenants
799
+ };
800
+ }
801
+ isCompanyFeatureEnabled(tenant) {
802
+ const effectiveTenant = tenant ?? this.getCurrentTenant();
803
+ return effectiveTenant?.enableCompanyFeature ?? this.authOptions.bootstrapAppConfig?.enableCompanyFeature ?? false;
804
+ }
805
+ isEmailVerificationEnabled(tenant) {
806
+ const effectiveTenant = tenant ?? this.getCurrentTenant();
807
+ return effectiveTenant?.enableEmailVerification ?? this.authOptions.bootstrapAppConfig?.enableEmailVerification ?? true;
808
+ }
809
+ isSignUpEnabled(tenant) {
810
+ const effectiveTenant = tenant ?? this.getCurrentTenant();
811
+ return effectiveTenant?.enableSignUp ?? this.authOptions.bootstrapAppConfig?.enableSignUp ?? true;
812
+ }
813
+ async getAuthEntities() {
814
+ const { getAuthEntitiesByConfig } = await __webpack_require__.e(/* import() */ 117).then(__webpack_require__.bind(__webpack_require__, 5180));
815
+ return getAuthEntitiesByConfig({
816
+ enableCompanyFeature: this.isCompanyFeatureEnabled(),
817
+ enableEmailVerification: this.isEmailVerificationEnabled()
818
+ });
819
+ }
820
+ async createDataSourceFromConfig(config) {
821
+ return super.createDataSourceFromConfig(config, await this.getAuthEntities());
822
+ }
823
+ }
824
+ AuthDataSourceProvider = _ts_decorate([
825
+ (0,_nestjs_common__rspack_import_1.Injectable)({
826
+ scope: _nestjs_common__rspack_import_1.Scope.REQUEST
827
+ }),
828
+ _ts_param(0, (0,_nestjs_common__rspack_import_1.Inject)(_config_auth_constants_js__rspack_import_3/* .AUTH_MODULE_OPTIONS */.xe)),
829
+ _ts_param(1, (0,_nestjs_common__rspack_import_1.Optional)()),
830
+ _ts_param(1, (0,_nestjs_common__rspack_import_1.Inject)(_nestjs_core__rspack_import_2.REQUEST)),
831
+ _ts_metadata("design:type", Function),
832
+ _ts_metadata("design:paramtypes", [
833
+ typeof AuthModuleOptions === "undefined" ? Object : AuthModuleOptions,
834
+ typeof Request === "undefined" ? Object : Request
835
+ ])
836
+ ], AuthDataSourceProvider);
837
+
838
+ __webpack_require__.d(__webpack_exports__, {
839
+ v: () => (AuthDataSourceProvider)
840
+ });
841
+
842
+
843
+ },
844
+ 3221(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
845
+ /* import */ var _flusys_nestjs_shared__rspack_import_0 = __webpack_require__(3422);
846
+ /* import */ var _flusys_nestjs_shared_classes__rspack_import_1 = __webpack_require__(6937);
847
+ /* import */ var _flusys_nestjs_shared_constants__rspack_import_2 = __webpack_require__(9140);
848
+ /* import */ var _nestjs_common__rspack_import_3 = __webpack_require__(6157);
849
+ /* import */ var bcrypt__rspack_import_4 = __webpack_require__(7176);
850
+ /* import */ var crypto__rspack_import_5 = __webpack_require__(7823);
851
+ /* import */ var _config_index_js__rspack_import_10 = __webpack_require__(5363);
852
+ /* import */ var _config_index_js__rspack_import_12 = __webpack_require__(7987);
853
+ /* import */ var _entities_app_user_entity_js__rspack_import_6 = __webpack_require__(4758);
854
+ /* import */ var _entities_pending_registration_entity_js__rspack_import_7 = __webpack_require__(9388);
855
+ /* import */ var _entities_user_token_entity_js__rspack_import_8 = __webpack_require__(9696);
856
+ /* import */ var _interfaces_index_js__rspack_import_13 = __webpack_require__(9125);
857
+ /* import */ var _auth_datasource_provider_js__rspack_import_9 = __webpack_require__(2732);
858
+ function _ts_decorate(decorators, target, key, desc) {
859
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
860
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
861
+ r = Reflect.decorate(decorators, target, key, desc);
862
+ } else {
863
+ for(var i = decorators.length - 1; i >= 0; i--){
864
+ if (d = decorators[i]) {
865
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
866
+ }
867
+ }
868
+ }
869
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
870
+ }
871
+ function _ts_metadata(metadataKey, metadataValue) {
872
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
873
+ return Reflect.metadata(metadataKey, metadataValue);
874
+ }
875
+ }
876
+ function _ts_param(paramIndex, decorator) {
877
+ return function(target, key) {
878
+ decorator(target, key, paramIndex);
879
+ };
880
+ }
881
+
882
+
883
+
884
+
885
+
886
+
887
+
888
+
889
+
890
+
891
+
892
+
893
+ class AuthEmailService {
894
+ dataSourceProvider;
895
+ emailProvider;
896
+ PASSWORD_RESET_EXPIRY = 60 * 60 * 1000;
897
+ EMAIL_VERIFICATION_EXPIRY = 24 * 60 * 60 * 1000;
898
+ constructor(dataSourceProvider, emailProvider){
899
+ this.dataSourceProvider = dataSourceProvider;
900
+ this.emailProvider = emailProvider;
901
+ }
902
+ isEmailEnabled() {
903
+ return !!this.emailProvider;
904
+ }
905
+ async getRepository(entity) {
906
+ if (!this.dataSourceProvider) {
907
+ throw new _nestjs_common__rspack_import_3.InternalServerErrorException({
908
+ message: `${String(entity)} repository not available`,
909
+ messageKey: _flusys_nestjs_shared_constants__rspack_import_2.SYSTEM_MESSAGES.REPOSITORY_NOT_AVAILABLE,
910
+ messageVariables: {
911
+ entity: String(entity)
912
+ }
913
+ });
914
+ }
915
+ return this.dataSourceProvider.getRepository(entity);
916
+ }
917
+ generateToken() {
918
+ return crypto__rspack_import_5.randomBytes(32).toString('hex');
919
+ }
920
+ hashToken(token) {
921
+ return crypto__rspack_import_5.createHash('sha256').update(token).digest('hex');
922
+ }
923
+ assertEmailEnabled() {
924
+ if (!this.emailProvider) {
925
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
926
+ message: 'Email service is not configured',
927
+ messageKey: _config_index_js__rspack_import_10/* .AUTH_MESSAGES.EMAIL_NOT_CONFIGURED */.mK.EMAIL_NOT_CONFIGURED
928
+ });
929
+ }
930
+ }
931
+ async sendVerificationEmailSafe(email, token, verifyUrl) {
932
+ try {
933
+ await this.emailProvider.sendVerificationEmail(email, token, verifyUrl);
934
+ } catch {
935
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
936
+ message: 'Failed to send verification email. Please try again.',
937
+ messageKey: _config_index_js__rspack_import_10/* .AUTH_MESSAGES.EMAIL_SEND_FAILED */.mK.EMAIL_SEND_FAILED
938
+ });
939
+ }
940
+ }
941
+ validateTokenNotExpiredOrUsed(token, expiredMessage, expiredMessageKey, usedMessage, usedMessageKey) {
942
+ if (token.expiresAt < new Date()) {
943
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
944
+ message: expiredMessage,
945
+ messageKey: expiredMessageKey
946
+ });
947
+ }
948
+ if (usedMessage && usedMessageKey && token.usedAt) {
949
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
950
+ message: usedMessage,
951
+ messageKey: usedMessageKey
952
+ });
953
+ }
954
+ }
955
+ async hasPendingRegistration(email) {
956
+ if (!this.isEmailEnabled()) return false;
957
+ const pendingRepository = await this.getRepository(_entities_pending_registration_entity_js__rspack_import_7/* .PendingRegistration */.N);
958
+ const pending = await pendingRepository.findOne({
959
+ where: {
960
+ email
961
+ }
962
+ });
963
+ return !!pending && pending.expiresAt > new Date();
964
+ }
965
+ async createPendingRegistration(data) {
966
+ this.assertEmailEnabled();
967
+ const userRepository = await this.getRepository(_entities_app_user_entity_js__rspack_import_6/* .AppUser */.$);
968
+ const pendingRepository = await this.getRepository(_entities_pending_registration_entity_js__rspack_import_7/* .PendingRegistration */.N);
969
+ // Check if user already exists
970
+ const existingUser = await userRepository.findOne({
971
+ where: {
972
+ email: data.email
973
+ }
974
+ });
975
+ if (existingUser) {
976
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
977
+ message: 'Registration failed. Please try again or contact support.',
978
+ messageKey: _config_index_js__rspack_import_10/* .AUTH_MESSAGES.REGISTER_FAILED */.mK.REGISTER_FAILED
979
+ });
980
+ }
981
+ // Delete any existing pending registration for this email
982
+ await pendingRepository.delete({
983
+ email: data.email
984
+ });
985
+ // Create pending registration with hashed token for secure storage
986
+ const token = this.generateToken();
987
+ const tokenHash = this.hashToken(token);
988
+ const passwordHash = await bcrypt__rspack_import_4.hash(data.password, (/* inlined export .BCRYPT_SALT_ROUNDS */12));
989
+ const expiresAt = new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY);
990
+ const pending = pendingRepository.create({
991
+ email: data.email,
992
+ name: data.name ?? null,
993
+ phone: data.phone ?? null,
994
+ passwordHash,
995
+ token: tokenHash,
996
+ expiresAt,
997
+ companyData: data.companyData ?? null,
998
+ additionalFields: data.additionalFields ?? null
999
+ });
1000
+ await pendingRepository.save(pending);
1001
+ // Send verification email with raw token (user receives this)
1002
+ const verifyUrl = `${data.verifyUrlBase}?token=${token}`;
1003
+ await this.sendVerificationEmailSafe(data.email, token, verifyUrl);
1004
+ return {
1005
+ success: true,
1006
+ message: 'Please check your email to verify your registration.',
1007
+ messageKey: _config_index_js__rspack_import_10/* .EMAIL_VERIFICATION_MESSAGES.VERIFICATION_SENT */.sv.VERIFICATION_SENT
1008
+ };
1009
+ }
1010
+ async forgotPassword(email, resetUrlBase) {
1011
+ this.assertEmailEnabled();
1012
+ const userRepository = await this.getRepository(_entities_app_user_entity_js__rspack_import_6/* .AppUser */.$);
1013
+ const tokenRepository = await this.getRepository(_entities_user_token_entity_js__rspack_import_8/* .UserToken */.L);
1014
+ const user = await userRepository.findOne({
1015
+ where: {
1016
+ email
1017
+ }
1018
+ });
1019
+ // Always return success to prevent email enumeration
1020
+ if (!user || !user.isActive) {
1021
+ return {
1022
+ success: true,
1023
+ message: 'If the email exists, a password reset link has been sent.',
1024
+ messageKey: _config_index_js__rspack_import_10/* .AUTH_MESSAGES.PASSWORD_RESET_EMAIL_SENT */.mK.PASSWORD_RESET_EMAIL_SENT
1025
+ };
1026
+ }
1027
+ // Invalidate existing password reset tokens for this user
1028
+ await tokenRepository.delete({
1029
+ userId: user.id,
1030
+ type: _entities_user_token_entity_js__rspack_import_8/* .TokenType.PASSWORD_RESET */.k.PASSWORD_RESET
1031
+ });
1032
+ // Create new token with hashed storage
1033
+ const token = this.generateToken();
1034
+ const tokenHash = this.hashToken(token);
1035
+ const userToken = tokenRepository.create({
1036
+ userId: user.id,
1037
+ type: _entities_user_token_entity_js__rspack_import_8/* .TokenType.PASSWORD_RESET */.k.PASSWORD_RESET,
1038
+ token: tokenHash,
1039
+ expiresAt: new Date(Date.now() + this.PASSWORD_RESET_EXPIRY)
1040
+ });
1041
+ await tokenRepository.save(userToken);
1042
+ // Send email with raw token
1043
+ const resetUrl = `${resetUrlBase}?token=${token}`;
1044
+ try {
1045
+ await this.emailProvider.sendPasswordResetEmail(email, token, resetUrl);
1046
+ } catch {
1047
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
1048
+ message: 'Failed to process request. Please try again later.',
1049
+ messageKey: _flusys_nestjs_shared_constants__rspack_import_2.SYSTEM_MESSAGES.INTERNAL_ERROR,
1050
+ messageVariables: {
1051
+ provider: 'EmailProvider',
1052
+ error: 'Send email failed'
1053
+ }
1054
+ });
1055
+ }
1056
+ await this.publishUserEvent(_config_index_js__rspack_import_12/* .AUTH_EVENT_ACTIONS.PASSWORD_RESET_REQUESTED */.o.PASSWORD_RESET_REQUESTED, user.id, {
1057
+ email: user.email
1058
+ });
1059
+ return {
1060
+ success: true,
1061
+ message: 'If the email exists, a password reset link has been sent.',
1062
+ messageKey: _config_index_js__rspack_import_10/* .AUTH_MESSAGES.PASSWORD_RESET_EMAIL_SENT */.mK.PASSWORD_RESET_EMAIL_SENT
1063
+ };
1064
+ }
1065
+ async resetPassword(token, newPassword) {
1066
+ const userRepository = await this.getRepository(_entities_app_user_entity_js__rspack_import_6/* .AppUser */.$);
1067
+ const tokenRepository = await this.getRepository(_entities_user_token_entity_js__rspack_import_8/* .UserToken */.L);
1068
+ // Hash the incoming token to compare with stored hash
1069
+ const tokenHash = this.hashToken(token);
1070
+ const userToken = await tokenRepository.findOne({
1071
+ where: {
1072
+ token: tokenHash,
1073
+ type: _entities_user_token_entity_js__rspack_import_8/* .TokenType.PASSWORD_RESET */.k.PASSWORD_RESET
1074
+ }
1075
+ });
1076
+ if (!userToken) {
1077
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
1078
+ message: 'Invalid or expired reset token',
1079
+ messageKey: _config_index_js__rspack_import_10/* .EMAIL_VERIFICATION_MESSAGES.VERIFICATION_TOKEN_INVALID */.sv.VERIFICATION_TOKEN_INVALID
1080
+ });
1081
+ }
1082
+ this.validateTokenNotExpiredOrUsed(userToken, 'Reset token has expired. Please request a new one.', _config_index_js__rspack_import_10/* .AUTH_MESSAGES.PASSWORD_RESET_TOKEN_EXPIRED */.mK.PASSWORD_RESET_TOKEN_EXPIRED, 'This reset token has already been used.', _config_index_js__rspack_import_10/* .AUTH_MESSAGES.PASSWORD_RESET_TOKEN_USED */.mK.PASSWORD_RESET_TOKEN_USED);
1083
+ const user = await userRepository.findOne({
1084
+ where: {
1085
+ id: userToken.userId
1086
+ }
1087
+ });
1088
+ if (!user) {
1089
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
1090
+ message: 'User not found',
1091
+ messageKey: _config_index_js__rspack_import_10/* .USER_MESSAGES.NOT_FOUND */.ny.NOT_FOUND
1092
+ });
1093
+ }
1094
+ // Update password
1095
+ user.password = await bcrypt__rspack_import_4.hash(newPassword, (/* inlined export .BCRYPT_SALT_ROUNDS */12));
1096
+ await userRepository.save(user);
1097
+ // Mark token as used
1098
+ userToken.usedAt = new Date();
1099
+ await tokenRepository.save(userToken);
1100
+ await this.publishUserEvent(_config_index_js__rspack_import_12/* .AUTH_EVENT_ACTIONS.PASSWORD_RESET */.o.PASSWORD_RESET, user.id, {
1101
+ email: user.email
1102
+ });
1103
+ return {
1104
+ success: true,
1105
+ message: 'Password has been reset successfully.',
1106
+ messageKey: _config_index_js__rspack_import_10/* .AUTH_MESSAGES.PASSWORD_RESET_SUCCESS */.mK.PASSWORD_RESET_SUCCESS
1107
+ };
1108
+ }
1109
+ async verifyEmail(token) {
1110
+ const pendingRepository = await this.getRepository(_entities_pending_registration_entity_js__rspack_import_7/* .PendingRegistration */.N);
1111
+ const userRepository = await this.getRepository(_entities_app_user_entity_js__rspack_import_6/* .AppUser */.$);
1112
+ const tokenRepository = await this.getRepository(_entities_user_token_entity_js__rspack_import_8/* .UserToken */.L);
1113
+ // Hash the incoming token to compare with stored hash
1114
+ const tokenHash = this.hashToken(token);
1115
+ // Check for pending registration first
1116
+ const pending = await pendingRepository.findOne({
1117
+ where: {
1118
+ token: tokenHash
1119
+ }
1120
+ });
1121
+ if (pending) {
1122
+ if (pending.expiresAt < new Date()) {
1123
+ await pendingRepository.delete({
1124
+ id: pending.id
1125
+ });
1126
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
1127
+ message: 'Verification token has expired. Please register again.',
1128
+ messageKey: _config_index_js__rspack_import_10/* .EMAIL_VERIFICATION_MESSAGES.VERIFICATION_TOKEN_EXPIRED */.sv.VERIFICATION_TOKEN_EXPIRED
1129
+ });
1130
+ }
1131
+ // Delete pending registration (will be consumed by caller to create user)
1132
+ await pendingRepository.delete({
1133
+ id: pending.id
1134
+ });
1135
+ return {
1136
+ type: 'pending',
1137
+ pending
1138
+ };
1139
+ }
1140
+ // Check for existing user email verification token
1141
+ const userToken = await tokenRepository.findOne({
1142
+ where: {
1143
+ token: tokenHash,
1144
+ type: _entities_user_token_entity_js__rspack_import_8/* .TokenType.EMAIL_VERIFICATION */.k.EMAIL_VERIFICATION
1145
+ }
1146
+ });
1147
+ if (!userToken) {
1148
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
1149
+ message: 'Invalid or expired verification token',
1150
+ messageKey: _config_index_js__rspack_import_10/* .EMAIL_VERIFICATION_MESSAGES.VERIFICATION_TOKEN_INVALID */.sv.VERIFICATION_TOKEN_INVALID
1151
+ });
1152
+ }
1153
+ if (userToken.expiresAt < new Date()) {
1154
+ await tokenRepository.delete({
1155
+ id: userToken.id
1156
+ });
1157
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
1158
+ message: 'Verification token has expired. Please request a new one.',
1159
+ messageKey: _config_index_js__rspack_import_10/* .EMAIL_VERIFICATION_MESSAGES.VERIFICATION_TOKEN_EXPIRED */.sv.VERIFICATION_TOKEN_EXPIRED
1160
+ });
1161
+ }
1162
+ if (userToken.usedAt) {
1163
+ return {
1164
+ type: 'verified',
1165
+ message: 'Email has already been verified.',
1166
+ messageKey: _config_index_js__rspack_import_10/* .EMAIL_VERIFICATION_MESSAGES.VERIFICATION_SUCCESS */.sv.VERIFICATION_SUCCESS
1167
+ };
1168
+ }
1169
+ const user = await userRepository.findOne({
1170
+ where: {
1171
+ id: userToken.userId
1172
+ }
1173
+ });
1174
+ if (!user) {
1175
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
1176
+ message: 'User not found',
1177
+ messageKey: _config_index_js__rspack_import_10/* .USER_MESSAGES.NOT_FOUND */.ny.NOT_FOUND
1178
+ });
1179
+ }
1180
+ // Mark email as verified
1181
+ user.emailVerified = true;
1182
+ await userRepository.save(user);
1183
+ // Mark token as used
1184
+ userToken.usedAt = new Date();
1185
+ await tokenRepository.save(userToken);
1186
+ await this.publishUserEvent(_config_index_js__rspack_import_12/* .AUTH_EVENT_ACTIONS.EMAIL_VERIFIED */.o.EMAIL_VERIFIED, user.id, {
1187
+ email: user.email
1188
+ });
1189
+ return {
1190
+ type: 'verified',
1191
+ message: 'Email has been verified successfully.',
1192
+ messageKey: _config_index_js__rspack_import_10/* .EMAIL_VERIFICATION_MESSAGES.VERIFICATION_SUCCESS */.sv.VERIFICATION_SUCCESS
1193
+ };
1194
+ }
1195
+ async publishUserEvent(action, userId, metadata) {
1196
+ await (0,_flusys_nestjs_shared_classes__rspack_import_1.publishDomainEvent)({
1197
+ module: (/* inlined export .AUTH_EVENT_MODULE */"auth"),
1198
+ entity: _config_index_js__rspack_import_12/* .AUTH_EVENT_ENTITIES.USER */.g.USER,
1199
+ action,
1200
+ ids: [
1201
+ userId
1202
+ ],
1203
+ metadata
1204
+ });
1205
+ }
1206
+ async resendVerificationEmail(email, verifyUrlBase) {
1207
+ this.assertEmailEnabled();
1208
+ const pendingRepository = await this.getRepository(_entities_pending_registration_entity_js__rspack_import_7/* .PendingRegistration */.N);
1209
+ const userRepository = await this.getRepository(_entities_app_user_entity_js__rspack_import_6/* .AppUser */.$);
1210
+ const tokenRepository = await this.getRepository(_entities_user_token_entity_js__rspack_import_8/* .UserToken */.L);
1211
+ // Check pending registration first
1212
+ const pending = await pendingRepository.findOne({
1213
+ where: {
1214
+ email
1215
+ }
1216
+ });
1217
+ if (pending) {
1218
+ const token = this.generateToken();
1219
+ pending.token = this.hashToken(token);
1220
+ pending.expiresAt = new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY);
1221
+ await pendingRepository.save(pending);
1222
+ const verifyUrl = `${verifyUrlBase}?token=${token}`;
1223
+ await this.sendVerificationEmailSafe(email, token, verifyUrl);
1224
+ return {
1225
+ success: true,
1226
+ message: 'If the email requires verification, a link has been sent.',
1227
+ messageKey: _config_index_js__rspack_import_10/* .EMAIL_VERIFICATION_MESSAGES.RESEND_SUCCESS */.sv.RESEND_SUCCESS
1228
+ };
1229
+ }
1230
+ // Check existing user
1231
+ const user = await userRepository.findOne({
1232
+ where: {
1233
+ email
1234
+ }
1235
+ });
1236
+ if (!user || user.emailVerified) {
1237
+ return {
1238
+ success: true,
1239
+ message: 'If the email requires verification, a link has been sent.',
1240
+ messageKey: _config_index_js__rspack_import_10/* .EMAIL_VERIFICATION_MESSAGES.RESEND_SUCCESS */.sv.RESEND_SUCCESS
1241
+ };
1242
+ }
1243
+ // Invalidate existing tokens and create new one
1244
+ await tokenRepository.delete({
1245
+ userId: user.id,
1246
+ type: _entities_user_token_entity_js__rspack_import_8/* .TokenType.EMAIL_VERIFICATION */.k.EMAIL_VERIFICATION
1247
+ });
1248
+ const token = this.generateToken();
1249
+ const userToken = tokenRepository.create({
1250
+ userId: user.id,
1251
+ type: _entities_user_token_entity_js__rspack_import_8/* .TokenType.EMAIL_VERIFICATION */.k.EMAIL_VERIFICATION,
1252
+ token: this.hashToken(token),
1253
+ expiresAt: new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY)
1254
+ });
1255
+ await tokenRepository.save(userToken);
1256
+ const verifyUrl = `${verifyUrlBase}?token=${token}`;
1257
+ await this.sendVerificationEmailSafe(user.email, token, verifyUrl);
1258
+ return {
1259
+ success: true,
1260
+ message: 'If the email requires verification, a link has been sent.',
1261
+ messageKey: _config_index_js__rspack_import_10/* .EMAIL_VERIFICATION_MESSAGES.RESEND_SUCCESS */.sv.RESEND_SUCCESS
1262
+ };
1263
+ }
1264
+ }
1265
+ _ts_decorate([
1266
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
1267
+ action: 'auth.createPendingRegistration',
1268
+ module: 'auth',
1269
+ includeParams: false
1270
+ }),
1271
+ _ts_metadata("design:type", Function),
1272
+ _ts_metadata("design:paramtypes", [
1273
+ Object
1274
+ ]),
1275
+ _ts_metadata("design:returntype", Promise)
1276
+ ], AuthEmailService.prototype, "createPendingRegistration", null);
1277
+ _ts_decorate([
1278
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
1279
+ action: 'auth.forgotPassword',
1280
+ module: 'auth',
1281
+ includeParams: false
1282
+ }),
1283
+ _ts_metadata("design:type", Function),
1284
+ _ts_metadata("design:paramtypes", [
1285
+ String,
1286
+ String
1287
+ ]),
1288
+ _ts_metadata("design:returntype", Promise)
1289
+ ], AuthEmailService.prototype, "forgotPassword", null);
1290
+ _ts_decorate([
1291
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
1292
+ action: 'auth.resetPassword',
1293
+ module: 'auth',
1294
+ includeParams: false
1295
+ }),
1296
+ _ts_metadata("design:type", Function),
1297
+ _ts_metadata("design:paramtypes", [
1298
+ String,
1299
+ String
1300
+ ]),
1301
+ _ts_metadata("design:returntype", Promise)
1302
+ ], AuthEmailService.prototype, "resetPassword", null);
1303
+ _ts_decorate([
1304
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
1305
+ action: 'auth.verifyEmailToken',
1306
+ module: 'auth'
1307
+ }),
1308
+ _ts_metadata("design:type", Function),
1309
+ _ts_metadata("design:paramtypes", [
1310
+ String
1311
+ ]),
1312
+ _ts_metadata("design:returntype", Promise)
1313
+ ], AuthEmailService.prototype, "verifyEmail", null);
1314
+ _ts_decorate([
1315
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
1316
+ action: 'auth.sendVerificationEmail',
1317
+ module: 'auth'
1318
+ }),
1319
+ _ts_metadata("design:type", Function),
1320
+ _ts_metadata("design:paramtypes", [
1321
+ String,
1322
+ String
1323
+ ]),
1324
+ _ts_metadata("design:returntype", Promise)
1325
+ ], AuthEmailService.prototype, "resendVerificationEmail", null);
1326
+ AuthEmailService = _ts_decorate([
1327
+ (0,_nestjs_common__rspack_import_3.Injectable)({
1328
+ scope: _nestjs_common__rspack_import_3.Scope.REQUEST
1329
+ }),
1330
+ _ts_param(0, (0,_nestjs_common__rspack_import_3.Optional)()),
1331
+ _ts_param(0, (0,_nestjs_common__rspack_import_3.Inject)(_auth_datasource_provider_js__rspack_import_9/* .AuthDataSourceProvider */.v)),
1332
+ _ts_param(1, (0,_nestjs_common__rspack_import_3.Optional)()),
1333
+ _ts_param(1, (0,_nestjs_common__rspack_import_3.Inject)(_interfaces_index_js__rspack_import_13/* .AUTH_EMAIL_PROVIDER */.C)),
1334
+ _ts_metadata("design:type", Function),
1335
+ _ts_metadata("design:paramtypes", [
1336
+ typeof _auth_datasource_provider_js__rspack_import_9/* .AuthDataSourceProvider */.v === "undefined" ? Object : _auth_datasource_provider_js__rspack_import_9/* .AuthDataSourceProvider */.v,
1337
+ typeof IAuthEmailProvider === "undefined" ? Object : IAuthEmailProvider
1338
+ ])
1339
+ ], AuthEmailService);
1340
+
1341
+ __webpack_require__.d(__webpack_exports__, {
1342
+ G: () => (AuthEmailService)
1343
+ });
1344
+
1345
+
1346
+ },
1347
+ 4722(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
1348
+
1349
+ // EXPORTS
1350
+ __webpack_require__.d(__webpack_exports__, {
1351
+ k: () => (/* binding */ AuthenticationService)
1352
+ });
1353
+
1354
+ // EXTERNAL MODULE: external "@flusys/nestjs-shared"
1355
+ var nestjs_shared_ = __webpack_require__(3422);
1356
+ // EXTERNAL MODULE: external "@flusys/nestjs-shared/classes"
1357
+ var classes_ = __webpack_require__(6937);
1358
+ // EXTERNAL MODULE: external "@flusys/nestjs-shared/constants"
1359
+ var constants_ = __webpack_require__(9140);
1360
+ ;// CONCATENATED MODULE: external "@flusys/nestjs-shared/enums"
1361
+
1362
+ // EXTERNAL MODULE: external "@flusys/nestjs-shared/interfaces"
1363
+ var interfaces_ = __webpack_require__(5103);
1364
+ // EXTERNAL MODULE: external "@flusys/nestjs-shared/utils"
1365
+ var utils_ = __webpack_require__(9216);
1366
+ // EXTERNAL MODULE: external "@nestjs/common"
1367
+ var common_ = __webpack_require__(6157);
1368
+ // EXTERNAL MODULE: external "@nestjs/jwt"
1369
+ var jwt_ = __webpack_require__(2125);
1370
+ // EXTERNAL MODULE: external "bcrypt"
1371
+ var external_bcrypt_ = __webpack_require__(7176);
1372
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/config/message-keys.ts
1373
+ var message_keys = __webpack_require__(5363);
1374
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/config/event-actions.ts
1375
+ var event_actions = __webpack_require__(7987);
1376
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/config/auth.constants.ts
1377
+ var auth_constants = __webpack_require__(5588);
1378
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/dtos/authentication.dto.ts
1379
+ var authentication_dto = __webpack_require__(8978);
1380
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/entities/app-user.entity.ts
1381
+ var app_user_entity = __webpack_require__(4758);
1382
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/entities/company-branch.entity.ts
1383
+ var company_branch_entity = __webpack_require__(1923);
1384
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/entities/company.entity.ts
1385
+ var company_entity = __webpack_require__(8538);
1386
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/entities/pending-registration.entity.ts
1387
+ var pending_registration_entity = __webpack_require__(9388);
1388
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/entities/user-company-permission.entity.ts
1389
+ var user_company_permission_entity = __webpack_require__(2377);
1390
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/enums/user-org-permission-type.enum.ts
1391
+ var user_org_permission_type_enum = __webpack_require__(5081);
1392
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/helpers/token.helper.ts
1393
+ var token_helper = __webpack_require__(1379);
1394
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/helpers/auth-response.mapper.ts
1395
+ var auth_response_mapper = __webpack_require__(2295);
1396
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/services/auth-config.service.ts + 1 modules
1397
+ var auth_config_service = __webpack_require__(6514);
1398
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/services/auth-datasource.provider.ts
1399
+ var auth_datasource_provider = __webpack_require__(2732);
1400
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/services/auth-email.service.ts
1401
+ var auth_email_service = __webpack_require__(3221);
1402
+ // EXTERNAL MODULE: ./projects/nestjs-auth/src/services/company-selection-session.service.ts
1403
+ var company_selection_session_service = __webpack_require__(5811);
1404
+ ;// CONCATENATED MODULE: ./projects/nestjs-auth/src/services/authentication.service.ts
1405
+ function _ts_decorate(decorators, target, key, desc) {
1406
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1407
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
1408
+ r = Reflect.decorate(decorators, target, key, desc);
1409
+ } else {
1410
+ for(var i = decorators.length - 1; i >= 0; i--){
1411
+ if (d = decorators[i]) {
1412
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1413
+ }
1414
+ }
1415
+ }
1416
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1417
+ }
1418
+ function _ts_metadata(metadataKey, metadataValue) {
1419
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
1420
+ return Reflect.metadata(metadataKey, metadataValue);
1421
+ }
1422
+ }
1423
+ function _ts_param(paramIndex, decorator) {
1424
+ return function(target, key) {
1425
+ decorator(target, key, paramIndex);
1426
+ };
1427
+ }
1428
+
1429
+
1430
+
1431
+
1432
+
1433
+
1434
+
1435
+
1436
+
1437
+
1438
+
1439
+
1440
+
1441
+
1442
+
1443
+
1444
+
1445
+
1446
+
1447
+
1448
+
1449
+
1450
+ class AuthenticationService {
1451
+ jwtService;
1452
+ authConfig;
1453
+ cacheManager;
1454
+ dataSourceProvider;
1455
+ sessionService;
1456
+ authEmailService;
1457
+ userEnricher;
1458
+ notificationAdapter;
1459
+ // NOTE: @Inject() required for bundled code - type metadata may be lost during esbuild
1460
+ constructor(jwtService, authConfig, cacheManager, dataSourceProvider, sessionService, authEmailService, userEnricher, notificationAdapter){
1461
+ this.jwtService = jwtService;
1462
+ this.authConfig = authConfig;
1463
+ this.cacheManager = cacheManager;
1464
+ this.dataSourceProvider = dataSourceProvider;
1465
+ this.sessionService = sessionService;
1466
+ this.authEmailService = authEmailService;
1467
+ this.userEnricher = userEnricher;
1468
+ this.notificationAdapter = notificationAdapter;
1469
+ }
1470
+ isCompanyFeatureEnabled() {
1471
+ return this.dataSourceProvider?.isCompanyFeatureEnabled() ?? this.authConfig.isCompanyFeatureEnabled();
1472
+ }
1473
+ isEmailVerificationEnabled() {
1474
+ const featureEnabled = this.dataSourceProvider?.isEmailVerificationEnabled() ?? this.authConfig.isEmailVerificationEnabled();
1475
+ const providerAvailable = this.authEmailService?.isEmailEnabled() ?? false;
1476
+ return featureEnabled && providerAvailable;
1477
+ }
1478
+ isSignUpEnabled() {
1479
+ return this.dataSourceProvider?.isSignUpEnabled() ?? this.authConfig.isSignUpEnabled();
1480
+ }
1481
+ async getUserRepository() {
1482
+ if (!this.dataSourceProvider) {
1483
+ throw new common_.InternalServerErrorException({
1484
+ message: 'User repository not available',
1485
+ messageKey: constants_.SYSTEM_MESSAGES.REPOSITORY_NOT_AVAILABLE,
1486
+ messageVariables: {
1487
+ entity: 'AppUser'
1488
+ }
1489
+ });
1490
+ }
1491
+ return this.dataSourceProvider.getRepository(app_user_entity/* .AppUser */.$);
1492
+ }
1493
+ async getCompanyScopedRepository(entity) {
1494
+ if (!this.isCompanyFeatureEnabled() || !this.dataSourceProvider) return null;
1495
+ return this.dataSourceProvider.getRepository(entity);
1496
+ }
1497
+ async login(email, password) {
1498
+ if (this.isEmailVerificationEnabled() && await this.authEmailService.hasPendingRegistration(email)) {
1499
+ return {
1500
+ requiresEmailVerification: true,
1501
+ email,
1502
+ message: 'Please verify your email address to complete registration.',
1503
+ messageKey: message_keys/* .EMAIL_VERIFICATION_MESSAGES.VERIFICATION_SENT */.sv.VERIFICATION_SENT
1504
+ };
1505
+ }
1506
+ const user = await this.validateUser(email, password);
1507
+ this.ensureUserActive(user);
1508
+ if (this.isEmailVerificationEnabled() && !user.emailVerified) {
1509
+ return {
1510
+ requiresEmailVerification: true,
1511
+ email: user.email,
1512
+ message: 'Please verify your email address before logging in.',
1513
+ messageKey: message_keys/* .AUTH_MESSAGES.LOGIN_EMAIL_NOT_VERIFIED */.mK.LOGIN_EMAIL_NOT_VERIFIED
1514
+ };
1515
+ }
1516
+ return this.issueLoginForUser(user);
1517
+ }
1518
+ async issueLoginForUser(user) {
1519
+ this.ensureUserActive(user);
1520
+ if (!this.isCompanyFeatureEnabled()) {
1521
+ return this.generateLoginResponse(user);
1522
+ }
1523
+ return await this.handleCompanyBasedLogin(user);
1524
+ }
1525
+ ensureUserActive(user) {
1526
+ if (!user.isActive) {
1527
+ throw new common_.ForbiddenException({
1528
+ message: 'User account is deactivated',
1529
+ messageKey: message_keys/* .AUTH_MESSAGES.LOGIN_ACCOUNT_DEACTIVATED */.mK.LOGIN_ACCOUNT_DEACTIVATED
1530
+ });
1531
+ }
1532
+ }
1533
+ async handleCompanyBasedLogin(user) {
1534
+ const permissionRepository = await this.getCompanyScopedRepository(user_company_permission_entity/* .UserCompanyPermission */.I);
1535
+ const branchRepository = await this.getCompanyScopedRepository(company_branch_entity/* .CompanyBranch */.A);
1536
+ if (!permissionRepository || !branchRepository) {
1537
+ return this.generateLoginResponse(user);
1538
+ }
1539
+ const companyPermissions = await permissionRepository.find({
1540
+ where: {
1541
+ userId: user.id,
1542
+ permissionType: user_org_permission_type_enum/* .PermissionType.COMPANY */.e.COMPANY
1543
+ }
1544
+ });
1545
+ const companyRepository = await this.getCompanyScopedRepository(company_entity/* .Company */.C);
1546
+ if (!companyRepository) {
1547
+ return this.generateLoginResponse(user);
1548
+ }
1549
+ const companyIds = companyPermissions.map((p)=>p.targetId);
1550
+ const companies = companyIds.length > 0 ? await companyRepository.createQueryBuilder('c').where('c.id IN (:...ids)', {
1551
+ ids: companyIds
1552
+ }).andWhere('c.is_active = :active', {
1553
+ active: true
1554
+ }).getMany() : [];
1555
+ if (companies.length === 0) {
1556
+ return this.generateLoginResponse(user);
1557
+ }
1558
+ const branchPermissions = await permissionRepository.find({
1559
+ where: {
1560
+ userId: user.id,
1561
+ permissionType: user_org_permission_type_enum/* .PermissionType.BRANCH */.e.BRANCH
1562
+ }
1563
+ });
1564
+ const branchIds = branchPermissions.map((p)=>p.targetId);
1565
+ const branches = branchIds.length > 0 ? await branchRepository.createQueryBuilder('b').leftJoinAndSelect('b.company', 'company').where('b.id IN (:...ids)', {
1566
+ ids: branchIds
1567
+ }).andWhere('b.is_active = :active', {
1568
+ active: true
1569
+ }).getMany() : [];
1570
+ if (companies.length === 1 && branches.length === 1) {
1571
+ return this.generateLoginResponseWithCompany(user, companies[0], branches[0]);
1572
+ }
1573
+ return await this.generateCompanySelectionResponse(user, companies, branches);
1574
+ }
1575
+ async register(dto, verifyUrlBase) {
1576
+ const userRepository = await this.getUserRepository();
1577
+ const existingUser = await userRepository.findOne({
1578
+ where: {
1579
+ email: dto.email
1580
+ },
1581
+ withDeleted: true
1582
+ });
1583
+ if (existingUser?.deletedAt) {
1584
+ throw new common_.BadRequestException({
1585
+ message: 'This account has been permanently deleted. Please contact your system administrator.',
1586
+ messageKey: message_keys/* .AUTH_MESSAGES.REGISTER_ACCOUNT_DELETED */.mK.REGISTER_ACCOUNT_DELETED
1587
+ });
1588
+ }
1589
+ if (existingUser && this.isCompanyFeatureEnabled()) {
1590
+ return await this.handleExistingUserCompanyRegistration(existingUser, dto);
1591
+ }
1592
+ if (existingUser) {
1593
+ throw new common_.BadRequestException({
1594
+ message: 'Registration failed due to email exists. Please try again or contact support.',
1595
+ messageKey: message_keys/* .AUTH_MESSAGES.REGISTER_EMAIL_EXISTS */.mK.REGISTER_EMAIL_EXISTS
1596
+ });
1597
+ }
1598
+ if (!this.isSignUpEnabled()) {
1599
+ throw new common_.BadRequestException({
1600
+ message: 'New account registration is currently disabled.',
1601
+ messageKey: message_keys/* .AUTH_MESSAGES.REGISTER_SIGNUP_DISABLED */.mK.REGISTER_SIGNUP_DISABLED
1602
+ });
1603
+ }
1604
+ if (this.isEmailVerificationEnabled() && verifyUrlBase) {
1605
+ const companyData = this.isCompanyFeatureEnabled() ? {
1606
+ companySlug: dto.companySlug,
1607
+ branchSlug: dto.branchSlug,
1608
+ newCompanyName: dto.newCompanyName,
1609
+ newCompanyPhone: dto.newCompanyPhone,
1610
+ newCompanyAddress: dto.newCompanyAddress
1611
+ } : undefined;
1612
+ const result = await this.authEmailService.createPendingRegistration({
1613
+ email: dto.email,
1614
+ name: dto.name,
1615
+ phone: dto.phone,
1616
+ password: dto.password,
1617
+ companyData,
1618
+ additionalFields: dto.additionalFields,
1619
+ verifyUrlBase
1620
+ });
1621
+ return {
1622
+ requiresEmailVerification: true,
1623
+ message: result.message,
1624
+ messageKey: message_keys/* .EMAIL_VERIFICATION_MESSAGES.VERIFICATION_SENT */.sv.VERIFICATION_SENT
1625
+ };
1626
+ }
1627
+ return await this.createUserDirectly(dto);
1628
+ }
1629
+ async handleExistingUserCompanyRegistration(existingUser, dto) {
1630
+ if (!dto.companySlug && !dto.newCompanyName) {
1631
+ throw new common_.BadRequestException({
1632
+ message: 'Email already registered. Please login or provide a company to join/create.',
1633
+ messageKey: message_keys/* .AUTH_MESSAGES.REGISTER_EMAIL_EXISTS */.mK.REGISTER_EMAIL_EXISTS
1634
+ });
1635
+ }
1636
+ const permissionRepository = await this.getCompanyScopedRepository(user_company_permission_entity/* .UserCompanyPermission */.I);
1637
+ const companyRepository = await this.getCompanyScopedRepository(company_entity/* .Company */.C);
1638
+ if (!permissionRepository || !companyRepository) {
1639
+ throw new common_.BadRequestException({
1640
+ message: 'Company feature repositories not available',
1641
+ messageKey: constants_.SYSTEM_MESSAGES.REPOSITORY_NOT_AVAILABLE,
1642
+ messageVariables: {
1643
+ entity: 'Company feature'
1644
+ }
1645
+ });
1646
+ }
1647
+ if (dto.companySlug) {
1648
+ const company = await companyRepository.findOne({
1649
+ where: {
1650
+ slug: dto.companySlug,
1651
+ isActive: true
1652
+ }
1653
+ });
1654
+ if (company) {
1655
+ const existingPermission = await permissionRepository.findOne({
1656
+ where: {
1657
+ userId: existingUser.id,
1658
+ permissionType: user_org_permission_type_enum/* .PermissionType.COMPANY */.e.COMPANY,
1659
+ targetId: company.id
1660
+ }
1661
+ });
1662
+ if (existingPermission) {
1663
+ throw new common_.BadRequestException({
1664
+ message: 'You are already assigned to this company. Please login.',
1665
+ messageKey: message_keys/* .AUTH_MESSAGES.REGISTER_COMPANY_ALREADY_ASSIGNED */.mK.REGISTER_COMPANY_ALREADY_ASSIGNED
1666
+ });
1667
+ }
1668
+ }
1669
+ }
1670
+ return await this.processCompanyRegistration(existingUser, dto, true);
1671
+ }
1672
+ async createUserDirectly(dto) {
1673
+ if (!this.dataSourceProvider) {
1674
+ throw new common_.BadRequestException({
1675
+ message: 'Data source not available',
1676
+ messageKey: constants_.SYSTEM_MESSAGES.DATASOURCE_NOT_AVAILABLE
1677
+ });
1678
+ }
1679
+ const dataSource = await this.dataSourceProvider.getDataSource();
1680
+ const queryRunner = dataSource.createQueryRunner();
1681
+ await queryRunner.connect();
1682
+ await queryRunner.startTransaction();
1683
+ try {
1684
+ const hashedPassword = await external_bcrypt_.hash(dto.password, (/* inlined export .BCRYPT_SALT_ROUNDS */12));
1685
+ const user = queryRunner.manager.create(app_user_entity/* .AppUser */.$, {
1686
+ name: dto.name,
1687
+ email: dto.email,
1688
+ phone: dto.phone,
1689
+ password: hashedPassword,
1690
+ isActive: true,
1691
+ emailVerified: false,
1692
+ phoneVerified: false
1693
+ });
1694
+ await queryRunner.manager.save(app_user_entity/* .AppUser */.$, user);
1695
+ if (this.userEnricher?.onUserCreated) {
1696
+ await this.userEnricher.onUserCreated(user.id, dto.additionalFields ?? null, queryRunner);
1697
+ }
1698
+ await queryRunner.commitTransaction();
1699
+ if (!this.isCompanyFeatureEnabled()) {
1700
+ return this.generateRegistrationResponse(user);
1701
+ }
1702
+ return await this.processCompanyRegistration(user, dto);
1703
+ } catch (error) {
1704
+ await queryRunner.rollbackTransaction();
1705
+ if (error instanceof common_.BadRequestException) {
1706
+ throw error;
1707
+ }
1708
+ throw new common_.BadRequestException({
1709
+ message: 'Registration failed. Please try again.',
1710
+ messageKey: message_keys/* .AUTH_MESSAGES.REGISTER_FAILED */.mK.REGISTER_FAILED
1711
+ });
1712
+ } finally{
1713
+ await queryRunner.release();
1714
+ }
1715
+ }
1716
+ async createUserFromPendingRegistration(pending) {
1717
+ if (!this.dataSourceProvider) {
1718
+ throw new common_.BadRequestException({
1719
+ message: 'Data source not available',
1720
+ messageKey: constants_.SYSTEM_MESSAGES.DATASOURCE_NOT_AVAILABLE
1721
+ });
1722
+ }
1723
+ const dataSource = await this.dataSourceProvider.getDataSource();
1724
+ const queryRunner = dataSource.createQueryRunner();
1725
+ await queryRunner.connect();
1726
+ await queryRunner.startTransaction();
1727
+ try {
1728
+ const existingUser = await queryRunner.manager.findOne(app_user_entity/* .AppUser */.$, {
1729
+ where: {
1730
+ email: pending.email
1731
+ },
1732
+ withDeleted: true
1733
+ });
1734
+ if (existingUser?.deletedAt) {
1735
+ throw new common_.BadRequestException({
1736
+ message: 'This account has been permanently deleted. Please contact your system administrator.',
1737
+ messageKey: message_keys/* .AUTH_MESSAGES.REGISTER_ACCOUNT_DELETED */.mK.REGISTER_ACCOUNT_DELETED
1738
+ });
1739
+ }
1740
+ if (existingUser) {
1741
+ throw new common_.BadRequestException({
1742
+ message: 'This email has already been registered.',
1743
+ messageKey: message_keys/* .AUTH_MESSAGES.REGISTER_EMAIL_EXISTS */.mK.REGISTER_EMAIL_EXISTS
1744
+ });
1745
+ }
1746
+ const user = queryRunner.manager.create(app_user_entity/* .AppUser */.$, {
1747
+ name: pending.name,
1748
+ email: pending.email,
1749
+ phone: pending.phone,
1750
+ password: pending.passwordHash,
1751
+ isActive: true,
1752
+ emailVerified: true,
1753
+ phoneVerified: false
1754
+ });
1755
+ await queryRunner.manager.save(app_user_entity/* .AppUser */.$, user);
1756
+ if (this.userEnricher?.onUserCreated) {
1757
+ await this.userEnricher.onUserCreated(user.id, pending.additionalFields ?? null, queryRunner);
1758
+ }
1759
+ await queryRunner.commitTransaction();
1760
+ if (this.isCompanyFeatureEnabled() && pending.companyData) {
1761
+ return await this.processCompanyRegistration(user, pending.companyData);
1762
+ }
1763
+ return this.generateRegistrationResponse(user);
1764
+ } catch (error) {
1765
+ await queryRunner.rollbackTransaction();
1766
+ if (error instanceof common_.BadRequestException) {
1767
+ throw error;
1768
+ }
1769
+ throw new common_.BadRequestException({
1770
+ message: 'Registration failed. Please try again.',
1771
+ messageKey: message_keys/* .AUTH_MESSAGES.REGISTER_FAILED */.mK.REGISTER_FAILED
1772
+ });
1773
+ } finally{
1774
+ await queryRunner.release();
1775
+ }
1776
+ }
1777
+ async processCompanyRegistration(user, data, throwOnUnavailable = false) {
1778
+ const companyRepository = await this.getCompanyScopedRepository(company_entity/* .Company */.C);
1779
+ const branchRepository = await this.getCompanyScopedRepository(company_branch_entity/* .CompanyBranch */.A);
1780
+ const permissionRepository = await this.getCompanyScopedRepository(user_company_permission_entity/* .UserCompanyPermission */.I);
1781
+ if (!companyRepository || !branchRepository || !permissionRepository) {
1782
+ if (throwOnUnavailable) throw new common_.BadRequestException({
1783
+ message: 'Company feature repositories not available',
1784
+ messageKey: constants_.SYSTEM_MESSAGES.REPOSITORY_NOT_AVAILABLE,
1785
+ messageVariables: {
1786
+ entity: 'Company feature'
1787
+ }
1788
+ });
1789
+ return this.generateRegistrationResponse(user);
1790
+ }
1791
+ const { company, branch } = await this.findOrCreateCompanyAndBranch(data, companyRepository, branchRepository);
1792
+ if (company) {
1793
+ await this.assignUserPermissions(user.id, company.id, branch?.id, permissionRepository);
1794
+ return this.generateRegistrationResponseWithCompany(user, company, branch ?? undefined);
1795
+ }
1796
+ return this.generateRegistrationResponse(user);
1797
+ }
1798
+ async findOrCreateCompanyAndBranch(data, companyRepo, branchRepo) {
1799
+ if (data.companySlug) {
1800
+ const company = await companyRepo.findOne({
1801
+ where: {
1802
+ slug: data.companySlug,
1803
+ isActive: true
1804
+ }
1805
+ });
1806
+ if (!company) throw new common_.BadRequestException({
1807
+ message: 'Company not found or inactive',
1808
+ messageKey: message_keys/* .AUTH_MESSAGES.COMPANY_NOT_FOUND */.mK.COMPANY_NOT_FOUND
1809
+ });
1810
+ const branch = data.branchSlug ? await branchRepo.findOne({
1811
+ where: {
1812
+ slug: data.branchSlug,
1813
+ companyId: company.id,
1814
+ isActive: true
1815
+ }
1816
+ }) : await branchRepo.findOne({
1817
+ where: {
1818
+ companyId: company.id,
1819
+ isActive: true
1820
+ },
1821
+ order: {
1822
+ serial: 'ASC',
1823
+ createdAt: 'ASC'
1824
+ }
1825
+ });
1826
+ if (data.branchSlug && !branch) throw new common_.BadRequestException({
1827
+ message: 'Branch not found or inactive',
1828
+ messageKey: message_keys/* .AUTH_MESSAGES.BRANCH_NOT_FOUND */.mK.BRANCH_NOT_FOUND
1829
+ });
1830
+ return {
1831
+ company,
1832
+ branch
1833
+ };
1834
+ }
1835
+ if (data.newCompanyName) {
1836
+ const slug = await (0,utils_.generateUniqueSlug)(data.newCompanyName, async (baseSlug)=>{
1837
+ const rows = await companyRepo.createQueryBuilder('c').select('c.slug').where('c.slug = :base OR c.slug LIKE :pattern', {
1838
+ base: baseSlug,
1839
+ pattern: `${baseSlug}-%`
1840
+ }).getMany();
1841
+ return rows.map((r)=>r.slug);
1842
+ });
1843
+ const company = companyRepo.create({
1844
+ name: data.newCompanyName,
1845
+ slug,
1846
+ phone: data.newCompanyPhone,
1847
+ address: data.newCompanyAddress,
1848
+ isActive: true
1849
+ });
1850
+ await companyRepo.save(company);
1851
+ const branch = branchRepo.create({
1852
+ name: 'Main Branch',
1853
+ slug: 'main-branch',
1854
+ companyId: company.id,
1855
+ isActive: true
1856
+ });
1857
+ await branchRepo.save(branch);
1858
+ return {
1859
+ company,
1860
+ branch
1861
+ };
1862
+ }
1863
+ return {
1864
+ company: null,
1865
+ branch: null
1866
+ };
1867
+ }
1868
+ async assignUserPermissions(userId, companyId, branchId, permissionRepo) {
1869
+ await permissionRepo.save(permissionRepo.create({
1870
+ userId,
1871
+ permissionType: user_org_permission_type_enum/* .PermissionType.COMPANY */.e.COMPANY,
1872
+ targetId: companyId
1873
+ }));
1874
+ if (branchId) {
1875
+ await permissionRepo.save(permissionRepo.create({
1876
+ userId,
1877
+ permissionType: user_org_permission_type_enum/* .PermissionType.BRANCH */.e.BRANCH,
1878
+ targetId: branchId
1879
+ }));
1880
+ }
1881
+ }
1882
+ async select(sessionId, companyId, branchId) {
1883
+ this.ensureCompanyFeatureEnabled();
1884
+ if (!this.sessionService) {
1885
+ throw new common_.BadRequestException({
1886
+ message: 'Session service not available',
1887
+ messageKey: message_keys/* .AUTH_MESSAGES.SESSION_NOT_AVAILABLE */.mK.SESSION_NOT_AVAILABLE
1888
+ });
1889
+ }
1890
+ const session = await this.sessionService.consumeSession(sessionId);
1891
+ if (!session) {
1892
+ throw new common_.UnauthorizedException({
1893
+ message: 'Invalid or expired session',
1894
+ messageKey: message_keys/* .AUTH_MESSAGES.SESSION_INVALID */.mK.SESSION_INVALID
1895
+ });
1896
+ }
1897
+ return await this.validateAndLoginWithCompany(session.userId, companyId, branchId);
1898
+ }
1899
+ async switchCompany(userId, companyId, branchId) {
1900
+ this.ensureCompanyFeatureEnabled();
1901
+ return await this.validateAndLoginWithCompany(userId, companyId, branchId);
1902
+ }
1903
+ async validateAndLoginWithCompany(userId, companyId, branchId) {
1904
+ const userRepository = await this.getUserRepository();
1905
+ const user = await userRepository.findOne({
1906
+ where: {
1907
+ id: userId
1908
+ }
1909
+ });
1910
+ if (!user) {
1911
+ throw new common_.NotFoundException({
1912
+ message: 'User not found',
1913
+ messageKey: message_keys/* .USER_MESSAGES.NOT_FOUND */.ny.NOT_FOUND
1914
+ });
1915
+ }
1916
+ const permissionRepository = await this.getCompanyScopedRepository(user_company_permission_entity/* .UserCompanyPermission */.I);
1917
+ const companyRepository = await this.getCompanyScopedRepository(company_entity/* .Company */.C);
1918
+ const branchRepository = await this.getCompanyScopedRepository(company_branch_entity/* .CompanyBranch */.A);
1919
+ if (!permissionRepository || !companyRepository || !branchRepository) {
1920
+ throw new common_.BadRequestException({
1921
+ message: 'Repositories not available',
1922
+ messageKey: constants_.SYSTEM_MESSAGES.REPOSITORY_NOT_AVAILABLE,
1923
+ messageVariables: {
1924
+ entity: 'Some'
1925
+ }
1926
+ });
1927
+ }
1928
+ const hasCompanyAccess = await permissionRepository.findOne({
1929
+ where: {
1930
+ userId,
1931
+ permissionType: user_org_permission_type_enum/* .PermissionType.COMPANY */.e.COMPANY,
1932
+ targetId: companyId
1933
+ }
1934
+ });
1935
+ if (!hasCompanyAccess) {
1936
+ throw new common_.ForbiddenException({
1937
+ message: 'No access to this company',
1938
+ messageKey: message_keys/* .AUTH_MESSAGES.COMPANY_NO_ACCESS */.mK.COMPANY_NO_ACCESS
1939
+ });
1940
+ }
1941
+ const company = await companyRepository.findOne({
1942
+ where: {
1943
+ id: companyId,
1944
+ isActive: true
1945
+ }
1946
+ });
1947
+ if (!company) {
1948
+ throw new common_.NotFoundException({
1949
+ message: 'Company not found or inactive',
1950
+ messageKey: message_keys/* .AUTH_MESSAGES.COMPANY_NOT_FOUND */.mK.COMPANY_NOT_FOUND
1951
+ });
1952
+ }
1953
+ const hasBranchAccess = await permissionRepository.findOne({
1954
+ where: {
1955
+ userId,
1956
+ permissionType: user_org_permission_type_enum/* .PermissionType.BRANCH */.e.BRANCH,
1957
+ targetId: branchId
1958
+ }
1959
+ });
1960
+ if (!hasBranchAccess) {
1961
+ throw new common_.ForbiddenException({
1962
+ message: 'No access to this branch',
1963
+ messageKey: message_keys/* .AUTH_MESSAGES.BRANCH_NO_ACCESS */.mK.BRANCH_NO_ACCESS
1964
+ });
1965
+ }
1966
+ const branch = await branchRepository.findOne({
1967
+ where: {
1968
+ id: branchId,
1969
+ companyId,
1970
+ isActive: true
1971
+ }
1972
+ });
1973
+ if (!branch) {
1974
+ throw new common_.NotFoundException({
1975
+ message: 'Branch not found or inactive',
1976
+ messageKey: message_keys/* .AUTH_MESSAGES.BRANCH_NOT_FOUND */.mK.BRANCH_NOT_FOUND
1977
+ });
1978
+ }
1979
+ const response = this.generateLoginResponseWithCompany(user, company, branch);
1980
+ this.publishAuthEvent(event_actions/* .AUTH_EVENT_ENTITIES.SESSION */.g.SESSION, event_actions/* .AUTH_EVENT_ACTIONS.COMPANY_SWITCHED */.o.COMPANY_SWITCHED, user, {
1981
+ companyId: company.id,
1982
+ branchId: branch.id
1983
+ });
1984
+ return response;
1985
+ }
1986
+ async refreshToken(refreshToken) {
1987
+ try {
1988
+ const payload = this.jwtService.verify(refreshToken, {
1989
+ secret: this.authConfig.getRefreshTokenSecret(),
1990
+ algorithms: [
1991
+ 'HS256'
1992
+ ]
1993
+ });
1994
+ if (await this.isTokenRevoked(payload.id, payload.iat)) {
1995
+ throw new common_.UnauthorizedException({
1996
+ message: 'Token has been revoked',
1997
+ messageKey: message_keys/* .AUTH_MESSAGES.TOKEN_REVOKED */.mK.TOKEN_REVOKED
1998
+ });
1999
+ }
2000
+ const userRepository = await this.getUserRepository();
2001
+ const user = await userRepository.findOne({
2002
+ where: {
2003
+ id: payload.id
2004
+ }
2005
+ });
2006
+ if (!user || !user.isActive) {
2007
+ throw new common_.UnauthorizedException({
2008
+ message: 'Invalid refresh token',
2009
+ messageKey: message_keys/* .AUTH_MESSAGES.TOKEN_INVALID */.mK.TOKEN_INVALID
2010
+ });
2011
+ }
2012
+ if (payload.companyId) {
2013
+ const companyRepository = await this.getCompanyScopedRepository(company_entity/* .Company */.C);
2014
+ const permissionRepository = await this.getCompanyScopedRepository(user_company_permission_entity/* .UserCompanyPermission */.I);
2015
+ if (companyRepository) {
2016
+ const company = await companyRepository.findOne({
2017
+ where: {
2018
+ id: payload.companyId,
2019
+ isActive: true
2020
+ }
2021
+ });
2022
+ if (!company) {
2023
+ throw new common_.UnauthorizedException({
2024
+ message: 'Company not found or inactive',
2025
+ messageKey: message_keys/* .AUTH_MESSAGES.COMPANY_NOT_FOUND */.mK.COMPANY_NOT_FOUND
2026
+ });
2027
+ }
2028
+ }
2029
+ if (permissionRepository) {
2030
+ const hasCompanyAccess = await permissionRepository.findOne({
2031
+ where: {
2032
+ userId: user.id,
2033
+ permissionType: user_org_permission_type_enum/* .PermissionType.COMPANY */.e.COMPANY,
2034
+ targetId: payload.companyId
2035
+ }
2036
+ });
2037
+ if (!hasCompanyAccess) {
2038
+ throw new common_.UnauthorizedException({
2039
+ message: 'No access to this company',
2040
+ messageKey: message_keys/* .AUTH_MESSAGES.COMPANY_NO_ACCESS */.mK.COMPANY_NO_ACCESS
2041
+ });
2042
+ }
2043
+ }
2044
+ if (payload.branchId) {
2045
+ const branchRepository = await this.getCompanyScopedRepository(company_branch_entity/* .CompanyBranch */.A);
2046
+ if (branchRepository) {
2047
+ const branch = await branchRepository.findOne({
2048
+ where: {
2049
+ id: payload.branchId,
2050
+ companyId: payload.companyId,
2051
+ isActive: true
2052
+ }
2053
+ });
2054
+ if (!branch) {
2055
+ throw new common_.UnauthorizedException({
2056
+ message: 'Branch not found or inactive',
2057
+ messageKey: message_keys/* .AUTH_MESSAGES.BRANCH_NOT_FOUND */.mK.BRANCH_NOT_FOUND
2058
+ });
2059
+ }
2060
+ }
2061
+ if (permissionRepository) {
2062
+ const hasBranchAccess = await permissionRepository.findOne({
2063
+ where: {
2064
+ userId: user.id,
2065
+ permissionType: user_org_permission_type_enum/* .PermissionType.BRANCH */.e.BRANCH,
2066
+ targetId: payload.branchId
2067
+ }
2068
+ });
2069
+ if (!hasBranchAccess) {
2070
+ throw new common_.UnauthorizedException({
2071
+ message: 'No access to this branch',
2072
+ messageKey: message_keys/* .AUTH_MESSAGES.BRANCH_NO_ACCESS */.mK.BRANCH_NO_ACCESS
2073
+ });
2074
+ }
2075
+ }
2076
+ }
2077
+ }
2078
+ const tokens = (0,token_helper/* .generateTokens */.e)(this.jwtService, this.authConfig, {
2079
+ id: user.id,
2080
+ email: user.email,
2081
+ type: 'access',
2082
+ profilePictureId: user.profilePictureId ?? undefined,
2083
+ ...payload.companyId && {
2084
+ companyId: payload.companyId
2085
+ },
2086
+ ...payload.branchId && {
2087
+ branchId: payload.branchId
2088
+ }
2089
+ });
2090
+ this.publishAuthEvent(event_actions/* .AUTH_EVENT_ENTITIES.SESSION */.g.SESSION, event_actions/* .AUTH_EVENT_ACTIONS.TOKEN_REFRESHED */.o.TOKEN_REFRESHED, user, {
2091
+ companyId: payload.companyId ?? null,
2092
+ branchId: payload.branchId ?? null
2093
+ });
2094
+ return tokens;
2095
+ } catch {
2096
+ throw new common_.UnauthorizedException({
2097
+ message: 'Invalid or expired refresh token',
2098
+ messageKey: message_keys/* .AUTH_MESSAGES.TOKEN_EXPIRED */.mK.TOKEN_EXPIRED
2099
+ });
2100
+ }
2101
+ }
2102
+ async changePassword(userId, currentPassword, newPassword) {
2103
+ const userRepository = await this.getUserRepository();
2104
+ const user = await userRepository.findOne({
2105
+ where: {
2106
+ id: userId
2107
+ }
2108
+ });
2109
+ if (!user) throw new common_.UnauthorizedException({
2110
+ message: 'User not found',
2111
+ messageKey: message_keys/* .USER_MESSAGES.NOT_FOUND */.ny.NOT_FOUND
2112
+ });
2113
+ if (!await external_bcrypt_.compare(currentPassword, user.password || '')) {
2114
+ throw new common_.UnauthorizedException({
2115
+ message: 'Current password is incorrect',
2116
+ messageKey: message_keys/* .AUTH_MESSAGES.PASSWORD_CHANGE_INVALID_CURRENT */.mK.PASSWORD_CHANGE_INVALID_CURRENT
2117
+ });
2118
+ }
2119
+ user.password = await external_bcrypt_.hash(newPassword, (/* inlined export .BCRYPT_SALT_ROUNDS */12));
2120
+ await userRepository.save(user);
2121
+ this.publishAuthEvent(event_actions/* .AUTH_EVENT_ENTITIES.USER */.g.USER, event_actions/* .AUTH_EVENT_ACTIONS.PASSWORD_CHANGED */.o.PASSWORD_CHANGED, user);
2122
+ }
2123
+ async logout(userId) {
2124
+ if (!this.cacheManager) {
2125
+ throw new common_.BadRequestException({
2126
+ message: 'Logout service temporarily unavailable. Please try again later.',
2127
+ messageKey: message_keys/* .AUTH_MESSAGES.LOGOUT_SERVICE_UNAVAILABLE */.mK.LOGOUT_SERVICE_UNAVAILABLE
2128
+ });
2129
+ }
2130
+ const revokedAt = Math.floor(Date.now() / 1000);
2131
+ const cacheKey = `${auth_constants/* .TOKEN_REVOKED_PREFIX */.EV}:${userId}`;
2132
+ const refreshTokenExpiry = this.authConfig.getRefreshTokenExpiration();
2133
+ const ttlMs = (0,token_helper/* .parseExpiryToMs */.o)(refreshTokenExpiry);
2134
+ await this.cacheManager.set(cacheKey, revokedAt, ttlMs);
2135
+ await (0,classes_.publishDomainEvent)({
2136
+ module: (/* inlined export .AUTH_EVENT_MODULE */"auth"),
2137
+ entity: event_actions/* .AUTH_EVENT_ENTITIES.SESSION */.g.SESSION,
2138
+ action: event_actions/* .AUTH_EVENT_ACTIONS.LOGGED_OUT */.o.LOGGED_OUT,
2139
+ ids: [
2140
+ userId
2141
+ ],
2142
+ user: {
2143
+ id: userId
2144
+ }
2145
+ });
2146
+ }
2147
+ async isTokenRevoked(userId, tokenIssuedAt) {
2148
+ if (!this.cacheManager || !tokenIssuedAt) {
2149
+ return false;
2150
+ }
2151
+ const cacheKey = `${auth_constants/* .TOKEN_REVOKED_PREFIX */.EV}:${userId}`;
2152
+ const revokedAt = await this.cacheManager.get(cacheKey);
2153
+ if (!revokedAt) {
2154
+ return false;
2155
+ }
2156
+ return tokenIssuedAt < revokedAt;
2157
+ }
2158
+ async getUserCompanies(userId) {
2159
+ this.ensureCompanyFeatureEnabled();
2160
+ const permissionRepository = await this.getCompanyScopedRepository(user_company_permission_entity/* .UserCompanyPermission */.I);
2161
+ const companyRepository = await this.getCompanyScopedRepository(company_entity/* .Company */.C);
2162
+ if (!permissionRepository || !companyRepository) {
2163
+ throw new common_.BadRequestException({
2164
+ message: 'Repositories not available',
2165
+ messageKey: constants_.SYSTEM_MESSAGES.REPOSITORY_NOT_AVAILABLE,
2166
+ messageVariables: {
2167
+ entity: 'Some'
2168
+ }
2169
+ });
2170
+ }
2171
+ const permissions = await permissionRepository.find({
2172
+ where: {
2173
+ userId,
2174
+ permissionType: user_org_permission_type_enum/* .PermissionType.COMPANY */.e.COMPANY
2175
+ }
2176
+ });
2177
+ const companyIds = permissions.map((p)=>p.targetId);
2178
+ if (companyIds.length === 0) return [];
2179
+ return companyRepository.createQueryBuilder('c').where('c.id IN (:...ids)', {
2180
+ ids: companyIds
2181
+ }).andWhere('c.is_active = :active', {
2182
+ active: true
2183
+ }).orderBy('c.name', 'ASC').getMany();
2184
+ }
2185
+ async getUserBranches(userId, companyId) {
2186
+ this.ensureCompanyFeatureEnabled();
2187
+ const permissionRepository = await this.getCompanyScopedRepository(user_company_permission_entity/* .UserCompanyPermission */.I);
2188
+ const branchRepository = await this.getCompanyScopedRepository(company_branch_entity/* .CompanyBranch */.A);
2189
+ if (!permissionRepository || !branchRepository) {
2190
+ throw new common_.BadRequestException({
2191
+ message: 'Repositories not available',
2192
+ messageKey: constants_.SYSTEM_MESSAGES.REPOSITORY_NOT_AVAILABLE,
2193
+ messageVariables: {
2194
+ entity: 'Some'
2195
+ }
2196
+ });
2197
+ }
2198
+ const companyPermission = await permissionRepository.findOne({
2199
+ where: {
2200
+ userId,
2201
+ permissionType: user_org_permission_type_enum/* .PermissionType.COMPANY */.e.COMPANY,
2202
+ targetId: companyId
2203
+ }
2204
+ });
2205
+ if (!companyPermission) {
2206
+ throw new common_.UnauthorizedException({
2207
+ message: 'No access to this company',
2208
+ messageKey: message_keys/* .AUTH_MESSAGES.COMPANY_NO_ACCESS */.mK.COMPANY_NO_ACCESS
2209
+ });
2210
+ }
2211
+ const branchPermissions = await permissionRepository.find({
2212
+ where: {
2213
+ userId,
2214
+ permissionType: user_org_permission_type_enum/* .PermissionType.BRANCH */.e.BRANCH
2215
+ }
2216
+ });
2217
+ const branchIds = branchPermissions.map((p)=>p.targetId);
2218
+ if (branchIds.length === 0) return [];
2219
+ return branchRepository.createQueryBuilder('b').where('b.id IN (:...ids)', {
2220
+ ids: branchIds
2221
+ }).andWhere('b.company_id = :companyId', {
2222
+ companyId
2223
+ }).andWhere('b.is_active = :active', {
2224
+ active: true
2225
+ }).orderBy('b.serial', 'ASC').addOrderBy('b.name', 'ASC').getMany();
2226
+ }
2227
+ async getCompanyById(companyId) {
2228
+ const companyRepository = await this.getCompanyScopedRepository(company_entity/* .Company */.C);
2229
+ if (!companyRepository) {
2230
+ return null;
2231
+ }
2232
+ return companyRepository.findOne({
2233
+ where: {
2234
+ id: companyId
2235
+ }
2236
+ });
2237
+ }
2238
+ async getBranchById(branchId) {
2239
+ const branchRepository = await this.getCompanyScopedRepository(company_branch_entity/* .CompanyBranch */.A);
2240
+ if (!branchRepository) {
2241
+ return null;
2242
+ }
2243
+ return branchRepository.findOne({
2244
+ where: {
2245
+ id: branchId
2246
+ }
2247
+ });
2248
+ }
2249
+ async getUserInfo(userId, companyId, branchId) {
2250
+ const userRepository = await this.getUserRepository();
2251
+ const user = await userRepository.findOne({
2252
+ where: {
2253
+ id: userId
2254
+ }
2255
+ });
2256
+ if (!user) throw new common_.UnauthorizedException({
2257
+ message: 'User not found',
2258
+ messageKey: message_keys/* .USER_MESSAGES.NOT_FOUND */.ny.NOT_FOUND
2259
+ });
2260
+ const response = {
2261
+ user: (0,auth_response_mapper/* .toUserInfo */.FV)(user)
2262
+ };
2263
+ if (this.isCompanyFeatureEnabled()) {
2264
+ if (!companyId) {
2265
+ throw new common_.UnauthorizedException({
2266
+ message: 'Company feature is enabled but user has no company assigned.',
2267
+ messageKey: message_keys/* .AUTH_MESSAGES.COMPANY_REQUIRED */.mK.COMPANY_REQUIRED
2268
+ });
2269
+ }
2270
+ const company = await this.getCompanyById(companyId);
2271
+ if (!company) throw new common_.UnauthorizedException({
2272
+ message: 'Company not found.',
2273
+ messageKey: message_keys/* .AUTH_MESSAGES.COMPANY_NOT_FOUND */.mK.COMPANY_NOT_FOUND
2274
+ });
2275
+ response.company = (0,auth_response_mapper/* .toCompanyInfo */.$C)(company);
2276
+ if (branchId) {
2277
+ const branch = await this.getBranchById(branchId);
2278
+ if (!branch) throw new common_.UnauthorizedException({
2279
+ message: 'Branch not found.',
2280
+ messageKey: message_keys/* .AUTH_MESSAGES.BRANCH_NOT_FOUND */.mK.BRANCH_NOT_FOUND
2281
+ });
2282
+ response.branch = (0,auth_response_mapper/* .toBranchInfo */.QH)(branch);
2283
+ }
2284
+ }
2285
+ return response;
2286
+ }
2287
+ ensureCompanyFeatureEnabled() {
2288
+ if (!this.isCompanyFeatureEnabled()) {
2289
+ throw new common_.BadRequestException({
2290
+ message: 'Company feature is not enabled',
2291
+ messageKey: message_keys/* .AUTH_MESSAGES.COMPANY_FEATURE_NOT_ENABLED */.mK.COMPANY_FEATURE_NOT_ENABLED
2292
+ });
2293
+ }
2294
+ }
2295
+ async validateUser(email, password) {
2296
+ const userRepository = await this.getUserRepository();
2297
+ const user = await userRepository.findOne({
2298
+ where: {
2299
+ email
2300
+ }
2301
+ });
2302
+ if (!user || !await external_bcrypt_.compare(password, user.password || '')) {
2303
+ throw new common_.UnauthorizedException({
2304
+ message: 'Invalid credentials',
2305
+ messageKey: message_keys/* .AUTH_MESSAGES.LOGIN_INVALID_CREDENTIALS */.mK.LOGIN_INVALID_CREDENTIALS
2306
+ });
2307
+ }
2308
+ user.lastLoginAt = new Date();
2309
+ await userRepository.save(user);
2310
+ return user;
2311
+ }
2312
+ generateLoginResponse(user) {
2313
+ const { accessToken, refreshToken } = (0,token_helper/* .generateTokens */.e)(this.jwtService, this.authConfig, {
2314
+ id: user.id,
2315
+ email: user.email,
2316
+ type: 'access'
2317
+ });
2318
+ this.sendLoginNotification(user.id);
2319
+ this.publishAuthEvent(event_actions/* .AUTH_EVENT_ENTITIES.SESSION */.g.SESSION, event_actions/* .AUTH_EVENT_ACTIONS.LOGGED_IN */.o.LOGGED_IN, user);
2320
+ return {
2321
+ accessToken,
2322
+ refreshToken,
2323
+ user: (0,auth_response_mapper/* .toUserInfo */.FV)(user)
2324
+ };
2325
+ }
2326
+ generateLoginResponseWithCompany(user, company, branch) {
2327
+ const { accessToken, refreshToken } = (0,token_helper/* .generateTokens */.e)(this.jwtService, this.authConfig, {
2328
+ id: user.id,
2329
+ email: user.email,
2330
+ type: 'access',
2331
+ companyId: company.id,
2332
+ branchId: branch?.id
2333
+ });
2334
+ this.sendLoginNotification(user.id, company.id);
2335
+ this.publishAuthEvent(event_actions/* .AUTH_EVENT_ENTITIES.SESSION */.g.SESSION, event_actions/* .AUTH_EVENT_ACTIONS.LOGGED_IN */.o.LOGGED_IN, user, {
2336
+ companyId: company.id,
2337
+ branchId: branch?.id ?? null
2338
+ });
2339
+ return {
2340
+ accessToken,
2341
+ refreshToken,
2342
+ user: (0,auth_response_mapper/* .toUserInfo */.FV)(user),
2343
+ company: (0,auth_response_mapper/* .toCompanyInfo */.$C)(company),
2344
+ branch: branch ? (0,auth_response_mapper/* .toBranchInfo */.QH)(branch) : undefined
2345
+ };
2346
+ }
2347
+ sendLoginNotification(userId, companyId) {
2348
+ if (!this.notificationAdapter) return;
2349
+ this.notificationAdapter.send({
2350
+ userId,
2351
+ title: 'Login successful',
2352
+ message: 'You have successfully logged in to your account.',
2353
+ type: __rspack_external__flusys_nestjs_shared_enums_327421f8.NotificationType.INFO,
2354
+ companyId,
2355
+ realtime: false
2356
+ }).catch(()=>{
2357
+ // Silent failure - notification is non-critical
2358
+ });
2359
+ }
2360
+ async generateCompanySelectionResponse(user, companies, branches) {
2361
+ if (!this.sessionService) {
2362
+ throw new common_.BadRequestException({
2363
+ message: 'Session service not available',
2364
+ messageKey: message_keys/* .AUTH_MESSAGES.SESSION_NOT_AVAILABLE */.mK.SESSION_NOT_AVAILABLE
2365
+ });
2366
+ }
2367
+ const sessionId = await this.sessionService.createSession(user.id);
2368
+ const companiesWithBranches = companies.map((company)=>({
2369
+ ...(0,auth_response_mapper/* .toCompanyInfo */.$C)(company),
2370
+ isActive: company.isActive,
2371
+ branches: branches.filter((b)=>b.companyId === company.id).map((b)=>({
2372
+ ...(0,auth_response_mapper/* .toBranchInfo */.QH)(b),
2373
+ isActive: b.isActive
2374
+ }))
2375
+ }));
2376
+ return {
2377
+ requiresSelection: true,
2378
+ sessionId,
2379
+ expiresAt: new Date(Date.now() + 5 * 60 * 1000),
2380
+ user: (0,auth_response_mapper/* .toUserInfo */.FV)(user),
2381
+ companies: companiesWithBranches
2382
+ };
2383
+ }
2384
+ generateRegistrationResponse(user) {
2385
+ const response = {
2386
+ ...this.generateLoginResponse(user),
2387
+ requiresEmailVerification: false
2388
+ };
2389
+ this.publishAuthEvent(event_actions/* .AUTH_EVENT_ENTITIES.USER */.g.USER, event_actions/* .AUTH_EVENT_ACTIONS.REGISTERED */.o.REGISTERED, user);
2390
+ return response;
2391
+ }
2392
+ generateRegistrationResponseWithCompany(user, company, branch) {
2393
+ const response = {
2394
+ ...this.generateLoginResponseWithCompany(user, company, branch),
2395
+ requiresEmailVerification: false
2396
+ };
2397
+ this.publishAuthEvent(event_actions/* .AUTH_EVENT_ENTITIES.USER */.g.USER, event_actions/* .AUTH_EVENT_ACTIONS.REGISTERED */.o.REGISTERED, user, {
2398
+ companyId: company.id,
2399
+ branchId: branch?.id ?? null
2400
+ });
2401
+ return response;
2402
+ }
2403
+ /** Never awaited - a login must not wait on, or fail because of, the event bus */ publishAuthEvent(entity, action, user, metadata = {}) {
2404
+ void (0,classes_.publishDomainEvent)({
2405
+ module: (/* inlined export .AUTH_EVENT_MODULE */"auth"),
2406
+ entity,
2407
+ action,
2408
+ ids: [
2409
+ user.id
2410
+ ],
2411
+ metadata: {
2412
+ email: user.email,
2413
+ ...metadata
2414
+ },
2415
+ user: {
2416
+ id: user.id,
2417
+ email: user.email
2418
+ }
2419
+ });
2420
+ }
2421
+ }
2422
+ _ts_decorate([
2423
+ (0,nestjs_shared_.LogAction)({
2424
+ action: 'auth.login',
2425
+ module: 'auth',
2426
+ includeParams: false
2427
+ }),
2428
+ _ts_metadata("design:type", Function),
2429
+ _ts_metadata("design:paramtypes", [
2430
+ String,
2431
+ String
2432
+ ]),
2433
+ _ts_metadata("design:returntype", Promise)
2434
+ ], AuthenticationService.prototype, "login", null);
2435
+ _ts_decorate([
2436
+ (0,nestjs_shared_.LogAction)({
2437
+ action: 'auth.register',
2438
+ module: 'auth',
2439
+ includeParams: false
2440
+ }),
2441
+ _ts_metadata("design:type", Function),
2442
+ _ts_metadata("design:paramtypes", [
2443
+ typeof authentication_dto/* .RegistrationDto */.xG === "undefined" ? Object : authentication_dto/* .RegistrationDto */.xG,
2444
+ String
2445
+ ]),
2446
+ _ts_metadata("design:returntype", Promise)
2447
+ ], AuthenticationService.prototype, "register", null);
2448
+ _ts_decorate([
2449
+ (0,nestjs_shared_.LogAction)({
2450
+ action: 'auth.createUser',
2451
+ module: 'auth',
2452
+ includeParams: false
2453
+ }),
2454
+ _ts_metadata("design:type", Function),
2455
+ _ts_metadata("design:paramtypes", [
2456
+ typeof authentication_dto/* .RegistrationDto */.xG === "undefined" ? Object : authentication_dto/* .RegistrationDto */.xG
2457
+ ]),
2458
+ _ts_metadata("design:returntype", Promise)
2459
+ ], AuthenticationService.prototype, "createUserDirectly", null);
2460
+ _ts_decorate([
2461
+ (0,nestjs_shared_.LogAction)({
2462
+ action: 'auth.createUserFromPending',
2463
+ module: 'auth',
2464
+ includeParams: false
2465
+ }),
2466
+ _ts_metadata("design:type", Function),
2467
+ _ts_metadata("design:paramtypes", [
2468
+ typeof pending_registration_entity/* .PendingRegistration */.N === "undefined" ? Object : pending_registration_entity/* .PendingRegistration */.N
2469
+ ]),
2470
+ _ts_metadata("design:returntype", Promise)
2471
+ ], AuthenticationService.prototype, "createUserFromPendingRegistration", null);
2472
+ _ts_decorate([
2473
+ (0,nestjs_shared_.LogAction)({
2474
+ action: 'auth.companySwitch',
2475
+ module: 'auth'
2476
+ }),
2477
+ _ts_metadata("design:type", Function),
2478
+ _ts_metadata("design:paramtypes", [
2479
+ String,
2480
+ String,
2481
+ String
2482
+ ]),
2483
+ _ts_metadata("design:returntype", Promise)
2484
+ ], AuthenticationService.prototype, "validateAndLoginWithCompany", null);
2485
+ _ts_decorate([
2486
+ (0,nestjs_shared_.LogAction)({
2487
+ action: 'auth.refreshToken',
2488
+ module: 'auth',
2489
+ includeParams: false
2490
+ }),
2491
+ _ts_metadata("design:type", Function),
2492
+ _ts_metadata("design:paramtypes", [
2493
+ String
2494
+ ]),
2495
+ _ts_metadata("design:returntype", Promise)
2496
+ ], AuthenticationService.prototype, "refreshToken", null);
2497
+ _ts_decorate([
2498
+ (0,nestjs_shared_.LogAction)({
2499
+ action: 'auth.changePassword',
2500
+ module: 'auth',
2501
+ includeParams: false
2502
+ }),
2503
+ _ts_metadata("design:type", Function),
2504
+ _ts_metadata("design:paramtypes", [
2505
+ String,
2506
+ String,
2507
+ String
2508
+ ]),
2509
+ _ts_metadata("design:returntype", Promise)
2510
+ ], AuthenticationService.prototype, "changePassword", null);
2511
+ _ts_decorate([
2512
+ (0,nestjs_shared_.LogAction)({
2513
+ action: 'auth.logout',
2514
+ module: 'auth'
2515
+ }),
2516
+ _ts_metadata("design:type", Function),
2517
+ _ts_metadata("design:paramtypes", [
2518
+ String
2519
+ ]),
2520
+ _ts_metadata("design:returntype", Promise)
2521
+ ], AuthenticationService.prototype, "logout", null);
2522
+ AuthenticationService = _ts_decorate([
2523
+ (0,common_.Injectable)({
2524
+ scope: common_.Scope.REQUEST
2525
+ }),
2526
+ _ts_param(0, (0,common_.Inject)(jwt_.JwtService)),
2527
+ _ts_param(1, (0,common_.Inject)(auth_config_service/* .AuthConfigService */.W)),
2528
+ _ts_param(2, (0,common_.Optional)()),
2529
+ _ts_param(2, (0,common_.Inject)('CACHE_INSTANCE')),
2530
+ _ts_param(3, (0,common_.Optional)()),
2531
+ _ts_param(3, (0,common_.Inject)(auth_datasource_provider/* .AuthDataSourceProvider */.v)),
2532
+ _ts_param(4, (0,common_.Optional)()),
2533
+ _ts_param(4, (0,common_.Inject)(company_selection_session_service/* .CompanySelectionSessionService */.v)),
2534
+ _ts_param(5, (0,common_.Optional)()),
2535
+ _ts_param(5, (0,common_.Inject)(auth_email_service/* .AuthEmailService */.G)),
2536
+ _ts_param(6, (0,common_.Optional)()),
2537
+ _ts_param(6, (0,common_.Inject)(auth_constants/* .USER_ENRICHER */.jt)),
2538
+ _ts_param(7, (0,common_.Optional)()),
2539
+ _ts_param(7, (0,common_.Inject)(interfaces_.NOTIFICATION_ADAPTER)),
2540
+ _ts_metadata("design:type", Function),
2541
+ _ts_metadata("design:paramtypes", [
2542
+ typeof jwt_.JwtService === "undefined" ? Object : jwt_.JwtService,
2543
+ typeof auth_config_service/* .AuthConfigService */.W === "undefined" ? Object : auth_config_service/* .AuthConfigService */.W,
2544
+ typeof classes_.HybridCache === "undefined" ? Object : classes_.HybridCache,
2545
+ typeof auth_datasource_provider/* .AuthDataSourceProvider */.v === "undefined" ? Object : auth_datasource_provider/* .AuthDataSourceProvider */.v,
2546
+ typeof company_selection_session_service/* .CompanySelectionSessionService */.v === "undefined" ? Object : company_selection_session_service/* .CompanySelectionSessionService */.v,
2547
+ typeof auth_email_service/* .AuthEmailService */.G === "undefined" ? Object : auth_email_service/* .AuthEmailService */.G,
2548
+ typeof IUserEnricher === "undefined" ? Object : IUserEnricher,
2549
+ typeof INotificationAdapter === "undefined" ? Object : INotificationAdapter
2550
+ ])
2551
+ ], AuthenticationService);
2552
+
2553
+
2554
+ },
2555
+ 5402(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
2556
+ /* import */ var _flusys_nestjs_shared_classes__rspack_import_0 = __webpack_require__(6937);
2557
+ /* import */ var _flusys_nestjs_shared_interfaces__rspack_import_1 = __webpack_require__(5103);
2558
+ /* import */ var _flusys_nestjs_shared_modules__rspack_import_2 = __webpack_require__(1236);
2559
+ /* import */ var _flusys_nestjs_shared_utils__rspack_import_3 = __webpack_require__(9216);
2560
+ /* import */ var _nestjs_common__rspack_import_4 = __webpack_require__(6157);
2561
+ /* import */ var typeorm__rspack_import_5 = __webpack_require__(7158);
2562
+ /* import */ var _config_index_js__rspack_import_10 = __webpack_require__(7987);
2563
+ /* import */ var _config_index_js__rspack_import_11 = __webpack_require__(5363);
2564
+ /* import */ var _entities_company_branch_entity_js__rspack_import_6 = __webpack_require__(1923);
2565
+ /* import */ var _entities_user_company_permission_entity_js__rspack_import_7 = __webpack_require__(2377);
2566
+ /* import */ var _auth_config_service_js__rspack_import_8 = __webpack_require__(6514);
2567
+ /* import */ var _auth_datasource_provider_js__rspack_import_9 = __webpack_require__(2732);
2568
+ function _ts_decorate(decorators, target, key, desc) {
2569
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2570
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2571
+ r = Reflect.decorate(decorators, target, key, desc);
2572
+ } else {
2573
+ for(var i = decorators.length - 1; i >= 0; i--){
2574
+ if (d = decorators[i]) {
2575
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2576
+ }
2577
+ }
2578
+ }
2579
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2580
+ }
2581
+ function _ts_metadata(metadataKey, metadataValue) {
2582
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
2583
+ return Reflect.metadata(metadataKey, metadataValue);
2584
+ }
2585
+ }
2586
+ function _ts_param(paramIndex, decorator) {
2587
+ return function(target, key) {
2588
+ decorator(target, key, paramIndex);
2589
+ };
2590
+ }
2591
+
2592
+
2593
+
2594
+
2595
+
2596
+
2597
+
2598
+
2599
+
2600
+
2601
+
2602
+ class BranchService extends _flusys_nestjs_shared_classes__rspack_import_0.ApiService {
2603
+ cacheManager;
2604
+ utilsService;
2605
+ authConfig;
2606
+ permissionSyncAdapter;
2607
+ constructor(cacheManager, utilsService, dataSourceProvider, authConfig, permissionSyncAdapter){
2608
+ super(_config_index_js__rspack_import_10/* .AUTH_EVENT_ENTITIES.COMPANY_BRANCH */.g.COMPANY_BRANCH, cacheManager, utilsService, BranchService.name, true, (/* inlined export .AUTH_EVENT_MODULE */"auth"), dataSourceProvider, _entities_company_branch_entity_js__rspack_import_6/* .CompanyBranch */.A), this.cacheManager = cacheManager, this.utilsService = utilsService, this.authConfig = authConfig, this.permissionSyncAdapter = permissionSyncAdapter;
2609
+ }
2610
+ async beforeDeleteOperation(dto, user, queryRunner) {
2611
+ const branchIds = Array.isArray(dto.id) ? dto.id : [
2612
+ dto.id
2613
+ ];
2614
+ await this.ensureDataSourceRepository();
2615
+ const readonlyBranches = await this.repository.find({
2616
+ where: {
2617
+ id: (0,typeorm__rspack_import_5.In)(branchIds),
2618
+ readOnly: true,
2619
+ deletedAt: (0,typeorm__rspack_import_5.IsNull)()
2620
+ }
2621
+ });
2622
+ if (readonlyBranches.length > 0) {
2623
+ const names = readonlyBranches.map((b)=>b.name).join(', ');
2624
+ throw new _nestjs_common__rspack_import_4.ForbiddenException({
2625
+ message: `Cannot delete readonly branch(es): ${names}`,
2626
+ messageKey: _config_index_js__rspack_import_11/* .BRANCH_MESSAGES.READONLY_DELETE_FORBIDDEN */.W1.READONLY_DELETE_FORBIDDEN,
2627
+ messageVariables: {
2628
+ names
2629
+ }
2630
+ });
2631
+ }
2632
+ await queryRunner.manager.getRepository(_entities_user_company_permission_entity_js__rspack_import_7/* .UserCompanyPermission */.I).delete({
2633
+ targetId: (0,typeorm__rspack_import_5.In)(branchIds)
2634
+ });
2635
+ if (!this.permissionSyncAdapter?.onBranchDeleted) {
2636
+ return;
2637
+ }
2638
+ const rows = await queryRunner.manager.getRepository(_entities_company_branch_entity_js__rspack_import_6/* .CompanyBranch */.A).find({
2639
+ where: {
2640
+ id: (0,typeorm__rspack_import_5.In)(branchIds)
2641
+ },
2642
+ select: [
2643
+ 'id',
2644
+ 'companyId'
2645
+ ]
2646
+ });
2647
+ await Promise.all(rows.map((row)=>this.permissionSyncAdapter.onBranchDeleted(row.id, row.companyId)));
2648
+ }
2649
+ // Query Customization
2650
+ async getSelectQuery(query, _user, select) {
2651
+ if (!select?.length) {
2652
+ select = [
2653
+ 'id',
2654
+ 'name',
2655
+ 'slug',
2656
+ 'email',
2657
+ 'phone',
2658
+ 'isActive',
2659
+ 'readOnly',
2660
+ 'createdAt'
2661
+ ];
2662
+ }
2663
+ query.select(select.map((f)=>`${this.entityName}.${f}`));
2664
+ return {
2665
+ query,
2666
+ isRaw: false
2667
+ };
2668
+ }
2669
+ async getGlobalSearchQuery(query, search) {
2670
+ query.andWhere('(company_branch.name LIKE :search OR company_branch.slug LIKE :search OR company_branch.email LIKE :search)', {
2671
+ search: `%${search}%`
2672
+ });
2673
+ return {
2674
+ query,
2675
+ isRaw: false
2676
+ };
2677
+ }
2678
+ async getExtraManipulateQuery(query, filterDto, user) {
2679
+ const result = await super.getExtraManipulateQuery(query, filterDto, user);
2680
+ // Only apply company filter if companyId is NOT explicitly provided in filter
2681
+ // This prevents dual filtering when user selects a specific company
2682
+ if (!filterDto?.filter?.companyId) {
2683
+ (0,_flusys_nestjs_shared_utils__rspack_import_3.applyCompanyFilter)(query, {
2684
+ isCompanyFeatureEnabled: this.authConfig.isCompanyFeatureEnabled(),
2685
+ entityAlias: 'company_branch',
2686
+ columnName: 'company_id'
2687
+ }, user);
2688
+ }
2689
+ return result;
2690
+ }
2691
+ }
2692
+ BranchService = _ts_decorate([
2693
+ (0,_nestjs_common__rspack_import_4.Injectable)({
2694
+ scope: _nestjs_common__rspack_import_4.Scope.REQUEST
2695
+ }),
2696
+ _ts_param(0, (0,_nestjs_common__rspack_import_4.Inject)('CACHE_INSTANCE')),
2697
+ _ts_param(1, (0,_nestjs_common__rspack_import_4.Inject)(_flusys_nestjs_shared_modules__rspack_import_2.UtilsService)),
2698
+ _ts_param(2, (0,_nestjs_common__rspack_import_4.Inject)(_auth_datasource_provider_js__rspack_import_9/* .AuthDataSourceProvider */.v)),
2699
+ _ts_param(3, (0,_nestjs_common__rspack_import_4.Inject)(_auth_config_service_js__rspack_import_8/* .AuthConfigService */.W)),
2700
+ _ts_param(4, (0,_nestjs_common__rspack_import_4.Optional)()),
2701
+ _ts_param(4, (0,_nestjs_common__rspack_import_4.Inject)(_flusys_nestjs_shared_interfaces__rspack_import_1.PERMISSION_SYNC_ADAPTER)),
2702
+ _ts_metadata("design:type", Function),
2703
+ _ts_metadata("design:paramtypes", [
2704
+ typeof _flusys_nestjs_shared_classes__rspack_import_0.HybridCache === "undefined" ? Object : _flusys_nestjs_shared_classes__rspack_import_0.HybridCache,
2705
+ typeof _flusys_nestjs_shared_modules__rspack_import_2.UtilsService === "undefined" ? Object : _flusys_nestjs_shared_modules__rspack_import_2.UtilsService,
2706
+ typeof _auth_datasource_provider_js__rspack_import_9/* .AuthDataSourceProvider */.v === "undefined" ? Object : _auth_datasource_provider_js__rspack_import_9/* .AuthDataSourceProvider */.v,
2707
+ typeof _auth_config_service_js__rspack_import_8/* .AuthConfigService */.W === "undefined" ? Object : _auth_config_service_js__rspack_import_8/* .AuthConfigService */.W,
2708
+ typeof IPermissionSyncAdapter === "undefined" ? Object : IPermissionSyncAdapter
2709
+ ])
2710
+ ], BranchService);
2711
+
2712
+ __webpack_require__.d(__webpack_exports__, {
2713
+ O: () => (BranchService)
2714
+ });
2715
+
2716
+
2717
+ },
2718
+ 5811(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
2719
+ /* import */ var _flusys_nestjs_shared__rspack_import_0 = __webpack_require__(3422);
2720
+ /* import */ var _flusys_nestjs_shared_classes__rspack_import_1 = __webpack_require__(6937);
2721
+ /* import */ var _nestjs_common__rspack_import_2 = __webpack_require__(6157);
2722
+ /* import */ var crypto__rspack_import_3 = __webpack_require__(7823);
2723
+ /* import */ var _config_auth_constants_js__rspack_import_4 = __webpack_require__(5588);
2724
+ function _ts_decorate(decorators, target, key, desc) {
2725
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2726
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2727
+ r = Reflect.decorate(decorators, target, key, desc);
2728
+ } else {
2729
+ for(var i = decorators.length - 1; i >= 0; i--){
2730
+ if (d = decorators[i]) {
2731
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2732
+ }
2733
+ }
2734
+ }
2735
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2736
+ }
2737
+ function _ts_metadata(metadataKey, metadataValue) {
2738
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
2739
+ return Reflect.metadata(metadataKey, metadataValue);
2740
+ }
2741
+ }
2742
+ function _ts_param(paramIndex, decorator) {
2743
+ return function(target, key) {
2744
+ decorator(target, key, paramIndex);
2745
+ };
2746
+ }
2747
+
2748
+
2749
+
2750
+
2751
+
2752
+ const SESSION_TTL_MS = 5 * 60 * 1000; // 5 minutes
2753
+ class CompanySelectionSessionService {
2754
+ cacheManager;
2755
+ constructor(cacheManager){
2756
+ this.cacheManager = cacheManager;
2757
+ }
2758
+ async createSession(userId) {
2759
+ const sessionId = (0,crypto__rspack_import_3.randomUUID)();
2760
+ const now = new Date();
2761
+ const expiresAt = new Date(now.getTime() + SESSION_TTL_MS);
2762
+ const session = {
2763
+ sessionId,
2764
+ userId,
2765
+ createdAt: now,
2766
+ expiresAt
2767
+ };
2768
+ await this.cacheManager.set(this.getKey(sessionId), session, SESSION_TTL_MS);
2769
+ return sessionId;
2770
+ }
2771
+ /**
2772
+ * Get session by ID (does not consume/delete)
2773
+ */ async getSession(sessionId) {
2774
+ const session = await this.cacheManager.get(this.getKey(sessionId));
2775
+ if (!session) return null;
2776
+ // Check if expired (extra safety, cache should handle TTL)
2777
+ if (new Date() > new Date(session.expiresAt)) {
2778
+ await this.deleteSession(sessionId);
2779
+ return null;
2780
+ }
2781
+ return session;
2782
+ }
2783
+ async consumeSession(sessionId) {
2784
+ const session = await this.getSession(sessionId);
2785
+ if (session) {
2786
+ await this.deleteSession(sessionId);
2787
+ }
2788
+ return session;
2789
+ }
2790
+ /**
2791
+ * Delete session
2792
+ */ async deleteSession(sessionId) {
2793
+ await this.cacheManager.del(this.getKey(sessionId));
2794
+ }
2795
+ /**
2796
+ * Get cache key for session
2797
+ */ getKey(sessionId) {
2798
+ return `${_config_auth_constants_js__rspack_import_4/* .SESSION_CACHE_PREFIX */.Vl}:${sessionId}`;
2799
+ }
2800
+ }
2801
+ _ts_decorate([
2802
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
2803
+ action: 'session.create',
2804
+ module: 'auth'
2805
+ }),
2806
+ _ts_metadata("design:type", Function),
2807
+ _ts_metadata("design:paramtypes", [
2808
+ String
2809
+ ]),
2810
+ _ts_metadata("design:returntype", Promise)
2811
+ ], CompanySelectionSessionService.prototype, "createSession", null);
2812
+ _ts_decorate([
2813
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
2814
+ action: 'session.consume',
2815
+ module: 'auth'
2816
+ }),
2817
+ _ts_metadata("design:type", Function),
2818
+ _ts_metadata("design:paramtypes", [
2819
+ String
2820
+ ]),
2821
+ _ts_metadata("design:returntype", Promise)
2822
+ ], CompanySelectionSessionService.prototype, "consumeSession", null);
2823
+ CompanySelectionSessionService = _ts_decorate([
2824
+ (0,_nestjs_common__rspack_import_2.Injectable)(),
2825
+ _ts_param(0, (0,_nestjs_common__rspack_import_2.Inject)('CACHE_INSTANCE')),
2826
+ _ts_metadata("design:type", Function),
2827
+ _ts_metadata("design:paramtypes", [
2828
+ typeof _flusys_nestjs_shared_classes__rspack_import_1.HybridCache === "undefined" ? Object : _flusys_nestjs_shared_classes__rspack_import_1.HybridCache
2829
+ ])
2830
+ ], CompanySelectionSessionService);
2831
+
2832
+ __webpack_require__.d(__webpack_exports__, {
2833
+ v: () => (CompanySelectionSessionService)
2834
+ });
2835
+
2836
+
2837
+ },
2838
+ 9201(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
2839
+ /* import */ var _flusys_nestjs_shared_classes__rspack_import_0 = __webpack_require__(6937);
2840
+ /* import */ var _flusys_nestjs_shared_interfaces__rspack_import_1 = __webpack_require__(5103);
2841
+ /* import */ var _flusys_nestjs_shared_modules__rspack_import_2 = __webpack_require__(1236);
2842
+ /* import */ var _nestjs_common__rspack_import_3 = __webpack_require__(6157);
2843
+ /* import */ var typeorm__rspack_import_4 = __webpack_require__(7158);
2844
+ /* import */ var _config_index_js__rspack_import_9 = __webpack_require__(7987);
2845
+ /* import */ var _config_index_js__rspack_import_10 = __webpack_require__(5363);
2846
+ /* import */ var _entities_company_branch_entity_js__rspack_import_5 = __webpack_require__(1923);
2847
+ /* import */ var _entities_company_entity_js__rspack_import_6 = __webpack_require__(8538);
2848
+ /* import */ var _entities_user_company_permission_entity_js__rspack_import_7 = __webpack_require__(2377);
2849
+ /* import */ var _auth_datasource_provider_js__rspack_import_8 = __webpack_require__(2732);
2850
+ function _ts_decorate(decorators, target, key, desc) {
2851
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2852
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2853
+ r = Reflect.decorate(decorators, target, key, desc);
2854
+ } else {
2855
+ for(var i = decorators.length - 1; i >= 0; i--){
2856
+ if (d = decorators[i]) {
2857
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
2858
+ }
2859
+ }
2860
+ }
2861
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2862
+ }
2863
+ function _ts_metadata(metadataKey, metadataValue) {
2864
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
2865
+ return Reflect.metadata(metadataKey, metadataValue);
2866
+ }
2867
+ }
2868
+ function _ts_param(paramIndex, decorator) {
2869
+ return function(target, key) {
2870
+ decorator(target, key, paramIndex);
2871
+ };
2872
+ }
2873
+
2874
+
2875
+
2876
+
2877
+
2878
+
2879
+
2880
+
2881
+
2882
+
2883
+ class CompanyService extends _flusys_nestjs_shared_classes__rspack_import_0.ApiService {
2884
+ cacheManager;
2885
+ utilsService;
2886
+ permissionSyncAdapter;
2887
+ constructor(cacheManager, utilsService, dataSourceProvider, permissionSyncAdapter){
2888
+ super(_config_index_js__rspack_import_9/* .AUTH_EVENT_ENTITIES.COMPANY */.g.COMPANY, cacheManager, utilsService, CompanyService.name, true, (/* inlined export .AUTH_EVENT_MODULE */"auth"), dataSourceProvider, _entities_company_entity_js__rspack_import_6/* .Company */.C), this.cacheManager = cacheManager, this.utilsService = utilsService, this.permissionSyncAdapter = permissionSyncAdapter;
2889
+ }
2890
+ async beforeDeleteOperation(dto, user, queryRunner) {
2891
+ const companyIds = Array.isArray(dto.id) ? dto.id : [
2892
+ dto.id
2893
+ ];
2894
+ await this.ensureDataSourceRepository();
2895
+ const readonlyCompanies = await this.repository.find({
2896
+ where: {
2897
+ id: (0,typeorm__rspack_import_4.In)(companyIds),
2898
+ readOnly: true,
2899
+ deletedAt: (0,typeorm__rspack_import_4.IsNull)()
2900
+ }
2901
+ });
2902
+ if (readonlyCompanies.length > 0) {
2903
+ const names = readonlyCompanies.map((c)=>c.name).join(', ');
2904
+ throw new _nestjs_common__rspack_import_3.ForbiddenException({
2905
+ message: `Cannot delete readonly company(ies): ${names}`,
2906
+ messageKey: _config_index_js__rspack_import_10/* .COMPANY_MESSAGES.READONLY_DELETE_FORBIDDEN */.hg.READONLY_DELETE_FORBIDDEN,
2907
+ messageVariables: {
2908
+ names
2909
+ }
2910
+ });
2911
+ }
2912
+ const branchRows = await queryRunner.manager.getRepository(_entities_company_branch_entity_js__rspack_import_5/* .CompanyBranch */.A).find({
2913
+ where: {
2914
+ companyId: (0,typeorm__rspack_import_4.In)(companyIds)
2915
+ },
2916
+ select: [
2917
+ 'id'
2918
+ ]
2919
+ });
2920
+ const targetIds = [
2921
+ ...companyIds,
2922
+ ...branchRows.map((row)=>row.id)
2923
+ ];
2924
+ await queryRunner.manager.getRepository(_entities_user_company_permission_entity_js__rspack_import_7/* .UserCompanyPermission */.I).delete({
2925
+ targetId: (0,typeorm__rspack_import_4.In)(targetIds)
2926
+ });
2927
+ if (!this.permissionSyncAdapter?.onCompanyDeleted) {
2928
+ return;
2929
+ }
2930
+ await Promise.all(companyIds.map((companyId)=>this.permissionSyncAdapter.onCompanyDeleted(companyId)));
2931
+ }
2932
+ // Query Customization
2933
+ async getSelectQuery(query, _user, select) {
2934
+ if (!select?.length) {
2935
+ select = [
2936
+ 'id',
2937
+ 'name',
2938
+ 'slug',
2939
+ 'email',
2940
+ 'phone',
2941
+ 'isActive',
2942
+ 'readOnly',
2943
+ 'createdAt'
2944
+ ];
2945
+ }
2946
+ query.select(select.map((f)=>`${this.entityName}.${f}`));
2947
+ return {
2948
+ query,
2949
+ isRaw: false
2950
+ };
2951
+ }
2952
+ async getGlobalSearchQuery(query, search) {
2953
+ query.andWhere('(company.name LIKE :search OR company.slug LIKE :search OR company.email LIKE :search)', {
2954
+ search: `%${search}%`
2955
+ });
2956
+ return {
2957
+ query,
2958
+ isRaw: false
2959
+ };
2960
+ }
2961
+ }
2962
+ CompanyService = _ts_decorate([
2963
+ (0,_nestjs_common__rspack_import_3.Injectable)({
2964
+ scope: _nestjs_common__rspack_import_3.Scope.REQUEST
2965
+ }),
2966
+ _ts_param(0, (0,_nestjs_common__rspack_import_3.Inject)('CACHE_INSTANCE')),
2967
+ _ts_param(1, (0,_nestjs_common__rspack_import_3.Inject)(_flusys_nestjs_shared_modules__rspack_import_2.UtilsService)),
2968
+ _ts_param(2, (0,_nestjs_common__rspack_import_3.Inject)(_auth_datasource_provider_js__rspack_import_8/* .AuthDataSourceProvider */.v)),
2969
+ _ts_param(3, (0,_nestjs_common__rspack_import_3.Optional)()),
2970
+ _ts_param(3, (0,_nestjs_common__rspack_import_3.Inject)(_flusys_nestjs_shared_interfaces__rspack_import_1.PERMISSION_SYNC_ADAPTER)),
2971
+ _ts_metadata("design:type", Function),
2972
+ _ts_metadata("design:paramtypes", [
2973
+ typeof _flusys_nestjs_shared_classes__rspack_import_0.HybridCache === "undefined" ? Object : _flusys_nestjs_shared_classes__rspack_import_0.HybridCache,
2974
+ typeof _flusys_nestjs_shared_modules__rspack_import_2.UtilsService === "undefined" ? Object : _flusys_nestjs_shared_modules__rspack_import_2.UtilsService,
2975
+ typeof _auth_datasource_provider_js__rspack_import_8/* .AuthDataSourceProvider */.v === "undefined" ? Object : _auth_datasource_provider_js__rspack_import_8/* .AuthDataSourceProvider */.v,
2976
+ typeof IPermissionSyncAdapter === "undefined" ? Object : IPermissionSyncAdapter
2977
+ ])
2978
+ ], CompanyService);
2979
+
2980
+ __webpack_require__.d(__webpack_exports__, {
2981
+ B: () => (CompanyService)
2982
+ });
2983
+
2984
+
2985
+ },
2986
+ 8275(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
2987
+ /* import */ var _flusys_nestjs_shared_classes__rspack_import_0 = __webpack_require__(6937);
2988
+ /* import */ var _flusys_nestjs_shared_modules__rspack_import_1 = __webpack_require__(1236);
2989
+ /* import */ var _nestjs_common__rspack_import_2 = __webpack_require__(6157);
2990
+ /* import */ var typeorm__rspack_import_3 = __webpack_require__(7158);
2991
+ /* import */ var _config_index_js__rspack_import_6 = __webpack_require__(7987);
2992
+ /* import */ var _config_index_js__rspack_import_7 = __webpack_require__(5363);
2993
+ /* import */ var _entities_social_auth_config_entity_js__rspack_import_4 = __webpack_require__(2020);
2994
+ /* import */ var _auth_datasource_provider_js__rspack_import_5 = __webpack_require__(2732);
2995
+ function _ts_decorate(decorators, target, key, desc) {
2996
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2997
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
2998
+ r = Reflect.decorate(decorators, target, key, desc);
2999
+ } else {
3000
+ for(var i = decorators.length - 1; i >= 0; i--){
3001
+ if (d = decorators[i]) {
3002
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3003
+ }
3004
+ }
3005
+ }
3006
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3007
+ }
3008
+ function _ts_metadata(metadataKey, metadataValue) {
3009
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
3010
+ return Reflect.metadata(metadataKey, metadataValue);
3011
+ }
3012
+ }
3013
+ function _ts_param(paramIndex, decorator) {
3014
+ return function(target, key) {
3015
+ decorator(target, key, paramIndex);
3016
+ };
3017
+ }
3018
+
3019
+
3020
+
3021
+
3022
+
3023
+
3024
+
3025
+ class SocialAuthConfigService extends _flusys_nestjs_shared_classes__rspack_import_0.ApiService {
3026
+ cacheManager;
3027
+ utilsService;
3028
+ constructor(cacheManager, utilsService, dataSourceProvider){
3029
+ super(_config_index_js__rspack_import_6/* .AUTH_EVENT_ENTITIES.SOCIAL_AUTH_CONFIG */.g.SOCIAL_AUTH_CONFIG, cacheManager, utilsService, SocialAuthConfigService.name, true, (/* inlined export .AUTH_EVENT_MODULE */"auth"), dataSourceProvider, _entities_social_auth_config_entity_js__rspack_import_4/* .SocialAuthConfig */.G), this.cacheManager = cacheManager, this.utilsService = utilsService;
3030
+ }
3031
+ async beforeInsertOperation(dto, _user, _queryRunner) {
3032
+ for (const entry of Array.isArray(dto) ? dto : [
3033
+ dto
3034
+ ]){
3035
+ await this.ensureProviderUnclaimed(entry.provider);
3036
+ }
3037
+ }
3038
+ async beforeUpdateOperation(dto, _user, _queryRunner) {
3039
+ for (const entry of Array.isArray(dto) ? dto : [
3040
+ dto
3041
+ ]){
3042
+ if (entry.provider) await this.ensureProviderUnclaimed(entry.provider, entry.id);
3043
+ }
3044
+ }
3045
+ async ensureProviderUnclaimed(provider, exceptId) {
3046
+ await this.ensureDataSourceRepository();
3047
+ const existing = await this.repository.findOne({
3048
+ where: {
3049
+ provider,
3050
+ deletedAt: (0,typeorm__rspack_import_3.IsNull)(),
3051
+ ...exceptId ? {
3052
+ id: (0,typeorm__rspack_import_3.Not)(exceptId)
3053
+ } : {}
3054
+ }
3055
+ });
3056
+ if (existing) {
3057
+ throw new _nestjs_common__rspack_import_2.ConflictException({
3058
+ message: `Social provider "${provider}" is already configured`,
3059
+ messageKey: _config_index_js__rspack_import_7/* .SOCIAL_AUTH_CONFIG_MESSAGES.PROVIDER_ALREADY_CONFIGURED */.HZ.PROVIDER_ALREADY_CONFIGURED,
3060
+ messageVariables: {
3061
+ provider
3062
+ }
3063
+ });
3064
+ }
3065
+ }
3066
+ async getExtraManipulateQuery(query, filterDto, user) {
3067
+ const result = await super.getExtraManipulateQuery(query, filterDto, user);
3068
+ query.orderBy(`${this.entityName}.provider`, 'ASC');
3069
+ return result;
3070
+ }
3071
+ }
3072
+ SocialAuthConfigService = _ts_decorate([
3073
+ (0,_nestjs_common__rspack_import_2.Injectable)({
3074
+ scope: _nestjs_common__rspack_import_2.Scope.REQUEST
3075
+ }),
3076
+ _ts_param(0, (0,_nestjs_common__rspack_import_2.Inject)('CACHE_INSTANCE')),
3077
+ _ts_param(1, (0,_nestjs_common__rspack_import_2.Inject)(_flusys_nestjs_shared_modules__rspack_import_1.UtilsService)),
3078
+ _ts_param(2, (0,_nestjs_common__rspack_import_2.Inject)(_auth_datasource_provider_js__rspack_import_5/* .AuthDataSourceProvider */.v)),
3079
+ _ts_metadata("design:type", Function),
3080
+ _ts_metadata("design:paramtypes", [
3081
+ typeof _flusys_nestjs_shared_classes__rspack_import_0.HybridCache === "undefined" ? Object : _flusys_nestjs_shared_classes__rspack_import_0.HybridCache,
3082
+ typeof _flusys_nestjs_shared_modules__rspack_import_1.UtilsService === "undefined" ? Object : _flusys_nestjs_shared_modules__rspack_import_1.UtilsService,
3083
+ typeof _auth_datasource_provider_js__rspack_import_5/* .AuthDataSourceProvider */.v === "undefined" ? Object : _auth_datasource_provider_js__rspack_import_5/* .AuthDataSourceProvider */.v
3084
+ ])
3085
+ ], SocialAuthConfigService);
3086
+
3087
+ __webpack_require__.d(__webpack_exports__, {
3088
+ t: () => (SocialAuthConfigService)
3089
+ });
3090
+
3091
+
3092
+ },
3093
+ 2786(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
3094
+ /* import */ var _flusys_nestjs_shared__rspack_import_0 = __webpack_require__(3422);
3095
+ /* import */ var _flusys_nestjs_shared_classes__rspack_import_1 = __webpack_require__(6937);
3096
+ /* import */ var _flusys_nestjs_shared_constants__rspack_import_2 = __webpack_require__(9140);
3097
+ /* import */ var _nestjs_common__rspack_import_3 = __webpack_require__(6157);
3098
+ /* import */ var crypto__rspack_import_4 = __webpack_require__(7823);
3099
+ /* import */ var typeorm__rspack_import_5 = __webpack_require__(7158);
3100
+ /* import */ var _config_index_js__rspack_import_12 = __webpack_require__(5363);
3101
+ /* import */ var _config_index_js__rspack_import_13 = __webpack_require__(7987);
3102
+ /* import */ var _config_index_js__rspack_import_11 = __webpack_require__(5588);
3103
+ /* import */ var _entities_app_user_entity_js__rspack_import_6 = __webpack_require__(4758);
3104
+ /* import */ var _entities_social_auth_config_entity_js__rspack_import_7 = __webpack_require__(2020);
3105
+ /* import */ var _enums_social_provider_type_enum_js__rspack_import_14 = __webpack_require__(5142);
3106
+ /* import */ var _providers_social_provider_registry_js__rspack_import_8 = __webpack_require__(6928);
3107
+ /* import */ var _auth_datasource_provider_js__rspack_import_9 = __webpack_require__(2732);
3108
+ /* import */ var _authentication_service_js__rspack_import_10 = __webpack_require__(4722);
3109
+ function _ts_decorate(decorators, target, key, desc) {
3110
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3111
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
3112
+ r = Reflect.decorate(decorators, target, key, desc);
3113
+ } else {
3114
+ for(var i = decorators.length - 1; i >= 0; i--){
3115
+ if (d = decorators[i]) {
3116
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3117
+ }
3118
+ }
3119
+ }
3120
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3121
+ }
3122
+ function _ts_metadata(metadataKey, metadataValue) {
3123
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
3124
+ return Reflect.metadata(metadataKey, metadataValue);
3125
+ }
3126
+ }
3127
+ function _ts_param(paramIndex, decorator) {
3128
+ return function(target, key) {
3129
+ decorator(target, key, paramIndex);
3130
+ };
3131
+ }
3132
+
3133
+
3134
+
3135
+
3136
+
3137
+
3138
+
3139
+
3140
+
3141
+
3142
+
3143
+
3144
+
3145
+ class SocialAuthService {
3146
+ authService;
3147
+ dataSourceProvider;
3148
+ cacheManager;
3149
+ constructor(authService, dataSourceProvider, cacheManager){
3150
+ this.authService = authService;
3151
+ this.dataSourceProvider = dataSourceProvider;
3152
+ this.cacheManager = cacheManager;
3153
+ }
3154
+ async listEnabledProviders(redirectUri) {
3155
+ const repository = await this.dataSourceProvider.getRepository(_entities_social_auth_config_entity_js__rspack_import_7/* .SocialAuthConfig */.G);
3156
+ const configs = await repository.find({
3157
+ where: {
3158
+ isEnabled: true,
3159
+ deletedAt: (0,typeorm__rspack_import_5.IsNull)()
3160
+ }
3161
+ });
3162
+ return configs.filter((config)=>!!config.clientId && !!config.clientSecret).map((config)=>({
3163
+ provider: config.provider,
3164
+ redirectUri
3165
+ }));
3166
+ }
3167
+ async createAuthorization(provider, redirectUri) {
3168
+ const config = await this.getUsableConfig(provider);
3169
+ const state = (0,crypto__rspack_import_4.randomBytes)(24).toString('hex');
3170
+ await this.getCache().set(this.stateKey(state), {
3171
+ provider,
3172
+ redirectUri
3173
+ }, (/* inlined export .SOCIAL_STATE_TTL_MS */600000));
3174
+ return {
3175
+ provider,
3176
+ authorizationUrl: (0,_providers_social_provider_registry_js__rspack_import_8/* .getSocialProvider */.V)(provider).buildAuthorizationUrl(this.toCredentials(config, redirectUri), state),
3177
+ state
3178
+ };
3179
+ }
3180
+ async completeLogin(code, state, redirectUri) {
3181
+ const provider = await this.consumeState(state, redirectUri);
3182
+ const config = await this.getUsableConfig(provider);
3183
+ const profile = await (0,_providers_social_provider_registry_js__rspack_import_8/* .getSocialProvider */.V)(provider).fetchProfile(this.toCredentials(config, redirectUri), code);
3184
+ if (!profile.providerUserId) {
3185
+ throw new _nestjs_common__rspack_import_3.UnauthorizedException({
3186
+ message: `${provider} did not return an account identifier`,
3187
+ messageKey: _config_index_js__rspack_import_12/* .SOCIAL_AUTH_MESSAGES.PROFILE_INCOMPLETE */.OF.PROFILE_INCOMPLETE,
3188
+ messageVariables: {
3189
+ provider
3190
+ }
3191
+ });
3192
+ }
3193
+ const user = await this.resolveUser(provider, profile);
3194
+ const response = await this.authService.issueLoginForUser(user);
3195
+ this.publishSocialEvent(_config_index_js__rspack_import_13/* .AUTH_EVENT_ENTITIES.SESSION */.g.SESSION, _config_index_js__rspack_import_13/* .AUTH_EVENT_ACTIONS.SOCIAL_LOGGED_IN */.o.SOCIAL_LOGGED_IN, user, provider);
3196
+ return response;
3197
+ }
3198
+ async resolveUser(provider, profile) {
3199
+ this.ensureVerifiedEmail(provider, profile);
3200
+ const userRepository = await this.dataSourceProvider.getRepository(_entities_app_user_entity_js__rspack_import_6/* .AppUser */.$);
3201
+ const existing = await userRepository.findOne({
3202
+ where: {
3203
+ email: profile.email
3204
+ },
3205
+ withDeleted: true
3206
+ });
3207
+ if (existing?.deletedAt) {
3208
+ throw new _nestjs_common__rspack_import_3.UnauthorizedException({
3209
+ message: 'This account has been permanently deleted. Please contact your system administrator.',
3210
+ messageKey: _config_index_js__rspack_import_12/* .SOCIAL_AUTH_MESSAGES.ACCOUNT_DELETED */.OF.ACCOUNT_DELETED
3211
+ });
3212
+ }
3213
+ if (existing) {
3214
+ // The provider already proved ownership of this email (ensureVerifiedEmail above),
3215
+ // so a social login carries at least as much proof as clicking a verification link.
3216
+ if (!existing.emailVerified) {
3217
+ existing.emailVerified = true;
3218
+ await userRepository.save(existing);
3219
+ }
3220
+ return existing;
3221
+ }
3222
+ const user = await this.registerUser(provider, userRepository, profile);
3223
+ this.publishSocialEvent(_config_index_js__rspack_import_13/* .AUTH_EVENT_ENTITIES.USER */.g.USER, _config_index_js__rspack_import_13/* .AUTH_EVENT_ACTIONS.REGISTERED */.o.REGISTERED, user, provider);
3224
+ return user;
3225
+ }
3226
+ ensureVerifiedEmail(provider, profile) {
3227
+ if (!profile.email) {
3228
+ throw new _nestjs_common__rspack_import_3.UnauthorizedException({
3229
+ message: `${provider} did not share an email address`,
3230
+ messageKey: _config_index_js__rspack_import_12/* .SOCIAL_AUTH_MESSAGES.EMAIL_REQUIRED */.OF.EMAIL_REQUIRED,
3231
+ messageVariables: {
3232
+ provider
3233
+ }
3234
+ });
3235
+ }
3236
+ if (!profile.emailVerified) {
3237
+ throw new _nestjs_common__rspack_import_3.UnauthorizedException({
3238
+ message: `${provider} has not verified this email address`,
3239
+ messageKey: _config_index_js__rspack_import_12/* .SOCIAL_AUTH_MESSAGES.EMAIL_NOT_VERIFIED */.OF.EMAIL_NOT_VERIFIED,
3240
+ messageVariables: {
3241
+ provider
3242
+ }
3243
+ });
3244
+ }
3245
+ }
3246
+ async registerUser(provider, userRepository, profile) {
3247
+ if (!this.dataSourceProvider.isSignUpEnabled()) {
3248
+ throw new _nestjs_common__rspack_import_3.UnauthorizedException({
3249
+ message: `No account is linked to this ${provider} profile`,
3250
+ messageKey: _config_index_js__rspack_import_12/* .SOCIAL_AUTH_MESSAGES.ACCOUNT_NOT_LINKED */.OF.ACCOUNT_NOT_LINKED,
3251
+ messageVariables: {
3252
+ provider
3253
+ }
3254
+ });
3255
+ }
3256
+ if (this.dataSourceProvider.isCompanyFeatureEnabled()) {
3257
+ throw new _nestjs_common__rspack_import_3.UnauthorizedException({
3258
+ message: `No account is linked to this ${provider} profile. Please sign up manually and join or create a company first, then social sign-in will work.`,
3259
+ messageKey: _config_index_js__rspack_import_12/* .SOCIAL_AUTH_MESSAGES.COMPANY_REQUIRED */.OF.COMPANY_REQUIRED,
3260
+ messageVariables: {
3261
+ provider
3262
+ }
3263
+ });
3264
+ }
3265
+ return userRepository.save(userRepository.create({
3266
+ email: profile.email,
3267
+ name: profile.name,
3268
+ password: null,
3269
+ isActive: true,
3270
+ emailVerified: true
3271
+ }));
3272
+ }
3273
+ async getUsableConfig(provider) {
3274
+ const repository = await this.dataSourceProvider.getRepository(_entities_social_auth_config_entity_js__rspack_import_7/* .SocialAuthConfig */.G);
3275
+ const config = await repository.findOne({
3276
+ where: {
3277
+ provider,
3278
+ deletedAt: (0,typeorm__rspack_import_5.IsNull)()
3279
+ }
3280
+ });
3281
+ if (!config?.isEnabled) {
3282
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
3283
+ message: `Social sign-in with ${provider} is not enabled`,
3284
+ messageKey: _config_index_js__rspack_import_12/* .SOCIAL_AUTH_MESSAGES.PROVIDER_DISABLED */.OF.PROVIDER_DISABLED,
3285
+ messageVariables: {
3286
+ provider
3287
+ }
3288
+ });
3289
+ }
3290
+ if (!config.clientId || !config.clientSecret) {
3291
+ throw new _nestjs_common__rspack_import_3.BadRequestException({
3292
+ message: `Social sign-in with ${provider} is missing its client credentials`,
3293
+ messageKey: _config_index_js__rspack_import_12/* .SOCIAL_AUTH_MESSAGES.PROVIDER_NOT_CONFIGURED */.OF.PROVIDER_NOT_CONFIGURED,
3294
+ messageVariables: {
3295
+ provider
3296
+ }
3297
+ });
3298
+ }
3299
+ return config;
3300
+ }
3301
+ toCredentials(config, redirectUri) {
3302
+ return {
3303
+ clientId: config.clientId,
3304
+ clientSecret: config.clientSecret,
3305
+ redirectUri,
3306
+ scopes: config.scopes,
3307
+ extraConfig: config.extraConfig
3308
+ };
3309
+ }
3310
+ async consumeState(state, redirectUri) {
3311
+ const key = this.stateKey(state);
3312
+ const stored = await this.getCache().get(key);
3313
+ await this.getCache().del(key);
3314
+ if (!stored) {
3315
+ throw new _nestjs_common__rspack_import_3.UnauthorizedException({
3316
+ message: 'Social sign-in session is invalid or has expired',
3317
+ messageKey: _config_index_js__rspack_import_12/* .SOCIAL_AUTH_MESSAGES.STATE_INVALID */.OF.STATE_INVALID
3318
+ });
3319
+ }
3320
+ if (stored.redirectUri !== redirectUri) {
3321
+ throw new _nestjs_common__rspack_import_3.UnauthorizedException({
3322
+ message: 'Redirect URI does not match the one the sign-in started with',
3323
+ messageKey: _config_index_js__rspack_import_12/* .SOCIAL_AUTH_MESSAGES.REDIRECT_URI_MISMATCH */.OF.REDIRECT_URI_MISMATCH
3324
+ });
3325
+ }
3326
+ return stored.provider;
3327
+ }
3328
+ stateKey(state) {
3329
+ return `${_config_index_js__rspack_import_11/* .SOCIAL_STATE_PREFIX */.PR}:${state}`;
3330
+ }
3331
+ getCache() {
3332
+ if (!this.cacheManager) {
3333
+ throw new _nestjs_common__rspack_import_3.InternalServerErrorException({
3334
+ message: 'Cache is required to hold the social sign-in state',
3335
+ messageKey: _flusys_nestjs_shared_constants__rspack_import_2.SYSTEM_MESSAGES.SERVICE_NOT_AVAILABLE,
3336
+ messageVariables: {
3337
+ provider: 'CACHE_INSTANCE',
3338
+ available: ''
3339
+ }
3340
+ });
3341
+ }
3342
+ return this.cacheManager;
3343
+ }
3344
+ publishSocialEvent(entity, action, user, provider) {
3345
+ void (0,_flusys_nestjs_shared_classes__rspack_import_1.publishDomainEvent)({
3346
+ module: (/* inlined export .AUTH_EVENT_MODULE */"auth"),
3347
+ entity,
3348
+ action,
3349
+ ids: [
3350
+ user.id
3351
+ ],
3352
+ metadata: {
3353
+ email: user.email,
3354
+ provider
3355
+ },
3356
+ user: {
3357
+ id: user.id,
3358
+ email: user.email
3359
+ }
3360
+ });
3361
+ }
3362
+ }
3363
+ _ts_decorate([
3364
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
3365
+ action: 'auth.social.authorize',
3366
+ module: 'auth',
3367
+ includeParams: false
3368
+ }),
3369
+ _ts_metadata("design:type", Function),
3370
+ _ts_metadata("design:paramtypes", [
3371
+ typeof _enums_social_provider_type_enum_js__rspack_import_14/* .SocialProviderTypeEnum */.u === "undefined" ? Object : _enums_social_provider_type_enum_js__rspack_import_14/* .SocialProviderTypeEnum */.u,
3372
+ String
3373
+ ]),
3374
+ _ts_metadata("design:returntype", Promise)
3375
+ ], SocialAuthService.prototype, "createAuthorization", null);
3376
+ _ts_decorate([
3377
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
3378
+ action: 'auth.social.login',
3379
+ module: 'auth',
3380
+ includeParams: false
3381
+ }),
3382
+ _ts_metadata("design:type", Function),
3383
+ _ts_metadata("design:paramtypes", [
3384
+ String,
3385
+ String,
3386
+ String
3387
+ ]),
3388
+ _ts_metadata("design:returntype", Promise)
3389
+ ], SocialAuthService.prototype, "completeLogin", null);
3390
+ SocialAuthService = _ts_decorate([
3391
+ (0,_nestjs_common__rspack_import_3.Injectable)({
3392
+ scope: _nestjs_common__rspack_import_3.Scope.REQUEST
3393
+ }),
3394
+ _ts_param(0, (0,_nestjs_common__rspack_import_3.Inject)(_authentication_service_js__rspack_import_10/* .AuthenticationService */.k)),
3395
+ _ts_param(1, (0,_nestjs_common__rspack_import_3.Inject)(_auth_datasource_provider_js__rspack_import_9/* .AuthDataSourceProvider */.v)),
3396
+ _ts_param(2, (0,_nestjs_common__rspack_import_3.Optional)()),
3397
+ _ts_param(2, (0,_nestjs_common__rspack_import_3.Inject)('CACHE_INSTANCE')),
3398
+ _ts_metadata("design:type", Function),
3399
+ _ts_metadata("design:paramtypes", [
3400
+ typeof _authentication_service_js__rspack_import_10/* .AuthenticationService */.k === "undefined" ? Object : _authentication_service_js__rspack_import_10/* .AuthenticationService */.k,
3401
+ typeof _auth_datasource_provider_js__rspack_import_9/* .AuthDataSourceProvider */.v === "undefined" ? Object : _auth_datasource_provider_js__rspack_import_9/* .AuthDataSourceProvider */.v,
3402
+ typeof _flusys_nestjs_shared_classes__rspack_import_1.HybridCache === "undefined" ? Object : _flusys_nestjs_shared_classes__rspack_import_1.HybridCache
3403
+ ])
3404
+ ], SocialAuthService);
3405
+
3406
+ __webpack_require__.d(__webpack_exports__, {
3407
+ J: () => (SocialAuthService)
3408
+ });
3409
+
3410
+
3411
+ },
3412
+ 5291(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
3413
+ /* import */ var _flusys_nestjs_shared__rspack_import_0 = __webpack_require__(3422);
3414
+ /* import */ var _flusys_nestjs_shared_classes__rspack_import_1 = __webpack_require__(6937);
3415
+ /* import */ var _flusys_nestjs_shared_interfaces__rspack_import_2 = __webpack_require__(5103);
3416
+ /* import */ var _nestjs_common__rspack_import_3 = __webpack_require__(6157);
3417
+ /* import */ var _config_index_js__rspack_import_8 = __webpack_require__(5363);
3418
+ /* import */ var _config_index_js__rspack_import_9 = __webpack_require__(7987);
3419
+ /* import */ var _entities_company_branch_entity_js__rspack_import_4 = __webpack_require__(1923);
3420
+ /* import */ var _entities_user_company_permission_entity_js__rspack_import_5 = __webpack_require__(2377);
3421
+ /* import */ var _auth_config_service_js__rspack_import_6 = __webpack_require__(6514);
3422
+ /* import */ var _auth_datasource_provider_js__rspack_import_7 = __webpack_require__(2732);
3423
+ function _ts_decorate(decorators, target, key, desc) {
3424
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3425
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
3426
+ r = Reflect.decorate(decorators, target, key, desc);
3427
+ } else {
3428
+ for(var i = decorators.length - 1; i >= 0; i--){
3429
+ if (d = decorators[i]) {
3430
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3431
+ }
3432
+ }
3433
+ }
3434
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3435
+ }
3436
+ function _ts_metadata(metadataKey, metadataValue) {
3437
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
3438
+ return Reflect.metadata(metadataKey, metadataValue);
3439
+ }
3440
+ }
3441
+ function _ts_param(paramIndex, decorator) {
3442
+ return function(target, key) {
3443
+ decorator(target, key, paramIndex);
3444
+ };
3445
+ }
3446
+
3447
+
3448
+
3449
+
3450
+
3451
+
3452
+
3453
+
3454
+
3455
+ class UserPermissionService {
3456
+ dataSourceProvider;
3457
+ authConfig;
3458
+ permissionSyncAdapter;
3459
+ _repository = null;
3460
+ constructor(dataSourceProvider, authConfig, permissionSyncAdapter){
3461
+ this.dataSourceProvider = dataSourceProvider;
3462
+ this.authConfig = authConfig;
3463
+ this.permissionSyncAdapter = permissionSyncAdapter;
3464
+ }
3465
+ /**
3466
+ * Ensures the acting user is only granting/revoking access within their own tenant.
3467
+ * Without this, any user holding USER_PERMISSIONS.UPDATE could assign/revoke access
3468
+ * for a company or branch outside their own company.
3469
+ */ async validateTenantScope(type, targetId, user) {
3470
+ if (!this.authConfig.isCompanyFeatureEnabled() || !user.companyId) {
3471
+ return;
3472
+ }
3473
+ if (type === _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType.COMPANY */.e.COMPANY) {
3474
+ if (targetId !== user.companyId) {
3475
+ throw new _nestjs_common__rspack_import_3.ForbiddenException({
3476
+ message: 'You do not have access to this company',
3477
+ messageKey: _config_index_js__rspack_import_8/* .USER_PERMISSION_MESSAGES.COMPANY_NO_ACCESS */.jz.COMPANY_NO_ACCESS
3478
+ });
3479
+ }
3480
+ return;
3481
+ }
3482
+ const branchRepository = await this.dataSourceProvider.getRepository(_entities_company_branch_entity_js__rspack_import_4/* .CompanyBranch */.A);
3483
+ const branch = await branchRepository.findOne({
3484
+ where: {
3485
+ id: targetId
3486
+ }
3487
+ });
3488
+ if (!branch || branch.companyId !== user.companyId) {
3489
+ throw new _nestjs_common__rspack_import_3.ForbiddenException({
3490
+ message: 'You do not have access to this branch',
3491
+ messageKey: _config_index_js__rspack_import_8/* .USER_PERMISSION_MESSAGES.BRANCH_NO_ACCESS */.jz.BRANCH_NO_ACCESS
3492
+ });
3493
+ }
3494
+ }
3495
+ async getRepository() {
3496
+ if (!this._repository) {
3497
+ this._repository = await this.dataSourceProvider.getRepository(_entities_user_company_permission_entity_js__rspack_import_5/* .UserCompanyPermission */.I);
3498
+ }
3499
+ return this._repository;
3500
+ }
3501
+ // Generic Permission Operations
3502
+ /** Find all permissions of a specific type for a user */ async findUserPermissions(userId, type) {
3503
+ const repository = await this.getRepository();
3504
+ return repository.find({
3505
+ where: {
3506
+ userId,
3507
+ permissionType: type
3508
+ },
3509
+ relations: [
3510
+ type === _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType.COMPANY */.e.COMPANY ? 'company' : 'branch'
3511
+ ],
3512
+ order: {
3513
+ createdAt: 'DESC'
3514
+ }
3515
+ });
3516
+ }
3517
+ /** Assign permission to user */ async assignPermission(userId, targetId, type) {
3518
+ const repository = await this.getRepository();
3519
+ const typeName = type === _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType.COMPANY */.e.COMPANY ? 'company' : 'branch';
3520
+ const existing = await repository.findOne({
3521
+ where: {
3522
+ userId,
3523
+ targetId,
3524
+ permissionType: type
3525
+ }
3526
+ });
3527
+ if (existing) {
3528
+ throw new _nestjs_common__rspack_import_3.ConflictException({
3529
+ message: `User already assigned to this ${typeName}`,
3530
+ messageKey: _config_index_js__rspack_import_8/* .USER_PERMISSION_MESSAGES.ALREADY_ASSIGNED */.jz.ALREADY_ASSIGNED,
3531
+ messageVariables: {
3532
+ type: typeName
3533
+ }
3534
+ });
3535
+ }
3536
+ try {
3537
+ await repository.save(repository.create({
3538
+ userId,
3539
+ permissionType: type,
3540
+ targetId
3541
+ }));
3542
+ } catch (error) {
3543
+ const err = error;
3544
+ if (err?.code === 'ER_DUP_ENTRY' || String(err?.message).includes('Duplicate entry')) {
3545
+ throw new _nestjs_common__rspack_import_3.ConflictException({
3546
+ message: `User already assigned to this ${typeName}. Please refresh and try again.`,
3547
+ messageKey: _config_index_js__rspack_import_8/* .USER_PERMISSION_MESSAGES.ALREADY_ASSIGNED */.jz.ALREADY_ASSIGNED,
3548
+ messageVariables: {
3549
+ type: typeName
3550
+ }
3551
+ });
3552
+ }
3553
+ throw error;
3554
+ }
3555
+ await this.publishPermissionEvent(_config_index_js__rspack_import_9/* .AUTH_EVENT_ACTIONS.PERMISSION_GRANTED */.o.PERMISSION_GRANTED, userId, targetId, type);
3556
+ }
3557
+ async revokePermission(userId, targetId, type) {
3558
+ const repository = await this.getRepository();
3559
+ const typeName = type === _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType.COMPANY */.e.COMPANY ? 'company' : 'branch';
3560
+ const permission = await repository.findOne({
3561
+ where: {
3562
+ userId,
3563
+ targetId,
3564
+ permissionType: type
3565
+ },
3566
+ relations: [
3567
+ type === _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType.BRANCH */.e.BRANCH ? 'branch' : 'company'
3568
+ ]
3569
+ });
3570
+ if (!permission) {
3571
+ throw new _nestjs_common__rspack_import_3.NotFoundException({
3572
+ message: `${typeName.charAt(0).toUpperCase() + typeName.slice(1)} permission not found`,
3573
+ messageKey: _config_index_js__rspack_import_8/* .USER_PERMISSION_MESSAGES.PERMISSION_NOT_FOUND */.jz.PERMISSION_NOT_FOUND,
3574
+ messageVariables: {
3575
+ type: typeName.charAt(0).toUpperCase() + typeName.slice(1)
3576
+ }
3577
+ });
3578
+ }
3579
+ const companyId = type === _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType.COMPANY */.e.COMPANY ? targetId : permission.branch?.companyId;
3580
+ await repository.remove(permission);
3581
+ if (type === _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType.COMPANY */.e.COMPANY) {
3582
+ const revokedBranchIds = await this.revokeBranchPermissionsForCompany(repository, userId, targetId);
3583
+ await this.permissionSyncAdapter?.onUserCompanyAccessRevoked?.(userId, targetId);
3584
+ await Promise.all(revokedBranchIds.map((branchId)=>this.permissionSyncAdapter?.onUserBranchAccessRevoked?.(userId, branchId, targetId)));
3585
+ } else {
3586
+ if (companyId) await this.permissionSyncAdapter?.onUserBranchAccessRevoked?.(userId, targetId, companyId);
3587
+ }
3588
+ await this.publishPermissionEvent(_config_index_js__rspack_import_9/* .AUTH_EVENT_ACTIONS.PERMISSION_REVOKED */.o.PERMISSION_REVOKED, userId, targetId, type, companyId);
3589
+ }
3590
+ async publishPermissionEvent(action, userId, targetId, type, companyId) {
3591
+ await (0,_flusys_nestjs_shared_classes__rspack_import_1.publishDomainEvent)({
3592
+ module: (/* inlined export .AUTH_EVENT_MODULE */"auth"),
3593
+ entity: _config_index_js__rspack_import_9/* .AUTH_EVENT_ENTITIES.USER_PERMISSION */.g.USER_PERMISSION,
3594
+ action,
3595
+ ids: [
3596
+ targetId
3597
+ ],
3598
+ metadata: {
3599
+ targetUserId: userId,
3600
+ permissionType: type,
3601
+ ...companyId ? {
3602
+ companyId
3603
+ } : {}
3604
+ }
3605
+ });
3606
+ }
3607
+ async revokeBranchPermissionsForCompany(repository, userId, companyId) {
3608
+ const branchPermissions = await repository.createQueryBuilder('permission').innerJoin('permission.branch', 'branch').where('permission.userId = :userId', {
3609
+ userId
3610
+ }).andWhere('permission.permissionType = :type', {
3611
+ type: _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType.BRANCH */.e.BRANCH
3612
+ }).andWhere('branch.companyId = :companyId', {
3613
+ companyId
3614
+ }).getMany();
3615
+ if (branchPermissions.length === 0) {
3616
+ return [];
3617
+ }
3618
+ await repository.remove(branchPermissions);
3619
+ return branchPermissions.map((permission)=>permission.targetId);
3620
+ }
3621
+ // Convenience Methods
3622
+ findUserCompanies = (userId)=>this.findUserPermissions(userId, _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType.COMPANY */.e.COMPANY);
3623
+ /** Find user branch permissions with optional company filter */ async findUserBranches(userId, companyId) {
3624
+ const repository = await this.getRepository();
3625
+ const queryBuilder = repository.createQueryBuilder('permission').leftJoinAndSelect('permission.branch', 'branch').where('permission.userId = :userId', {
3626
+ userId
3627
+ }).andWhere('permission.permissionType = :type', {
3628
+ type: _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType.BRANCH */.e.BRANCH
3629
+ }).orderBy('permission.createdAt', 'DESC');
3630
+ if (companyId) {
3631
+ queryBuilder.andWhere('branch.companyId = :companyId', {
3632
+ companyId
3633
+ });
3634
+ }
3635
+ return queryBuilder.getMany();
3636
+ }
3637
+ // Reverse Lookups (target -> users)
3638
+ /** Find all users permitted for a given company */ async findUsersForCompany(companyId) {
3639
+ const repository = await this.getRepository();
3640
+ return repository.find({
3641
+ where: {
3642
+ targetId: companyId,
3643
+ permissionType: _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType.COMPANY */.e.COMPANY
3644
+ },
3645
+ relations: [
3646
+ 'user'
3647
+ ],
3648
+ order: {
3649
+ createdAt: 'DESC'
3650
+ }
3651
+ });
3652
+ }
3653
+ /** Find all users permitted for a given branch */ async findUsersForBranch(branchId) {
3654
+ const repository = await this.getRepository();
3655
+ return repository.find({
3656
+ where: {
3657
+ targetId: branchId,
3658
+ permissionType: _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType.BRANCH */.e.BRANCH
3659
+ },
3660
+ relations: [
3661
+ 'user'
3662
+ ],
3663
+ order: {
3664
+ createdAt: 'DESC'
3665
+ }
3666
+ });
3667
+ }
3668
+ }
3669
+ _ts_decorate([
3670
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
3671
+ action: 'user.assignPermission',
3672
+ module: 'auth'
3673
+ }),
3674
+ _ts_metadata("design:type", Function),
3675
+ _ts_metadata("design:paramtypes", [
3676
+ String,
3677
+ String,
3678
+ typeof _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType */.e === "undefined" ? Object : _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType */.e
3679
+ ]),
3680
+ _ts_metadata("design:returntype", Promise)
3681
+ ], UserPermissionService.prototype, "assignPermission", null);
3682
+ _ts_decorate([
3683
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
3684
+ action: 'user.revokePermission',
3685
+ module: 'auth'
3686
+ }),
3687
+ _ts_metadata("design:type", Function),
3688
+ _ts_metadata("design:paramtypes", [
3689
+ String,
3690
+ String,
3691
+ typeof _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType */.e === "undefined" ? Object : _entities_user_company_permission_entity_js__rspack_import_5/* .PermissionType */.e
3692
+ ]),
3693
+ _ts_metadata("design:returntype", Promise)
3694
+ ], UserPermissionService.prototype, "revokePermission", null);
3695
+ UserPermissionService = _ts_decorate([
3696
+ (0,_nestjs_common__rspack_import_3.Injectable)({
3697
+ scope: _nestjs_common__rspack_import_3.Scope.REQUEST
3698
+ }),
3699
+ _ts_param(0, (0,_nestjs_common__rspack_import_3.Inject)(_auth_datasource_provider_js__rspack_import_7/* .AuthDataSourceProvider */.v)),
3700
+ _ts_param(1, (0,_nestjs_common__rspack_import_3.Inject)(_auth_config_service_js__rspack_import_6/* .AuthConfigService */.W)),
3701
+ _ts_param(2, (0,_nestjs_common__rspack_import_3.Optional)()),
3702
+ _ts_param(2, (0,_nestjs_common__rspack_import_3.Inject)(_flusys_nestjs_shared_interfaces__rspack_import_2.PERMISSION_SYNC_ADAPTER)),
3703
+ _ts_metadata("design:type", Function),
3704
+ _ts_metadata("design:paramtypes", [
3705
+ typeof _auth_datasource_provider_js__rspack_import_7/* .AuthDataSourceProvider */.v === "undefined" ? Object : _auth_datasource_provider_js__rspack_import_7/* .AuthDataSourceProvider */.v,
3706
+ typeof _auth_config_service_js__rspack_import_6/* .AuthConfigService */.W === "undefined" ? Object : _auth_config_service_js__rspack_import_6/* .AuthConfigService */.W,
3707
+ typeof IPermissionSyncAdapter === "undefined" ? Object : IPermissionSyncAdapter
3708
+ ])
3709
+ ], UserPermissionService);
3710
+
3711
+ __webpack_require__.d(__webpack_exports__, {
3712
+ O: () => (UserPermissionService)
3713
+ });
3714
+
3715
+
3716
+ },
3717
+ 7229(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
3718
+ /* import */ var _flusys_nestjs_shared__rspack_import_0 = __webpack_require__(3422);
3719
+ /* import */ var _flusys_nestjs_shared_classes__rspack_import_1 = __webpack_require__(6937);
3720
+ /* import */ var _flusys_nestjs_shared_constants__rspack_import_2 = __webpack_require__(9140);
3721
+ /* import */ var _flusys_nestjs_shared_modules__rspack_import_3 = __webpack_require__(1236);
3722
+ /* import */ var _nestjs_common__rspack_import_4 = __webpack_require__(6157);
3723
+ /* import */ var bcrypt__rspack_import_5 = __webpack_require__(7176);
3724
+ /* import */ var _config_index_js__rspack_import_11 = __webpack_require__(7987);
3725
+ /* import */ var _config_index_js__rspack_import_12 = __webpack_require__(5363);
3726
+ /* import */ var _config_index_js__rspack_import_14 = __webpack_require__(5588);
3727
+ /* import */ var _dtos_user_dto_js__rspack_import_6 = __webpack_require__(7265);
3728
+ /* import */ var _entities_app_user_entity_js__rspack_import_7 = __webpack_require__(4758);
3729
+ /* import */ var _entities_user_company_permission_entity_js__rspack_import_8 = __webpack_require__(2377);
3730
+ /* import */ var _enums_index_js__rspack_import_13 = __webpack_require__(5081);
3731
+ /* import */ var _auth_config_service_js__rspack_import_9 = __webpack_require__(6514);
3732
+ /* import */ var _auth_datasource_provider_js__rspack_import_10 = __webpack_require__(2732);
3733
+ function _ts_decorate(decorators, target, key, desc) {
3734
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3735
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
3736
+ r = Reflect.decorate(decorators, target, key, desc);
3737
+ } else {
3738
+ for(var i = decorators.length - 1; i >= 0; i--){
3739
+ if (d = decorators[i]) {
3740
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3741
+ }
3742
+ }
3743
+ }
3744
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3745
+ }
3746
+ function _ts_metadata(metadataKey, metadataValue) {
3747
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
3748
+ return Reflect.metadata(metadataKey, metadataValue);
3749
+ }
3750
+ }
3751
+ function _ts_param(paramIndex, decorator) {
3752
+ return function(target, key) {
3753
+ decorator(target, key, paramIndex);
3754
+ };
3755
+ }
3756
+
3757
+
3758
+
3759
+
3760
+
3761
+
3762
+
3763
+
3764
+
3765
+
3766
+
3767
+
3768
+
3769
+ class UserService extends _flusys_nestjs_shared_classes__rspack_import_1.ApiService {
3770
+ cacheManager;
3771
+ utilsService;
3772
+ authConfig;
3773
+ userEnricher;
3774
+ permissionRepository;
3775
+ dataSource;
3776
+ logAdapter = (0,_flusys_nestjs_shared_classes__rspack_import_1.createModuleLogger)('auth');
3777
+ constructor(cacheManager, utilsService, dataSourceProvider, authConfig, userEnricher){
3778
+ super(_config_index_js__rspack_import_11/* .AUTH_EVENT_ENTITIES.USER */.g.USER, cacheManager, utilsService, UserService.name, true, (/* inlined export .AUTH_EVENT_MODULE */"auth"), dataSourceProvider, _entities_app_user_entity_js__rspack_import_7/* .AppUser */.$), this.cacheManager = cacheManager, this.utilsService = utilsService, this.authConfig = authConfig, this.userEnricher = userEnricher;
3779
+ }
3780
+ async ensureDataSourceRepository() {
3781
+ await super.ensureDataSourceRepository();
3782
+ const isCompanyFeatureEnabled = this.authConfig.isCompanyFeatureEnabled();
3783
+ if (isCompanyFeatureEnabled && !this.permissionRepository) {
3784
+ [this.permissionRepository] = await this.resolveRepositories([
3785
+ _entities_user_company_permission_entity_js__rspack_import_8/* .UserCompanyPermission */.I
3786
+ ]);
3787
+ }
3788
+ if (!this.dataSource) {
3789
+ this.dataSource = await this.getDataSourceProvider().getDataSource();
3790
+ }
3791
+ }
3792
+ async getUserForProfile(userId, user) {
3793
+ if (userId !== user.id) {
3794
+ throw new _nestjs_common__rspack_import_4.ForbiddenException({
3795
+ message: "Cannot access another user's profile",
3796
+ messageKey: _config_index_js__rspack_import_12/* .AUTH_MESSAGES.PROFILE_ACCESS_DENIED */.mK.PROFILE_ACCESS_DENIED
3797
+ });
3798
+ }
3799
+ await this.ensureDataSourceRepository();
3800
+ const userEntity = await this.repository.findOne({
3801
+ where: {
3802
+ id: userId
3803
+ }
3804
+ });
3805
+ if (!userEntity) {
3806
+ throw new _nestjs_common__rspack_import_4.NotFoundException({
3807
+ message: 'User not found',
3808
+ messageKey: _config_index_js__rspack_import_12/* .USER_MESSAGES.NOT_FOUND */.ny.NOT_FOUND
3809
+ });
3810
+ }
3811
+ return userEntity;
3812
+ }
3813
+ async verifyEmail(id) {
3814
+ await this.ensureDataSourceRepository();
3815
+ await this.repository.update(id, {
3816
+ emailVerified: true
3817
+ });
3818
+ await Promise.all([
3819
+ this.clearCacheForAll(),
3820
+ this.clearCacheForId([
3821
+ {
3822
+ id
3823
+ }
3824
+ ])
3825
+ ]);
3826
+ }
3827
+ async verifyPhone(id) {
3828
+ await this.ensureDataSourceRepository();
3829
+ await this.repository.update(id, {
3830
+ phoneVerified: true
3831
+ });
3832
+ await Promise.all([
3833
+ this.clearCacheForAll(),
3834
+ this.clearCacheForId([
3835
+ {
3836
+ id
3837
+ }
3838
+ ])
3839
+ ]);
3840
+ }
3841
+ async updateStatus(id, isActive, user) {
3842
+ await this.ensureDataSourceRepository();
3843
+ const isCompanyFeatureEnabled = this.authConfig.isCompanyFeatureEnabled();
3844
+ if (isCompanyFeatureEnabled && user?.companyId && this.permissionRepository) {
3845
+ const permission = await this.permissionRepository.findOne({
3846
+ where: {
3847
+ userId: id,
3848
+ permissionType: _enums_index_js__rspack_import_13/* .PermissionType.COMPANY */.e.COMPANY,
3849
+ targetId: user.companyId
3850
+ }
3851
+ });
3852
+ if (!permission) {
3853
+ throw new _nestjs_common__rspack_import_4.NotFoundException({
3854
+ message: 'User company permission not found',
3855
+ messageKey: _config_index_js__rspack_import_12/* .USER_PERMISSION_MESSAGES.PERMISSION_NOT_FOUND */.jz.PERMISSION_NOT_FOUND,
3856
+ messageVariables: {
3857
+ type: 'User company'
3858
+ }
3859
+ });
3860
+ }
3861
+ permission.isActive = isActive;
3862
+ await this.permissionRepository.save(permission);
3863
+ } else {
3864
+ await this.repository.update(id, {
3865
+ isActive
3866
+ });
3867
+ }
3868
+ await Promise.all([
3869
+ this.clearCacheForAll(),
3870
+ this.clearCacheForId([
3871
+ {
3872
+ id
3873
+ }
3874
+ ])
3875
+ ]);
3876
+ }
3877
+ async convertSingleDtoToEntity(dto, user) {
3878
+ const entity = await super.convertSingleDtoToEntity(dto, user);
3879
+ if ('password' in dto && dto.password) {
3880
+ entity.password = await bcrypt__rspack_import_5.hash(dto.password, (/* inlined export .BCRYPT_SALT_ROUNDS */12));
3881
+ }
3882
+ return entity;
3883
+ }
3884
+ convertEntityToResponseDto(entity, isRaw) {
3885
+ if (isRaw) {
3886
+ return this.convertRawToResponseDto(entity);
3887
+ }
3888
+ return this.convertEntityToDto(entity);
3889
+ }
3890
+ convertRawToResponseDto(raw) {
3891
+ const isActive = raw.appuser_companyIsActive !== undefined ? Boolean(raw.appuser_companyIsActive) : raw.appuser_is_active;
3892
+ return {
3893
+ id: raw.appuser_id,
3894
+ name: raw.appuser_name,
3895
+ phone: raw.appuser_phone,
3896
+ email: raw.appuser_email,
3897
+ profilePictureId: raw.appuser_profile_picture_id,
3898
+ isActive,
3899
+ emailVerified: raw.appuser_email_verified,
3900
+ phoneVerified: raw.appuser_phone_verified,
3901
+ lastLoginAt: raw.appuser_last_login_at,
3902
+ additionalFields: raw.appuser_additional_fields,
3903
+ createdAt: raw.appuser_created_at,
3904
+ updatedAt: raw.appuser_updated_at,
3905
+ deletedAt: raw.appuser_deleted_at,
3906
+ createdById: raw.appuser_created_by_id,
3907
+ updatedById: raw.appuser_updated_by_id,
3908
+ deletedById: raw.appuser_deleted_by_id
3909
+ };
3910
+ }
3911
+ convertEntityToDto(entity) {
3912
+ return {
3913
+ id: entity.id,
3914
+ name: entity.name,
3915
+ phone: entity.phone,
3916
+ email: entity.email,
3917
+ profilePictureId: entity.profilePictureId,
3918
+ isActive: entity.isActive,
3919
+ emailVerified: entity.emailVerified,
3920
+ phoneVerified: entity.phoneVerified,
3921
+ lastLoginAt: entity.lastLoginAt,
3922
+ additionalFields: entity.additionalFields,
3923
+ createdAt: entity.createdAt,
3924
+ updatedAt: entity.updatedAt,
3925
+ deletedAt: entity.deletedAt,
3926
+ createdById: entity.createdById,
3927
+ updatedById: entity.updatedById,
3928
+ deletedById: entity.deletedById
3929
+ };
3930
+ }
3931
+ convertEntityListToResponseListDto(entities, isRaw) {
3932
+ return entities.map((entity)=>this.convertEntityToResponseDto(entity, isRaw));
3933
+ }
3934
+ async getFilterQuery(query, filter, _user) {
3935
+ for (const [key, value] of Object.entries(filter)){
3936
+ if (key === 'actionCode' || key === 'isActive') {
3937
+ continue; // real continue
3938
+ }
3939
+ query.andWhere(`${this.entityName}.${key} = :value`, {
3940
+ value
3941
+ });
3942
+ }
3943
+ return {
3944
+ query,
3945
+ isRaw: false
3946
+ };
3947
+ }
3948
+ async getGlobalSearchQuery(query, search, _user) {
3949
+ query.andWhere('(appuser.name LIKE :search OR appuser.email LIKE :search OR appuser.phone LIKE :search)', {
3950
+ search: `%${search}%`
3951
+ });
3952
+ return {
3953
+ query,
3954
+ isRaw: false
3955
+ };
3956
+ }
3957
+ async getExtraManipulateQuery(query, filterAndPaginationDto, user) {
3958
+ const superQuery = await super.getExtraManipulateQuery(query, filterAndPaginationDto, user);
3959
+ const isCompanyFeatureEnabled = this.authConfig.isCompanyFeatureEnabled();
3960
+ const filter = filterAndPaginationDto?.filter;
3961
+ // --- Action code filter (applies regardless of company feature) ---
3962
+ if (filter?.actionCode) {
3963
+ const actionCode = filter.actionCode;
3964
+ const companyId = isCompanyFeatureEnabled ? user?.companyId : undefined;
3965
+ if (isCompanyFeatureEnabled && !companyId) {
3966
+ // Company feature is on but no companyId — no results should match
3967
+ query.andWhere('1 = 0');
3968
+ return {
3969
+ query,
3970
+ isRaw: true
3971
+ };
3972
+ }
3973
+ const isPermissionModeFound = this.authConfig.isPermissionModeFound();
3974
+ if (!isPermissionModeFound) {
3975
+ // Optionally log a warning so the caller knows the filter was ignored
3976
+ this.logAdapter.warn(`actionCode filter was requested but permission mode is not set to 'found' — filter ignored`);
3977
+ } else {
3978
+ query.andWhere(`EXISTS (
3979
+ SELECT 1 FROM user_iam_permission perm
3980
+ WHERE perm.permission_type = 'user_role'
3981
+ AND perm.source_id = appuser.id
3982
+ AND perm.target_id IN (
3983
+ SELECT source_id FROM user_iam_permission
3984
+ WHERE permission_type = 'role_action'
3985
+ AND target_id = (SELECT id FROM action WHERE code = :actionCode)
3986
+ ${isCompanyFeatureEnabled ? 'AND company_id = :actionCompanyId' : ''}
3987
+ )
3988
+ ) OR EXISTS (
3989
+ SELECT 1 FROM user_iam_permission perm
3990
+ WHERE perm.permission_type = 'user_action'
3991
+ AND perm.source_id = appuser.id
3992
+ AND perm.target_id = (SELECT id FROM action WHERE code = :actionCode)
3993
+ ${isCompanyFeatureEnabled ? 'AND company_id = :actionCompanyId' : ''}
3994
+ )`, {
3995
+ actionCode,
3996
+ ...isCompanyFeatureEnabled && {
3997
+ actionCompanyId: companyId
3998
+ }
3999
+ });
4000
+ }
4001
+ }
4002
+ // --- Non-company path ---
4003
+ if (!isCompanyFeatureEnabled) {
4004
+ if (filter?.isActive !== undefined) {
4005
+ query.andWhere(`${this.entityName}.isActive = :value`, {
4006
+ value: filter.isActive
4007
+ });
4008
+ }
4009
+ return superQuery;
4010
+ }
4011
+ // --- Company feature path ---
4012
+ if (!user?.companyId || !this.permissionRepository) {
4013
+ return superQuery;
4014
+ }
4015
+ // Add companyIsActive as a selected column
4016
+ query.addSelect(`(SELECT perm.is_active FROM user_company_permissions perm
4017
+ WHERE perm.user_id = appuser.id
4018
+ AND perm.permission_type = :permissionType
4019
+ AND perm.target_id = :companyId
4020
+ LIMIT 1)`, 'user_companyIsActive');
4021
+ query.setParameter('permissionType', _enums_index_js__rspack_import_13/* .PermissionType.COMPANY */.e.COMPANY);
4022
+ query.setParameter('companyId', user.companyId);
4023
+ // Filter by isActive within the company if requested
4024
+ if (filter?.isActive !== undefined) {
4025
+ query.andWhere(`EXISTS (
4026
+ SELECT 1 FROM user_company_permissions perm
4027
+ WHERE perm.user_id = appuser.id
4028
+ AND perm.permission_type = :permissionType
4029
+ AND perm.target_id = :companyId
4030
+ AND perm.is_active = :isActiveValue
4031
+ )`, {
4032
+ permissionType: _enums_index_js__rspack_import_13/* .PermissionType.COMPANY */.e.COMPANY,
4033
+ companyId: user.companyId,
4034
+ isActiveValue: filter.isActive
4035
+ });
4036
+ }
4037
+ // Always restrict to users belonging to this company
4038
+ query.andWhere(`EXISTS (
4039
+ SELECT 1 FROM user_company_permissions perm
4040
+ WHERE perm.user_id = appuser.id
4041
+ AND perm.permission_type = :permissionType
4042
+ AND perm.target_id = :companyId
4043
+ )`, {
4044
+ permissionType: _enums_index_js__rspack_import_13/* .PermissionType.COMPANY */.e.COMPANY,
4045
+ companyId: user.companyId
4046
+ });
4047
+ return {
4048
+ query,
4049
+ isRaw: true
4050
+ };
4051
+ }
4052
+ async insert(dto, user) {
4053
+ const isCompanyFeatureEnabled = this.authConfig.isCompanyFeatureEnabled();
4054
+ if (!isCompanyFeatureEnabled || !this.dataSource || !user?.companyId || !this.permissionRepository) {
4055
+ return await super.insert(dto, user);
4056
+ }
4057
+ const queryRunner = this.dataSource.createQueryRunner();
4058
+ await queryRunner.connect();
4059
+ await queryRunner.startTransaction();
4060
+ try {
4061
+ const userEntity = await this.convertSingleDtoToEntity(dto, user);
4062
+ const savedUser = await queryRunner.manager.save(this.repository.target, userEntity);
4063
+ const existingPermission = await queryRunner.manager.findOne(this.permissionRepository.target, {
4064
+ where: {
4065
+ userId: savedUser.id,
4066
+ permissionType: _enums_index_js__rspack_import_13/* .PermissionType.COMPANY */.e.COMPANY,
4067
+ targetId: user.companyId
4068
+ }
4069
+ });
4070
+ if (!existingPermission) {
4071
+ const permission = queryRunner.manager.create(this.permissionRepository.target, {
4072
+ userId: savedUser.id,
4073
+ permissionType: _enums_index_js__rspack_import_13/* .PermissionType.COMPANY */.e.COMPANY,
4074
+ targetId: user.companyId,
4075
+ isActive: dto.isActive ?? true
4076
+ });
4077
+ await queryRunner.manager.save(this.permissionRepository.target, permission);
4078
+ }
4079
+ if (user.branchId) {
4080
+ const existingBranchPermission = await queryRunner.manager.findOne(this.permissionRepository.target, {
4081
+ where: {
4082
+ userId: savedUser.id,
4083
+ permissionType: _enums_index_js__rspack_import_13/* .PermissionType.BRANCH */.e.BRANCH,
4084
+ targetId: user.branchId
4085
+ }
4086
+ });
4087
+ if (!existingBranchPermission) {
4088
+ const branchPermission = queryRunner.manager.create(this.permissionRepository.target, {
4089
+ userId: savedUser.id,
4090
+ permissionType: _enums_index_js__rspack_import_13/* .PermissionType.BRANCH */.e.BRANCH,
4091
+ targetId: user.branchId,
4092
+ isActive: dto.isActive ?? true
4093
+ });
4094
+ await queryRunner.manager.save(this.permissionRepository.target, branchPermission);
4095
+ }
4096
+ }
4097
+ await queryRunner.commitTransaction();
4098
+ await Promise.all([
4099
+ this.clearCacheForAll(),
4100
+ this.clearCacheForId([
4101
+ savedUser
4102
+ ])
4103
+ ]);
4104
+ return this.convertEntityToResponseDto(savedUser, false);
4105
+ } catch (error) {
4106
+ await queryRunner.rollbackTransaction();
4107
+ throw error;
4108
+ } finally{
4109
+ await queryRunner.release();
4110
+ }
4111
+ }
4112
+ async getProfileWithExtras(userId, user) {
4113
+ const userEntity = await this.getUserForProfile(userId, user);
4114
+ const userData = this.convertEntityToResponseDto(userEntity, false);
4115
+ let extras;
4116
+ if (this.userEnricher?.getProfileExtras) {
4117
+ extras = await this.userEnricher.getProfileExtras(userId, user);
4118
+ }
4119
+ return {
4120
+ user: userData,
4121
+ extras
4122
+ };
4123
+ }
4124
+ async getAll(search, filterAndPaginationDto, user) {
4125
+ const result = await super.getAll(search, filterAndPaginationDto, user);
4126
+ const enrichedData = await this.getEnrichedList(result.data, user);
4127
+ return {
4128
+ data: enrichedData,
4129
+ total: result.total
4130
+ };
4131
+ }
4132
+ async getEnrichedList(users, user) {
4133
+ if (this.userEnricher?.enrichListItems) {
4134
+ return this.userEnricher.enrichListItems(users, user);
4135
+ }
4136
+ return users;
4137
+ }
4138
+ async getProfileSections() {
4139
+ if (this.userEnricher?.getProfileSections) {
4140
+ return this.userEnricher.getProfileSections();
4141
+ }
4142
+ return [];
4143
+ }
4144
+ async getProfileSectionData(userId, sectionId, user) {
4145
+ await this.getUserForProfile(userId, user);
4146
+ if (this.userEnricher?.getProfileSectionData) {
4147
+ return this.userEnricher.getProfileSectionData(userId, sectionId, user);
4148
+ }
4149
+ return null;
4150
+ }
4151
+ async updateProfileSection(userId, sectionId, data, user) {
4152
+ const userEntity = await this.getUserForProfile(userId, user);
4153
+ if (!this.dataSource) {
4154
+ throw new _nestjs_common__rspack_import_4.BadRequestException({
4155
+ message: 'DataSource not available',
4156
+ messageKey: _flusys_nestjs_shared_constants__rspack_import_2.SYSTEM_MESSAGES.DATASOURCE_NOT_AVAILABLE
4157
+ });
4158
+ }
4159
+ if (!this.userEnricher?.updateProfileSection) {
4160
+ throw new _nestjs_common__rspack_import_4.BadRequestException({
4161
+ message: 'Profile sections not supported',
4162
+ messageKey: _config_index_js__rspack_import_12/* .AUTH_MESSAGES.PROFILE_SECTIONS_NOT_SUPPORTED */.mK.PROFILE_SECTIONS_NOT_SUPPORTED
4163
+ });
4164
+ }
4165
+ const queryRunner = this.dataSource.createQueryRunner();
4166
+ await queryRunner.connect();
4167
+ await queryRunner.startTransaction();
4168
+ try {
4169
+ await this.userEnricher.updateProfileSection(userId, sectionId, data, queryRunner);
4170
+ await queryRunner.commitTransaction();
4171
+ await Promise.all([
4172
+ this.clearCacheForAll(),
4173
+ this.clearCacheForId([
4174
+ userEntity
4175
+ ])
4176
+ ]);
4177
+ } catch (error) {
4178
+ await queryRunner.rollbackTransaction();
4179
+ throw error;
4180
+ } finally{
4181
+ await queryRunner.release();
4182
+ }
4183
+ }
4184
+ async getProfileCompletion(userId, user) {
4185
+ await this.getUserForProfile(userId, user);
4186
+ if (this.userEnricher?.calculateProfileCompletion) {
4187
+ return this.userEnricher.calculateProfileCompletion(userId, user);
4188
+ }
4189
+ return 100;
4190
+ }
4191
+ async profile(dto, user) {
4192
+ await this.ensureDataSourceRepository();
4193
+ if (!this.dataSource) {
4194
+ throw new _nestjs_common__rspack_import_4.BadRequestException({
4195
+ message: 'DataSource not available',
4196
+ messageKey: _flusys_nestjs_shared_constants__rspack_import_2.SYSTEM_MESSAGES.DATASOURCE_NOT_AVAILABLE
4197
+ });
4198
+ }
4199
+ const userId = dto.id ?? user.id;
4200
+ if (dto.extras && this.userEnricher?.validateProfileExtras) {
4201
+ await this.userEnricher.validateProfileExtras(userId, dto.extras, user);
4202
+ }
4203
+ const queryRunner = this.dataSource.createQueryRunner();
4204
+ await queryRunner.connect();
4205
+ await queryRunner.startTransaction();
4206
+ try {
4207
+ const findUser = await queryRunner.manager.findOne(this.repository.target, {
4208
+ where: {
4209
+ id: userId
4210
+ }
4211
+ });
4212
+ if (!findUser) {
4213
+ throw new _nestjs_common__rspack_import_4.NotFoundException({
4214
+ message: 'User not found',
4215
+ messageKey: _config_index_js__rspack_import_12/* .USER_MESSAGES.NOT_FOUND */.ny.NOT_FOUND
4216
+ });
4217
+ }
4218
+ if (dto.password) {
4219
+ const isOwnProfile = !dto.id || dto.id === user.id;
4220
+ if (isOwnProfile) {
4221
+ if (!dto.oldPassword) {
4222
+ throw new _nestjs_common__rspack_import_4.BadRequestException({
4223
+ message: 'Current password is required to change your password',
4224
+ messageKey: _config_index_js__rspack_import_12/* .AUTH_MESSAGES.PASSWORD_CHANGE_CURRENT_REQUIRED */.mK.PASSWORD_CHANGE_CURRENT_REQUIRED
4225
+ });
4226
+ }
4227
+ const isPasswordValid = await bcrypt__rspack_import_5.compare(dto.oldPassword, findUser.password);
4228
+ if (!isPasswordValid) {
4229
+ throw new _nestjs_common__rspack_import_4.BadRequestException({
4230
+ message: 'Current password is incorrect',
4231
+ messageKey: _config_index_js__rspack_import_12/* .AUTH_MESSAGES.PASSWORD_CHANGE_INVALID_CURRENT */.mK.PASSWORD_CHANGE_INVALID_CURRENT
4232
+ });
4233
+ }
4234
+ }
4235
+ findUser.password = await bcrypt__rspack_import_5.hash(dto.password, (/* inlined export .BCRYPT_SALT_ROUNDS */12));
4236
+ }
4237
+ const { password, oldPassword, extras, emailVerified, phoneVerified, isActive, ...restDto } = dto;
4238
+ Object.assign(findUser, restDto);
4239
+ await queryRunner.manager.save(this.repository.target, findUser);
4240
+ if (extras && this.userEnricher?.updateProfileExtras) {
4241
+ await this.userEnricher.updateProfileExtras(userId, extras, queryRunner);
4242
+ }
4243
+ await queryRunner.commitTransaction();
4244
+ await Promise.all([
4245
+ this.clearCacheForAll(),
4246
+ this.clearCacheForId([
4247
+ findUser
4248
+ ])
4249
+ ]);
4250
+ return findUser.id;
4251
+ } catch (error) {
4252
+ await queryRunner.rollbackTransaction();
4253
+ throw error;
4254
+ } finally{
4255
+ await queryRunner.release();
4256
+ }
4257
+ }
4258
+ }
4259
+ _ts_decorate([
4260
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
4261
+ action: 'user.verifyEmail',
4262
+ module: 'auth'
4263
+ }),
4264
+ _ts_metadata("design:type", Function),
4265
+ _ts_metadata("design:paramtypes", [
4266
+ String
4267
+ ]),
4268
+ _ts_metadata("design:returntype", Promise)
4269
+ ], UserService.prototype, "verifyEmail", null);
4270
+ _ts_decorate([
4271
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
4272
+ action: 'user.verifyPhone',
4273
+ module: 'auth'
4274
+ }),
4275
+ _ts_metadata("design:type", Function),
4276
+ _ts_metadata("design:paramtypes", [
4277
+ String
4278
+ ]),
4279
+ _ts_metadata("design:returntype", Promise)
4280
+ ], UserService.prototype, "verifyPhone", null);
4281
+ _ts_decorate([
4282
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
4283
+ action: 'user.updateStatus',
4284
+ module: 'auth'
4285
+ }),
4286
+ _ts_metadata("design:type", Function),
4287
+ _ts_metadata("design:paramtypes", [
4288
+ String,
4289
+ Boolean,
4290
+ Object
4291
+ ]),
4292
+ _ts_metadata("design:returntype", Promise)
4293
+ ], UserService.prototype, "updateStatus", null);
4294
+ _ts_decorate([
4295
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
4296
+ action: 'user.create',
4297
+ module: 'auth',
4298
+ includeParams: false
4299
+ }),
4300
+ _ts_metadata("design:type", Function),
4301
+ _ts_metadata("design:paramtypes", [
4302
+ typeof _dtos_user_dto_js__rspack_import_6/* .CreateUserDto */.TG === "undefined" ? Object : _dtos_user_dto_js__rspack_import_6/* .CreateUserDto */.TG,
4303
+ Object
4304
+ ]),
4305
+ _ts_metadata("design:returntype", Promise)
4306
+ ], UserService.prototype, "insert", null);
4307
+ _ts_decorate([
4308
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
4309
+ action: 'user.updateProfileSection',
4310
+ module: 'auth',
4311
+ includeParams: false
4312
+ }),
4313
+ _ts_metadata("design:type", Function),
4314
+ _ts_metadata("design:paramtypes", [
4315
+ String,
4316
+ String,
4317
+ typeof Record === "undefined" ? Object : Record,
4318
+ typeof ILoggedUserInfo === "undefined" ? Object : ILoggedUserInfo
4319
+ ]),
4320
+ _ts_metadata("design:returntype", Promise)
4321
+ ], UserService.prototype, "updateProfileSection", null);
4322
+ _ts_decorate([
4323
+ (0,_flusys_nestjs_shared__rspack_import_0.LogAction)({
4324
+ action: 'user.updateProfile',
4325
+ module: 'auth',
4326
+ includeParams: false
4327
+ }),
4328
+ _ts_metadata("design:type", Function),
4329
+ _ts_metadata("design:paramtypes", [
4330
+ Object,
4331
+ typeof ILoggedUserInfo === "undefined" ? Object : ILoggedUserInfo
4332
+ ]),
4333
+ _ts_metadata("design:returntype", Promise)
4334
+ ], UserService.prototype, "profile", null);
4335
+ UserService = _ts_decorate([
4336
+ (0,_nestjs_common__rspack_import_4.Injectable)({
4337
+ scope: _nestjs_common__rspack_import_4.Scope.REQUEST
4338
+ }),
4339
+ _ts_param(0, (0,_nestjs_common__rspack_import_4.Inject)('CACHE_INSTANCE')),
4340
+ _ts_param(1, (0,_nestjs_common__rspack_import_4.Inject)(_flusys_nestjs_shared_modules__rspack_import_3.UtilsService)),
4341
+ _ts_param(2, (0,_nestjs_common__rspack_import_4.Inject)(_auth_datasource_provider_js__rspack_import_10/* .AuthDataSourceProvider */.v)),
4342
+ _ts_param(3, (0,_nestjs_common__rspack_import_4.Inject)(_auth_config_service_js__rspack_import_9/* .AuthConfigService */.W)),
4343
+ _ts_param(4, (0,_nestjs_common__rspack_import_4.Optional)()),
4344
+ _ts_param(4, (0,_nestjs_common__rspack_import_4.Inject)(_config_index_js__rspack_import_14/* .USER_ENRICHER */.jt)),
4345
+ _ts_metadata("design:type", Function),
4346
+ _ts_metadata("design:paramtypes", [
4347
+ typeof _flusys_nestjs_shared_classes__rspack_import_1.HybridCache === "undefined" ? Object : _flusys_nestjs_shared_classes__rspack_import_1.HybridCache,
4348
+ typeof _flusys_nestjs_shared_modules__rspack_import_3.UtilsService === "undefined" ? Object : _flusys_nestjs_shared_modules__rspack_import_3.UtilsService,
4349
+ typeof _auth_datasource_provider_js__rspack_import_10/* .AuthDataSourceProvider */.v === "undefined" ? Object : _auth_datasource_provider_js__rspack_import_10/* .AuthDataSourceProvider */.v,
4350
+ typeof _auth_config_service_js__rspack_import_9/* .AuthConfigService */.W === "undefined" ? Object : _auth_config_service_js__rspack_import_9/* .AuthConfigService */.W,
4351
+ typeof IUserEnricher === "undefined" ? Object : IUserEnricher
4352
+ ])
4353
+ ], UserService);
4354
+
4355
+ __webpack_require__.d(__webpack_exports__, {
4356
+ D: () => (UserService)
4357
+ });
4358
+
4359
+
4360
+ },
4361
+ 6937(module) {
4362
+
4363
+ module.exports = __rspack_external__flusys_nestjs_shared_classes_6076a329;
4364
+
4365
+
4366
+ },
4367
+ 9140(module) {
4368
+
4369
+ module.exports = __rspack_external__flusys_nestjs_shared_constants_81f33d5b;
4370
+
4371
+
4372
+ },
4373
+ 5103(module) {
4374
+
4375
+ module.exports = __rspack_external__flusys_nestjs_shared_interfaces_413f2706;
4376
+
4377
+
4378
+ },
4379
+ 1236(module) {
4380
+
4381
+ module.exports = __rspack_external__flusys_nestjs_shared_modules_24702bee;
4382
+
4383
+
4384
+ },
4385
+ 9216(module) {
4386
+
4387
+ module.exports = __rspack_external__flusys_nestjs_shared_utils_9125c1f1;
4388
+
4389
+
4390
+ },
4391
+ 6157(module) {
4392
+
4393
+ module.exports = __rspack_external__nestjs_common_a04939da;
4394
+
4395
+
4396
+ },
4397
+ 3075(module) {
4398
+
4399
+ module.exports = __rspack_external__nestjs_core_d7b00a1a;
4400
+
4401
+
4402
+ },
4403
+ 2125(module) {
4404
+
4405
+ module.exports = __rspack_external__nestjs_jwt_50c0e0ae;
4406
+
4407
+
4408
+ },
4409
+ 7176(module) {
4410
+
4411
+ module.exports = __rspack_external_bcrypt;
4412
+
4413
+
4414
+ },
4415
+ 7823(module) {
4416
+
4417
+ module.exports = __rspack_external_crypto;
4418
+
4419
+
4420
+ },
4421
+
4422
+ };