@flusys/nestjs-auth 7.0.2 → 8.0.0-beta.1

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