@flusys/nestjs-auth 7.1.0 → 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 (270) hide show
  1. package/README.md +1 -1
  2. package/config/index.d.ts +3 -3
  3. package/config/message-keys.d.ts +2 -0
  4. package/controllers/authentication.controller.d.ts +5 -5
  5. package/controllers/branch.controller.d.ts +2 -2
  6. package/controllers/company-selection.controller.d.ts +4 -4
  7. package/controllers/company.controller.d.ts +2 -2
  8. package/controllers/email-verification.controller.d.ts +6 -6
  9. package/controllers/index.d.ts +9 -9
  10. package/controllers/social-auth-config.controller.d.ts +2 -2
  11. package/controllers/social-auth.controller.d.ts +3 -3
  12. package/controllers/user-permission.controller.d.ts +5 -4
  13. package/controllers/user.controller.d.ts +7 -7
  14. package/docs/auth-swagger.config.d.ts +2 -2
  15. package/docs/index.d.ts +1 -1
  16. package/dtos/index.d.ts +6 -6
  17. package/dtos/social-auth.dto.d.ts +1 -1
  18. package/entities/company-branch.entity.d.ts +1 -1
  19. package/entities/company.entity.d.ts +1 -1
  20. package/entities/index.d.ts +14 -14
  21. package/entities/pending-registration.entity.d.ts +1 -1
  22. package/entities/user-company-permission.entity.d.ts +4 -4
  23. package/enums/index.d.ts +2 -2
  24. package/fesm/118.js +1230 -0
  25. package/fesm/120.js +2197 -0
  26. package/fesm/24.js +4389 -0
  27. package/fesm/370.js +1163 -0
  28. package/fesm/446.js +877 -0
  29. package/fesm/chunks/117.js +69 -0
  30. package/fesm/config/index.js +244 -3
  31. package/fesm/controllers/index.js +27 -9
  32. package/fesm/docs/index.js +479 -1
  33. package/fesm/dtos/index.js +123 -6
  34. package/fesm/entities/index.js +68 -22
  35. package/fesm/enums/index.js +53 -2
  36. package/fesm/helpers/index.js +115 -2
  37. package/fesm/index.js +1437 -13
  38. package/fesm/interceptors/index.js +508 -2
  39. package/fesm/interfaces/index.js +75 -8
  40. package/fesm/modules/index.js +546 -1
  41. package/fesm/runtime.js +134 -0
  42. package/fesm/services/index.js +67 -11
  43. package/helpers/auth-response.mapper.d.ts +3 -3
  44. package/helpers/index.d.ts +2 -2
  45. package/helpers/token.helper.d.ts +2 -2
  46. package/index.d.ts +13 -13
  47. package/interceptors/clear-token.interceptor.d.ts +2 -2
  48. package/interceptors/index.d.ts +2 -2
  49. package/interceptors/set-token.interceptor.d.ts +2 -2
  50. package/interfaces/auth-module-options.interface.d.ts +3 -3
  51. package/interfaces/authentication.interface.d.ts +3 -3
  52. package/interfaces/company-branch.interface.d.ts +2 -2
  53. package/interfaces/company.interface.d.ts +1 -1
  54. package/interfaces/index.d.ts +8 -8
  55. package/interfaces/social-auth.interface.d.ts +2 -2
  56. package/interfaces/user-enricher.interface.d.ts +3 -3
  57. package/modules/auth.module.d.ts +4 -4
  58. package/modules/index.d.ts +1 -1
  59. package/package.json +32 -39
  60. package/providers/facebook.social-provider.d.ts +2 -2
  61. package/providers/google.social-provider.d.ts +2 -2
  62. package/providers/index.d.ts +1 -1
  63. package/providers/linkedin.social-provider.d.ts +2 -2
  64. package/providers/microsoft.social-provider.d.ts +2 -2
  65. package/providers/social-provider.registry.d.ts +2 -2
  66. package/services/auth-config.service.d.ts +3 -3
  67. package/services/auth-datasource.provider.d.ts +3 -3
  68. package/services/auth-email.service.d.ts +3 -3
  69. package/services/authentication.service.d.ts +12 -12
  70. package/services/branch.service.d.ts +7 -7
  71. package/services/company.service.d.ts +6 -6
  72. package/services/index.d.ts +11 -11
  73. package/services/social-auth-config.service.d.ts +6 -6
  74. package/services/social-auth.service.d.ts +5 -5
  75. package/services/user-permission.service.d.ts +8 -4
  76. package/services/user.service.d.ts +7 -7
  77. package/strategies/jwt.strategy.d.ts +4 -4
  78. package/validators/password.validator.d.ts +1 -1
  79. package/cjs/config/auth.constants.js +0 -49
  80. package/cjs/config/event-actions.js +0 -47
  81. package/cjs/config/index.js +0 -20
  82. package/cjs/config/message-keys.js +0 -135
  83. package/cjs/controllers/authentication.controller.js +0 -427
  84. package/cjs/controllers/authentication.controller.spec.js +0 -219
  85. package/cjs/controllers/branch.controller.js +0 -102
  86. package/cjs/controllers/branch.controller.spec.js +0 -134
  87. package/cjs/controllers/company-selection.controller.js +0 -198
  88. package/cjs/controllers/company-selection.controller.spec.js +0 -84
  89. package/cjs/controllers/company.controller.js +0 -102
  90. package/cjs/controllers/company.controller.spec.js +0 -131
  91. package/cjs/controllers/email-verification.controller.js +0 -224
  92. package/cjs/controllers/email-verification.controller.spec.js +0 -142
  93. package/cjs/controllers/index.js +0 -26
  94. package/cjs/controllers/social-auth-config.controller.js +0 -107
  95. package/cjs/controllers/social-auth.controller.js +0 -175
  96. package/cjs/controllers/social-auth.controller.spec.js +0 -79
  97. package/cjs/controllers/user-permission.controller.js +0 -223
  98. package/cjs/controllers/user-permission.controller.spec.js +0 -138
  99. package/cjs/controllers/user.controller.js +0 -438
  100. package/cjs/controllers/user.controller.spec.js +0 -204
  101. package/cjs/docs/auth-swagger.config.js +0 -461
  102. package/cjs/docs/auth-swagger.config.spec.js +0 -130
  103. package/cjs/docs/index.js +0 -18
  104. package/cjs/dtos/authentication.dto.js +0 -755
  105. package/cjs/dtos/company-branch.dto.js +0 -294
  106. package/cjs/dtos/company.dto.js +0 -298
  107. package/cjs/dtos/index.js +0 -23
  108. package/cjs/dtos/social-auth.dto.js +0 -318
  109. package/cjs/dtos/user-permission.dto.js +0 -358
  110. package/cjs/dtos/user.dto.js +0 -413
  111. package/cjs/entities/app-user.entity.js +0 -25
  112. package/cjs/entities/company-branch.entity.js +0 -163
  113. package/cjs/entities/company.entity.js +0 -146
  114. package/cjs/entities/index.js +0 -67
  115. package/cjs/entities/index.spec.js +0 -84
  116. package/cjs/entities/pending-registration.entity.js +0 -135
  117. package/cjs/entities/social-auth-config.entity.js +0 -102
  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 -19
  121. package/cjs/enums/social-provider-type.enum.js +0 -17
  122. package/cjs/enums/user-org-permission-type.enum.js +0 -15
  123. package/cjs/helpers/auth-response.mapper.js +0 -46
  124. package/cjs/helpers/auth-response.mapper.spec.js +0 -139
  125. package/cjs/helpers/index.js +0 -19
  126. package/cjs/helpers/token.helper.js +0 -58
  127. package/cjs/helpers/token.helper.spec.js +0 -86
  128. package/cjs/index.js +0 -30
  129. package/cjs/interceptors/clear-token.interceptor.js +0 -73
  130. package/cjs/interceptors/clear-token.interceptor.spec.js +0 -107
  131. package/cjs/interceptors/index.js +0 -19
  132. package/cjs/interceptors/set-token.interceptor.js +0 -107
  133. package/cjs/interceptors/set-token.interceptor.spec.js +0 -165
  134. package/cjs/interfaces/auth-email-provider.interface.js +0 -45
  135. package/cjs/interfaces/auth-module-options.interface.js +0 -4
  136. package/cjs/interfaces/authentication.interface.js +0 -4
  137. package/cjs/interfaces/company-branch.interface.js +0 -4
  138. package/cjs/interfaces/company.interface.js +0 -4
  139. package/cjs/interfaces/index.js +0 -25
  140. package/cjs/interfaces/social-auth.interface.js +0 -4
  141. package/cjs/interfaces/user-enricher.interface.js +0 -4
  142. package/cjs/interfaces/user.interface.js +0 -4
  143. package/cjs/modules/auth.module.js +0 -208
  144. package/cjs/modules/auth.module.spec.js +0 -258
  145. package/cjs/modules/index.js +0 -18
  146. package/cjs/providers/facebook.social-provider.js +0 -73
  147. package/cjs/providers/google.social-provider.js +0 -68
  148. package/cjs/providers/index.js +0 -18
  149. package/cjs/providers/linkedin.social-provider.js +0 -66
  150. package/cjs/providers/microsoft.social-provider.js +0 -78
  151. package/cjs/providers/oauth-http.util.js +0 -107
  152. package/cjs/providers/social-provider.registry.js +0 -24
  153. package/cjs/providers/social-provider.registry.spec.js +0 -135
  154. package/cjs/services/auth-config.service.js +0 -113
  155. package/cjs/services/auth-config.service.spec.js +0 -100
  156. package/cjs/services/auth-datasource.provider.js +0 -138
  157. package/cjs/services/auth-datasource.provider.spec.js +0 -191
  158. package/cjs/services/auth-email.service.js +0 -539
  159. package/cjs/services/auth-email.service.spec.js +0 -456
  160. package/cjs/services/authentication.service.js +0 -1203
  161. package/cjs/services/authentication.service.spec.js +0 -1020
  162. package/cjs/services/branch.service.js +0 -153
  163. package/cjs/services/branch.service.spec.js +0 -169
  164. package/cjs/services/company-selection-session.service.js +0 -121
  165. package/cjs/services/company-selection-session.service.spec.js +0 -90
  166. package/cjs/services/company.service.js +0 -140
  167. package/cjs/services/company.service.spec.js +0 -127
  168. package/cjs/services/index.js +0 -28
  169. package/cjs/services/social-auth-config.service.js +0 -103
  170. package/cjs/services/social-auth-config.service.spec.js +0 -71
  171. package/cjs/services/social-auth.service.js +0 -310
  172. package/cjs/services/social-auth.service.spec.js +0 -310
  173. package/cjs/services/user-permission.service.js +0 -236
  174. package/cjs/services/user-permission.service.spec.js +0 -254
  175. package/cjs/services/user.service.js +0 -671
  176. package/cjs/services/user.service.spec.js +0 -718
  177. package/cjs/strategies/jwt.strategy.js +0 -140
  178. package/cjs/strategies/jwt.strategy.spec.js +0 -166
  179. package/cjs/validators/password.validator.js +0 -45
  180. package/cjs/validators/password.validator.spec.js +0 -161
  181. package/fesm/config/auth.constants.js +0 -14
  182. package/fesm/config/event-actions.js +0 -26
  183. package/fesm/config/message-keys.js +0 -99
  184. package/fesm/controllers/authentication.controller.js +0 -417
  185. package/fesm/controllers/authentication.controller.spec.js +0 -215
  186. package/fesm/controllers/branch.controller.js +0 -92
  187. package/fesm/controllers/branch.controller.spec.js +0 -130
  188. package/fesm/controllers/company-selection.controller.js +0 -188
  189. package/fesm/controllers/company-selection.controller.spec.js +0 -80
  190. package/fesm/controllers/company.controller.js +0 -92
  191. package/fesm/controllers/company.controller.spec.js +0 -127
  192. package/fesm/controllers/email-verification.controller.js +0 -214
  193. package/fesm/controllers/email-verification.controller.spec.js +0 -138
  194. package/fesm/controllers/social-auth-config.controller.js +0 -97
  195. package/fesm/controllers/social-auth.controller.js +0 -165
  196. package/fesm/controllers/social-auth.controller.spec.js +0 -75
  197. package/fesm/controllers/user-permission.controller.js +0 -213
  198. package/fesm/controllers/user-permission.controller.spec.js +0 -134
  199. package/fesm/controllers/user.controller.js +0 -428
  200. package/fesm/controllers/user.controller.spec.js +0 -200
  201. package/fesm/docs/auth-swagger.config.js +0 -454
  202. package/fesm/docs/auth-swagger.config.spec.js +0 -126
  203. package/fesm/dtos/authentication.dto.js +0 -683
  204. package/fesm/dtos/company-branch.dto.js +0 -279
  205. package/fesm/dtos/company.dto.js +0 -283
  206. package/fesm/dtos/social-auth.dto.js +0 -282
  207. package/fesm/dtos/user-permission.dto.js +0 -339
  208. package/fesm/dtos/user.dto.js +0 -391
  209. package/fesm/entities/app-user.entity.js +0 -15
  210. package/fesm/entities/company-branch.entity.js +0 -153
  211. package/fesm/entities/company.entity.js +0 -136
  212. package/fesm/entities/index.spec.js +0 -80
  213. package/fesm/entities/pending-registration.entity.js +0 -125
  214. package/fesm/entities/social-auth-config.entity.js +0 -92
  215. package/fesm/entities/user-company-permission.entity.js +0 -136
  216. package/fesm/entities/user-token.entity.js +0 -104
  217. package/fesm/enums/social-provider-type.enum.js +0 -7
  218. package/fesm/enums/user-org-permission-type.enum.js +0 -5
  219. package/fesm/helpers/auth-response.mapper.js +0 -25
  220. package/fesm/helpers/auth-response.mapper.spec.js +0 -135
  221. package/fesm/helpers/token.helper.js +0 -40
  222. package/fesm/helpers/token.helper.spec.js +0 -82
  223. package/fesm/interceptors/clear-token.interceptor.js +0 -63
  224. package/fesm/interceptors/clear-token.interceptor.spec.js +0 -103
  225. package/fesm/interceptors/set-token.interceptor.js +0 -98
  226. package/fesm/interceptors/set-token.interceptor.spec.js +0 -161
  227. package/fesm/interfaces/auth-email-provider.interface.js +0 -38
  228. package/fesm/interfaces/auth-module-options.interface.js +0 -3
  229. package/fesm/interfaces/authentication.interface.js +0 -1
  230. package/fesm/interfaces/company-branch.interface.js +0 -1
  231. package/fesm/interfaces/company.interface.js +0 -1
  232. package/fesm/interfaces/social-auth.interface.js +0 -1
  233. package/fesm/interfaces/user-enricher.interface.js +0 -4
  234. package/fesm/interfaces/user.interface.js +0 -1
  235. package/fesm/modules/auth.module.js +0 -198
  236. package/fesm/modules/auth.module.spec.js +0 -254
  237. package/fesm/providers/facebook.social-provider.js +0 -63
  238. package/fesm/providers/google.social-provider.js +0 -58
  239. package/fesm/providers/index.js +0 -1
  240. package/fesm/providers/linkedin.social-provider.js +0 -56
  241. package/fesm/providers/microsoft.social-provider.js +0 -68
  242. package/fesm/providers/oauth-http.util.js +0 -77
  243. package/fesm/providers/social-provider.registry.js +0 -14
  244. package/fesm/providers/social-provider.registry.spec.js +0 -131
  245. package/fesm/services/auth-config.service.js +0 -103
  246. package/fesm/services/auth-config.service.spec.js +0 -96
  247. package/fesm/services/auth-datasource.provider.js +0 -87
  248. package/fesm/services/auth-datasource.provider.spec.js +0 -187
  249. package/fesm/services/auth-email.service.js +0 -488
  250. package/fesm/services/auth-email.service.spec.js +0 -411
  251. package/fesm/services/authentication.service.js +0 -1152
  252. package/fesm/services/authentication.service.spec.js +0 -975
  253. package/fesm/services/branch.service.js +0 -143
  254. package/fesm/services/branch.service.spec.js +0 -165
  255. package/fesm/services/company-selection-session.service.js +0 -111
  256. package/fesm/services/company-selection-session.service.spec.js +0 -86
  257. package/fesm/services/company.service.js +0 -130
  258. package/fesm/services/company.service.spec.js +0 -123
  259. package/fesm/services/social-auth-config.service.js +0 -93
  260. package/fesm/services/social-auth-config.service.spec.js +0 -67
  261. package/fesm/services/social-auth.service.js +0 -300
  262. package/fesm/services/social-auth.service.spec.js +0 -265
  263. package/fesm/services/user-permission.service.js +0 -226
  264. package/fesm/services/user-permission.service.spec.js +0 -250
  265. package/fesm/services/user.service.js +0 -620
  266. package/fesm/services/user.service.spec.js +0 -673
  267. package/fesm/strategies/jwt.strategy.js +0 -130
  268. package/fesm/strategies/jwt.strategy.spec.js +0 -162
  269. package/fesm/validators/password.validator.js +0 -48
  270. package/fesm/validators/password.validator.spec.js +0 -157
@@ -1,1203 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- Object.defineProperty(exports, "AuthenticationService", {
6
- enumerable: true,
7
- get: function() {
8
- return AuthenticationService;
9
- }
10
- });
11
- const _nestjsshared = require("@flusys/nestjs-shared");
12
- const _classes = require("@flusys/nestjs-shared/classes");
13
- const _constants = require("@flusys/nestjs-shared/constants");
14
- const _enums = require("@flusys/nestjs-shared/enums");
15
- const _interfaces = require("@flusys/nestjs-shared/interfaces");
16
- const _utils = require("@flusys/nestjs-shared/utils");
17
- const _common = require("@nestjs/common");
18
- const _jwt = require("@nestjs/jwt");
19
- const _bcrypt = /*#__PURE__*/ _interop_require_wildcard(require("bcrypt"));
20
- const _config = require("../config");
21
- const _authenticationdto = require("../dtos/authentication.dto");
22
- const _appuserentity = require("../entities/app-user.entity");
23
- const _companybranchentity = require("../entities/company-branch.entity");
24
- const _companyentity = require("../entities/company.entity");
25
- const _pendingregistrationentity = require("../entities/pending-registration.entity");
26
- const _usercompanypermissionentity = require("../entities/user-company-permission.entity");
27
- const _enums1 = require("../enums");
28
- const _helpers = require("../helpers");
29
- const _userenricherinterface = require("../interfaces/user-enricher.interface");
30
- const _authconfigservice = require("./auth-config.service");
31
- const _authdatasourceprovider = require("./auth-datasource.provider");
32
- const _authemailservice = require("./auth-email.service");
33
- const _companyselectionsessionservice = require("./company-selection-session.service");
34
- function _define_property(obj, key, value) {
35
- if (key in obj) {
36
- Object.defineProperty(obj, key, {
37
- value: value,
38
- enumerable: true,
39
- configurable: true,
40
- writable: true
41
- });
42
- } else {
43
- obj[key] = value;
44
- }
45
- return obj;
46
- }
47
- function _getRequireWildcardCache(nodeInterop) {
48
- if (typeof WeakMap !== "function") return null;
49
- var cacheBabelInterop = new WeakMap();
50
- var cacheNodeInterop = new WeakMap();
51
- return (_getRequireWildcardCache = function(nodeInterop) {
52
- return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
53
- })(nodeInterop);
54
- }
55
- function _interop_require_wildcard(obj, nodeInterop) {
56
- if (!nodeInterop && obj && obj.__esModule) {
57
- return obj;
58
- }
59
- if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
60
- return {
61
- default: obj
62
- };
63
- }
64
- var cache = _getRequireWildcardCache(nodeInterop);
65
- if (cache && cache.has(obj)) {
66
- return cache.get(obj);
67
- }
68
- var newObj = {
69
- __proto__: null
70
- };
71
- var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
72
- for(var key in obj){
73
- if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
74
- var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
75
- if (desc && (desc.get || desc.set)) {
76
- Object.defineProperty(newObj, key, desc);
77
- } else {
78
- newObj[key] = obj[key];
79
- }
80
- }
81
- }
82
- newObj.default = obj;
83
- if (cache) {
84
- cache.set(obj, newObj);
85
- }
86
- return newObj;
87
- }
88
- function _ts_decorate(decorators, target, key, desc) {
89
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
90
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
91
- else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
92
- return c > 3 && r && Object.defineProperty(target, key, r), r;
93
- }
94
- function _ts_metadata(k, v) {
95
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
96
- }
97
- function _ts_param(paramIndex, decorator) {
98
- return function(target, key) {
99
- decorator(target, key, paramIndex);
100
- };
101
- }
102
- let AuthenticationService = class AuthenticationService {
103
- isCompanyFeatureEnabled() {
104
- return this.dataSourceProvider?.isCompanyFeatureEnabled() ?? this.authConfig.isCompanyFeatureEnabled();
105
- }
106
- isEmailVerificationEnabled() {
107
- const featureEnabled = this.dataSourceProvider?.isEmailVerificationEnabled() ?? this.authConfig.isEmailVerificationEnabled();
108
- const providerAvailable = this.authEmailService?.isEmailEnabled() ?? false;
109
- return featureEnabled && providerAvailable;
110
- }
111
- isSignUpEnabled() {
112
- return this.dataSourceProvider?.isSignUpEnabled() ?? this.authConfig.isSignUpEnabled();
113
- }
114
- async getUserRepository() {
115
- if (!this.dataSourceProvider) {
116
- throw new _common.InternalServerErrorException({
117
- message: 'User repository not available',
118
- messageKey: _constants.SYSTEM_MESSAGES.REPOSITORY_NOT_AVAILABLE,
119
- messageVariables: {
120
- entity: 'AppUser'
121
- }
122
- });
123
- }
124
- return this.dataSourceProvider.getRepository(_appuserentity.AppUser);
125
- }
126
- async getCompanyScopedRepository(entity) {
127
- if (!this.isCompanyFeatureEnabled() || !this.dataSourceProvider) return null;
128
- return this.dataSourceProvider.getRepository(entity);
129
- }
130
- async login(email, password) {
131
- if (this.isEmailVerificationEnabled() && await this.authEmailService.hasPendingRegistration(email)) {
132
- return {
133
- requiresEmailVerification: true,
134
- email,
135
- message: 'Please verify your email address to complete registration.',
136
- messageKey: _config.EMAIL_VERIFICATION_MESSAGES.VERIFICATION_SENT
137
- };
138
- }
139
- const user = await this.validateUser(email, password);
140
- this.ensureUserActive(user);
141
- if (this.isEmailVerificationEnabled() && !user.emailVerified) {
142
- return {
143
- requiresEmailVerification: true,
144
- email: user.email,
145
- message: 'Please verify your email address before logging in.',
146
- messageKey: _config.AUTH_MESSAGES.LOGIN_EMAIL_NOT_VERIFIED
147
- };
148
- }
149
- return this.issueLoginForUser(user);
150
- }
151
- async issueLoginForUser(user) {
152
- this.ensureUserActive(user);
153
- if (!this.isCompanyFeatureEnabled()) {
154
- return this.generateLoginResponse(user);
155
- }
156
- return await this.handleCompanyBasedLogin(user);
157
- }
158
- ensureUserActive(user) {
159
- if (!user.isActive) {
160
- throw new _common.ForbiddenException({
161
- message: 'User account is deactivated',
162
- messageKey: _config.AUTH_MESSAGES.LOGIN_ACCOUNT_DEACTIVATED
163
- });
164
- }
165
- }
166
- async handleCompanyBasedLogin(user) {
167
- const permissionRepository = await this.getCompanyScopedRepository(_usercompanypermissionentity.UserCompanyPermission);
168
- const branchRepository = await this.getCompanyScopedRepository(_companybranchentity.CompanyBranch);
169
- if (!permissionRepository || !branchRepository) {
170
- return this.generateLoginResponse(user);
171
- }
172
- const companyPermissions = await permissionRepository.find({
173
- where: {
174
- userId: user.id,
175
- permissionType: _enums1.PermissionType.COMPANY
176
- }
177
- });
178
- const companyRepository = await this.getCompanyScopedRepository(_companyentity.Company);
179
- if (!companyRepository) {
180
- return this.generateLoginResponse(user);
181
- }
182
- const companyIds = companyPermissions.map((p)=>p.targetId);
183
- const companies = companyIds.length > 0 ? await companyRepository.createQueryBuilder('c').where('c.id IN (:...ids)', {
184
- ids: companyIds
185
- }).andWhere('c.is_active = :active', {
186
- active: true
187
- }).getMany() : [];
188
- if (companies.length === 0) {
189
- return this.generateLoginResponse(user);
190
- }
191
- const branchPermissions = await permissionRepository.find({
192
- where: {
193
- userId: user.id,
194
- permissionType: _enums1.PermissionType.BRANCH
195
- }
196
- });
197
- const branchIds = branchPermissions.map((p)=>p.targetId);
198
- const branches = branchIds.length > 0 ? await branchRepository.createQueryBuilder('b').leftJoinAndSelect('b.company', 'company').where('b.id IN (:...ids)', {
199
- ids: branchIds
200
- }).andWhere('b.is_active = :active', {
201
- active: true
202
- }).getMany() : [];
203
- if (companies.length === 1 && branches.length === 1) {
204
- return this.generateLoginResponseWithCompany(user, companies[0], branches[0]);
205
- }
206
- return await this.generateCompanySelectionResponse(user, companies, branches);
207
- }
208
- async register(dto, verifyUrlBase) {
209
- const userRepository = await this.getUserRepository();
210
- const existingUser = await userRepository.findOne({
211
- where: {
212
- email: dto.email
213
- },
214
- withDeleted: true
215
- });
216
- if (existingUser?.deletedAt) {
217
- throw new _common.BadRequestException({
218
- message: 'This account has been permanently deleted. Please contact your system administrator.',
219
- messageKey: _config.AUTH_MESSAGES.REGISTER_ACCOUNT_DELETED
220
- });
221
- }
222
- if (existingUser && this.isCompanyFeatureEnabled()) {
223
- return await this.handleExistingUserCompanyRegistration(existingUser, dto);
224
- }
225
- if (existingUser) {
226
- throw new _common.BadRequestException({
227
- message: 'Registration failed due to email exists. Please try again or contact support.',
228
- messageKey: _config.AUTH_MESSAGES.REGISTER_EMAIL_EXISTS
229
- });
230
- }
231
- if (!this.isSignUpEnabled()) {
232
- throw new _common.BadRequestException({
233
- message: 'New account registration is currently disabled.',
234
- messageKey: _config.AUTH_MESSAGES.REGISTER_SIGNUP_DISABLED
235
- });
236
- }
237
- if (this.isEmailVerificationEnabled() && verifyUrlBase) {
238
- const companyData = this.isCompanyFeatureEnabled() ? {
239
- companySlug: dto.companySlug,
240
- branchSlug: dto.branchSlug,
241
- newCompanyName: dto.newCompanyName,
242
- newCompanyPhone: dto.newCompanyPhone,
243
- newCompanyAddress: dto.newCompanyAddress
244
- } : undefined;
245
- const result = await this.authEmailService.createPendingRegistration({
246
- email: dto.email,
247
- name: dto.name,
248
- phone: dto.phone,
249
- password: dto.password,
250
- companyData,
251
- additionalFields: dto.additionalFields,
252
- verifyUrlBase
253
- });
254
- return {
255
- requiresEmailVerification: true,
256
- message: result.message,
257
- messageKey: _config.EMAIL_VERIFICATION_MESSAGES.VERIFICATION_SENT
258
- };
259
- }
260
- return await this.createUserDirectly(dto);
261
- }
262
- async handleExistingUserCompanyRegistration(existingUser, dto) {
263
- if (!dto.companySlug && !dto.newCompanyName) {
264
- throw new _common.BadRequestException({
265
- message: 'Email already registered. Please login or provide a company to join/create.',
266
- messageKey: _config.AUTH_MESSAGES.REGISTER_EMAIL_EXISTS
267
- });
268
- }
269
- const permissionRepository = await this.getCompanyScopedRepository(_usercompanypermissionentity.UserCompanyPermission);
270
- const companyRepository = await this.getCompanyScopedRepository(_companyentity.Company);
271
- if (!permissionRepository || !companyRepository) {
272
- throw new _common.BadRequestException({
273
- message: 'Company feature repositories not available',
274
- messageKey: _constants.SYSTEM_MESSAGES.REPOSITORY_NOT_AVAILABLE,
275
- messageVariables: {
276
- entity: 'Company feature'
277
- }
278
- });
279
- }
280
- if (dto.companySlug) {
281
- const company = await companyRepository.findOne({
282
- where: {
283
- slug: dto.companySlug,
284
- isActive: true
285
- }
286
- });
287
- if (company) {
288
- const existingPermission = await permissionRepository.findOne({
289
- where: {
290
- userId: existingUser.id,
291
- permissionType: _enums1.PermissionType.COMPANY,
292
- targetId: company.id
293
- }
294
- });
295
- if (existingPermission) {
296
- throw new _common.BadRequestException({
297
- message: 'You are already assigned to this company. Please login.',
298
- messageKey: _config.AUTH_MESSAGES.REGISTER_COMPANY_ALREADY_ASSIGNED
299
- });
300
- }
301
- }
302
- }
303
- return await this.processCompanyRegistration(existingUser, dto, true);
304
- }
305
- async createUserDirectly(dto) {
306
- if (!this.dataSourceProvider) {
307
- throw new _common.BadRequestException({
308
- message: 'Data source not available',
309
- messageKey: _constants.SYSTEM_MESSAGES.DATASOURCE_NOT_AVAILABLE
310
- });
311
- }
312
- const dataSource = await this.dataSourceProvider.getDataSource();
313
- const queryRunner = dataSource.createQueryRunner();
314
- await queryRunner.connect();
315
- await queryRunner.startTransaction();
316
- try {
317
- const hashedPassword = await _bcrypt.hash(dto.password, _config.BCRYPT_SALT_ROUNDS);
318
- const user = queryRunner.manager.create(_appuserentity.AppUser, {
319
- name: dto.name,
320
- email: dto.email,
321
- phone: dto.phone,
322
- password: hashedPassword,
323
- isActive: true,
324
- emailVerified: false,
325
- phoneVerified: false
326
- });
327
- await queryRunner.manager.save(_appuserentity.AppUser, user);
328
- if (this.userEnricher?.onUserCreated) {
329
- await this.userEnricher.onUserCreated(user.id, dto.additionalFields ?? null, queryRunner);
330
- }
331
- await queryRunner.commitTransaction();
332
- if (!this.isCompanyFeatureEnabled()) {
333
- return this.generateRegistrationResponse(user);
334
- }
335
- return await this.processCompanyRegistration(user, dto);
336
- } catch (error) {
337
- await queryRunner.rollbackTransaction();
338
- if (error instanceof _common.BadRequestException) {
339
- throw error;
340
- }
341
- throw new _common.BadRequestException({
342
- message: 'Registration failed. Please try again.',
343
- messageKey: _config.AUTH_MESSAGES.REGISTER_FAILED
344
- });
345
- } finally{
346
- await queryRunner.release();
347
- }
348
- }
349
- async createUserFromPendingRegistration(pending) {
350
- if (!this.dataSourceProvider) {
351
- throw new _common.BadRequestException({
352
- message: 'Data source not available',
353
- messageKey: _constants.SYSTEM_MESSAGES.DATASOURCE_NOT_AVAILABLE
354
- });
355
- }
356
- const dataSource = await this.dataSourceProvider.getDataSource();
357
- const queryRunner = dataSource.createQueryRunner();
358
- await queryRunner.connect();
359
- await queryRunner.startTransaction();
360
- try {
361
- const existingUser = await queryRunner.manager.findOne(_appuserentity.AppUser, {
362
- where: {
363
- email: pending.email
364
- },
365
- withDeleted: true
366
- });
367
- if (existingUser?.deletedAt) {
368
- throw new _common.BadRequestException({
369
- message: 'This account has been permanently deleted. Please contact your system administrator.',
370
- messageKey: _config.AUTH_MESSAGES.REGISTER_ACCOUNT_DELETED
371
- });
372
- }
373
- if (existingUser) {
374
- throw new _common.BadRequestException({
375
- message: 'This email has already been registered.',
376
- messageKey: _config.AUTH_MESSAGES.REGISTER_EMAIL_EXISTS
377
- });
378
- }
379
- const user = queryRunner.manager.create(_appuserentity.AppUser, {
380
- name: pending.name,
381
- email: pending.email,
382
- phone: pending.phone,
383
- password: pending.passwordHash,
384
- isActive: true,
385
- emailVerified: true,
386
- phoneVerified: false
387
- });
388
- await queryRunner.manager.save(_appuserentity.AppUser, user);
389
- if (this.userEnricher?.onUserCreated) {
390
- await this.userEnricher.onUserCreated(user.id, pending.additionalFields ?? null, queryRunner);
391
- }
392
- await queryRunner.commitTransaction();
393
- if (this.isCompanyFeatureEnabled() && pending.companyData) {
394
- return await this.processCompanyRegistration(user, pending.companyData);
395
- }
396
- return this.generateRegistrationResponse(user);
397
- } catch (error) {
398
- await queryRunner.rollbackTransaction();
399
- if (error instanceof _common.BadRequestException) {
400
- throw error;
401
- }
402
- throw new _common.BadRequestException({
403
- message: 'Registration failed. Please try again.',
404
- messageKey: _config.AUTH_MESSAGES.REGISTER_FAILED
405
- });
406
- } finally{
407
- await queryRunner.release();
408
- }
409
- }
410
- async processCompanyRegistration(user, data, throwOnUnavailable = false) {
411
- const companyRepository = await this.getCompanyScopedRepository(_companyentity.Company);
412
- const branchRepository = await this.getCompanyScopedRepository(_companybranchentity.CompanyBranch);
413
- const permissionRepository = await this.getCompanyScopedRepository(_usercompanypermissionentity.UserCompanyPermission);
414
- if (!companyRepository || !branchRepository || !permissionRepository) {
415
- if (throwOnUnavailable) throw new _common.BadRequestException({
416
- message: 'Company feature repositories not available',
417
- messageKey: _constants.SYSTEM_MESSAGES.REPOSITORY_NOT_AVAILABLE,
418
- messageVariables: {
419
- entity: 'Company feature'
420
- }
421
- });
422
- return this.generateRegistrationResponse(user);
423
- }
424
- const { company, branch } = await this.findOrCreateCompanyAndBranch(data, companyRepository, branchRepository);
425
- if (company) {
426
- await this.assignUserPermissions(user.id, company.id, branch?.id, permissionRepository);
427
- return this.generateRegistrationResponseWithCompany(user, company, branch ?? undefined);
428
- }
429
- return this.generateRegistrationResponse(user);
430
- }
431
- async findOrCreateCompanyAndBranch(data, companyRepo, branchRepo) {
432
- if (data.companySlug) {
433
- const company = await companyRepo.findOne({
434
- where: {
435
- slug: data.companySlug,
436
- isActive: true
437
- }
438
- });
439
- if (!company) throw new _common.BadRequestException({
440
- message: 'Company not found or inactive',
441
- messageKey: _config.AUTH_MESSAGES.COMPANY_NOT_FOUND
442
- });
443
- const branch = data.branchSlug ? await branchRepo.findOne({
444
- where: {
445
- slug: data.branchSlug,
446
- companyId: company.id,
447
- isActive: true
448
- }
449
- }) : await branchRepo.findOne({
450
- where: {
451
- companyId: company.id,
452
- isActive: true
453
- },
454
- order: {
455
- serial: 'ASC',
456
- createdAt: 'ASC'
457
- }
458
- });
459
- if (data.branchSlug && !branch) throw new _common.BadRequestException({
460
- message: 'Branch not found or inactive',
461
- messageKey: _config.AUTH_MESSAGES.BRANCH_NOT_FOUND
462
- });
463
- return {
464
- company,
465
- branch
466
- };
467
- }
468
- if (data.newCompanyName) {
469
- const slug = await (0, _utils.generateUniqueSlug)(data.newCompanyName, async (baseSlug)=>{
470
- const rows = await companyRepo.createQueryBuilder('c').select('c.slug').where('c.slug = :base OR c.slug LIKE :pattern', {
471
- base: baseSlug,
472
- pattern: `${baseSlug}-%`
473
- }).getMany();
474
- return rows.map((r)=>r.slug);
475
- });
476
- const company = companyRepo.create({
477
- name: data.newCompanyName,
478
- slug,
479
- phone: data.newCompanyPhone,
480
- address: data.newCompanyAddress,
481
- isActive: true
482
- });
483
- await companyRepo.save(company);
484
- const branch = branchRepo.create({
485
- name: 'Main Branch',
486
- slug: 'main-branch',
487
- companyId: company.id,
488
- isActive: true
489
- });
490
- await branchRepo.save(branch);
491
- return {
492
- company,
493
- branch
494
- };
495
- }
496
- return {
497
- company: null,
498
- branch: null
499
- };
500
- }
501
- async assignUserPermissions(userId, companyId, branchId, permissionRepo) {
502
- await permissionRepo.save(permissionRepo.create({
503
- userId,
504
- permissionType: _enums1.PermissionType.COMPANY,
505
- targetId: companyId
506
- }));
507
- if (branchId) {
508
- await permissionRepo.save(permissionRepo.create({
509
- userId,
510
- permissionType: _enums1.PermissionType.BRANCH,
511
- targetId: branchId
512
- }));
513
- }
514
- }
515
- async select(sessionId, companyId, branchId) {
516
- this.ensureCompanyFeatureEnabled();
517
- if (!this.sessionService) {
518
- throw new _common.BadRequestException({
519
- message: 'Session service not available',
520
- messageKey: _config.AUTH_MESSAGES.SESSION_NOT_AVAILABLE
521
- });
522
- }
523
- const session = await this.sessionService.consumeSession(sessionId);
524
- if (!session) {
525
- throw new _common.UnauthorizedException({
526
- message: 'Invalid or expired session',
527
- messageKey: _config.AUTH_MESSAGES.SESSION_INVALID
528
- });
529
- }
530
- return await this.validateAndLoginWithCompany(session.userId, companyId, branchId);
531
- }
532
- async switchCompany(userId, companyId, branchId) {
533
- this.ensureCompanyFeatureEnabled();
534
- return await this.validateAndLoginWithCompany(userId, companyId, branchId);
535
- }
536
- async validateAndLoginWithCompany(userId, companyId, branchId) {
537
- const userRepository = await this.getUserRepository();
538
- const user = await userRepository.findOne({
539
- where: {
540
- id: userId
541
- }
542
- });
543
- if (!user) {
544
- throw new _common.NotFoundException({
545
- message: 'User not found',
546
- messageKey: _config.USER_MESSAGES.NOT_FOUND
547
- });
548
- }
549
- const permissionRepository = await this.getCompanyScopedRepository(_usercompanypermissionentity.UserCompanyPermission);
550
- const companyRepository = await this.getCompanyScopedRepository(_companyentity.Company);
551
- const branchRepository = await this.getCompanyScopedRepository(_companybranchentity.CompanyBranch);
552
- if (!permissionRepository || !companyRepository || !branchRepository) {
553
- throw new _common.BadRequestException({
554
- message: 'Repositories not available',
555
- messageKey: _constants.SYSTEM_MESSAGES.REPOSITORY_NOT_AVAILABLE,
556
- messageVariables: {
557
- entity: 'Some'
558
- }
559
- });
560
- }
561
- const hasCompanyAccess = await permissionRepository.findOne({
562
- where: {
563
- userId,
564
- permissionType: _enums1.PermissionType.COMPANY,
565
- targetId: companyId
566
- }
567
- });
568
- if (!hasCompanyAccess) {
569
- throw new _common.ForbiddenException({
570
- message: 'No access to this company',
571
- messageKey: _config.AUTH_MESSAGES.COMPANY_NO_ACCESS
572
- });
573
- }
574
- const company = await companyRepository.findOne({
575
- where: {
576
- id: companyId,
577
- isActive: true
578
- }
579
- });
580
- if (!company) {
581
- throw new _common.NotFoundException({
582
- message: 'Company not found or inactive',
583
- messageKey: _config.AUTH_MESSAGES.COMPANY_NOT_FOUND
584
- });
585
- }
586
- const hasBranchAccess = await permissionRepository.findOne({
587
- where: {
588
- userId,
589
- permissionType: _enums1.PermissionType.BRANCH,
590
- targetId: branchId
591
- }
592
- });
593
- if (!hasBranchAccess) {
594
- throw new _common.ForbiddenException({
595
- message: 'No access to this branch',
596
- messageKey: _config.AUTH_MESSAGES.BRANCH_NO_ACCESS
597
- });
598
- }
599
- const branch = await branchRepository.findOne({
600
- where: {
601
- id: branchId,
602
- companyId,
603
- isActive: true
604
- }
605
- });
606
- if (!branch) {
607
- throw new _common.NotFoundException({
608
- message: 'Branch not found or inactive',
609
- messageKey: _config.AUTH_MESSAGES.BRANCH_NOT_FOUND
610
- });
611
- }
612
- const response = this.generateLoginResponseWithCompany(user, company, branch);
613
- this.publishAuthEvent(_config.AUTH_EVENT_ENTITIES.SESSION, _config.AUTH_EVENT_ACTIONS.COMPANY_SWITCHED, user, {
614
- companyId: company.id,
615
- branchId: branch.id
616
- });
617
- return response;
618
- }
619
- async refreshToken(refreshToken) {
620
- try {
621
- const payload = this.jwtService.verify(refreshToken, {
622
- secret: this.authConfig.getRefreshTokenSecret(),
623
- algorithms: [
624
- 'HS256'
625
- ]
626
- });
627
- if (await this.isTokenRevoked(payload.id, payload.iat)) {
628
- throw new _common.UnauthorizedException({
629
- message: 'Token has been revoked',
630
- messageKey: _config.AUTH_MESSAGES.TOKEN_REVOKED
631
- });
632
- }
633
- const userRepository = await this.getUserRepository();
634
- const user = await userRepository.findOne({
635
- where: {
636
- id: payload.id
637
- }
638
- });
639
- if (!user || !user.isActive) {
640
- throw new _common.UnauthorizedException({
641
- message: 'Invalid refresh token',
642
- messageKey: _config.AUTH_MESSAGES.TOKEN_INVALID
643
- });
644
- }
645
- if (payload.companyId) {
646
- const companyRepository = await this.getCompanyScopedRepository(_companyentity.Company);
647
- const permissionRepository = await this.getCompanyScopedRepository(_usercompanypermissionentity.UserCompanyPermission);
648
- if (companyRepository) {
649
- const company = await companyRepository.findOne({
650
- where: {
651
- id: payload.companyId,
652
- isActive: true
653
- }
654
- });
655
- if (!company) {
656
- throw new _common.UnauthorizedException({
657
- message: 'Company not found or inactive',
658
- messageKey: _config.AUTH_MESSAGES.COMPANY_NOT_FOUND
659
- });
660
- }
661
- }
662
- if (permissionRepository) {
663
- const hasCompanyAccess = await permissionRepository.findOne({
664
- where: {
665
- userId: user.id,
666
- permissionType: _enums1.PermissionType.COMPANY,
667
- targetId: payload.companyId
668
- }
669
- });
670
- if (!hasCompanyAccess) {
671
- throw new _common.UnauthorizedException({
672
- message: 'No access to this company',
673
- messageKey: _config.AUTH_MESSAGES.COMPANY_NO_ACCESS
674
- });
675
- }
676
- }
677
- if (payload.branchId) {
678
- const branchRepository = await this.getCompanyScopedRepository(_companybranchentity.CompanyBranch);
679
- if (branchRepository) {
680
- const branch = await branchRepository.findOne({
681
- where: {
682
- id: payload.branchId,
683
- companyId: payload.companyId,
684
- isActive: true
685
- }
686
- });
687
- if (!branch) {
688
- throw new _common.UnauthorizedException({
689
- message: 'Branch not found or inactive',
690
- messageKey: _config.AUTH_MESSAGES.BRANCH_NOT_FOUND
691
- });
692
- }
693
- }
694
- if (permissionRepository) {
695
- const hasBranchAccess = await permissionRepository.findOne({
696
- where: {
697
- userId: user.id,
698
- permissionType: _enums1.PermissionType.BRANCH,
699
- targetId: payload.branchId
700
- }
701
- });
702
- if (!hasBranchAccess) {
703
- throw new _common.UnauthorizedException({
704
- message: 'No access to this branch',
705
- messageKey: _config.AUTH_MESSAGES.BRANCH_NO_ACCESS
706
- });
707
- }
708
- }
709
- }
710
- }
711
- const tokens = (0, _helpers.generateTokens)(this.jwtService, this.authConfig, {
712
- id: user.id,
713
- email: user.email,
714
- type: 'access',
715
- profilePictureId: user.profilePictureId ?? undefined,
716
- ...payload.companyId && {
717
- companyId: payload.companyId
718
- },
719
- ...payload.branchId && {
720
- branchId: payload.branchId
721
- }
722
- });
723
- this.publishAuthEvent(_config.AUTH_EVENT_ENTITIES.SESSION, _config.AUTH_EVENT_ACTIONS.TOKEN_REFRESHED, user, {
724
- companyId: payload.companyId ?? null,
725
- branchId: payload.branchId ?? null
726
- });
727
- return tokens;
728
- } catch {
729
- throw new _common.UnauthorizedException({
730
- message: 'Invalid or expired refresh token',
731
- messageKey: _config.AUTH_MESSAGES.TOKEN_EXPIRED
732
- });
733
- }
734
- }
735
- async changePassword(userId, currentPassword, newPassword) {
736
- const userRepository = await this.getUserRepository();
737
- const user = await userRepository.findOne({
738
- where: {
739
- id: userId
740
- }
741
- });
742
- if (!user) throw new _common.UnauthorizedException({
743
- message: 'User not found',
744
- messageKey: _config.USER_MESSAGES.NOT_FOUND
745
- });
746
- if (!await _bcrypt.compare(currentPassword, user.password || '')) {
747
- throw new _common.UnauthorizedException({
748
- message: 'Current password is incorrect',
749
- messageKey: _config.AUTH_MESSAGES.PASSWORD_CHANGE_INVALID_CURRENT
750
- });
751
- }
752
- user.password = await _bcrypt.hash(newPassword, _config.BCRYPT_SALT_ROUNDS);
753
- await userRepository.save(user);
754
- this.publishAuthEvent(_config.AUTH_EVENT_ENTITIES.USER, _config.AUTH_EVENT_ACTIONS.PASSWORD_CHANGED, user);
755
- }
756
- async logout(userId) {
757
- if (!this.cacheManager) {
758
- throw new _common.BadRequestException({
759
- message: 'Logout service temporarily unavailable. Please try again later.',
760
- messageKey: _config.AUTH_MESSAGES.LOGOUT_SERVICE_UNAVAILABLE
761
- });
762
- }
763
- const revokedAt = Math.floor(Date.now() / 1000);
764
- const cacheKey = `${_config.TOKEN_REVOKED_PREFIX}:${userId}`;
765
- const refreshTokenExpiry = this.authConfig.getRefreshTokenExpiration();
766
- const ttlMs = (0, _helpers.parseExpiryToMs)(refreshTokenExpiry);
767
- await this.cacheManager.set(cacheKey, revokedAt, ttlMs);
768
- await (0, _classes.publishDomainEvent)({
769
- module: _config.AUTH_EVENT_MODULE,
770
- entity: _config.AUTH_EVENT_ENTITIES.SESSION,
771
- action: _config.AUTH_EVENT_ACTIONS.LOGGED_OUT,
772
- ids: [
773
- userId
774
- ],
775
- user: {
776
- id: userId
777
- }
778
- });
779
- }
780
- async isTokenRevoked(userId, tokenIssuedAt) {
781
- if (!this.cacheManager || !tokenIssuedAt) {
782
- return false;
783
- }
784
- const cacheKey = `${_config.TOKEN_REVOKED_PREFIX}:${userId}`;
785
- const revokedAt = await this.cacheManager.get(cacheKey);
786
- if (!revokedAt) {
787
- return false;
788
- }
789
- return tokenIssuedAt < revokedAt;
790
- }
791
- async getUserCompanies(userId) {
792
- this.ensureCompanyFeatureEnabled();
793
- const permissionRepository = await this.getCompanyScopedRepository(_usercompanypermissionentity.UserCompanyPermission);
794
- const companyRepository = await this.getCompanyScopedRepository(_companyentity.Company);
795
- if (!permissionRepository || !companyRepository) {
796
- throw new _common.BadRequestException({
797
- message: 'Repositories not available',
798
- messageKey: _constants.SYSTEM_MESSAGES.REPOSITORY_NOT_AVAILABLE,
799
- messageVariables: {
800
- entity: 'Some'
801
- }
802
- });
803
- }
804
- const permissions = await permissionRepository.find({
805
- where: {
806
- userId,
807
- permissionType: _enums1.PermissionType.COMPANY
808
- }
809
- });
810
- const companyIds = permissions.map((p)=>p.targetId);
811
- if (companyIds.length === 0) return [];
812
- return companyRepository.createQueryBuilder('c').where('c.id IN (:...ids)', {
813
- ids: companyIds
814
- }).andWhere('c.is_active = :active', {
815
- active: true
816
- }).orderBy('c.name', 'ASC').getMany();
817
- }
818
- async getUserBranches(userId, companyId) {
819
- this.ensureCompanyFeatureEnabled();
820
- const permissionRepository = await this.getCompanyScopedRepository(_usercompanypermissionentity.UserCompanyPermission);
821
- const branchRepository = await this.getCompanyScopedRepository(_companybranchentity.CompanyBranch);
822
- if (!permissionRepository || !branchRepository) {
823
- throw new _common.BadRequestException({
824
- message: 'Repositories not available',
825
- messageKey: _constants.SYSTEM_MESSAGES.REPOSITORY_NOT_AVAILABLE,
826
- messageVariables: {
827
- entity: 'Some'
828
- }
829
- });
830
- }
831
- const companyPermission = await permissionRepository.findOne({
832
- where: {
833
- userId,
834
- permissionType: _enums1.PermissionType.COMPANY,
835
- targetId: companyId
836
- }
837
- });
838
- if (!companyPermission) {
839
- throw new _common.UnauthorizedException({
840
- message: 'No access to this company',
841
- messageKey: _config.AUTH_MESSAGES.COMPANY_NO_ACCESS
842
- });
843
- }
844
- const branchPermissions = await permissionRepository.find({
845
- where: {
846
- userId,
847
- permissionType: _enums1.PermissionType.BRANCH
848
- }
849
- });
850
- const branchIds = branchPermissions.map((p)=>p.targetId);
851
- if (branchIds.length === 0) return [];
852
- return branchRepository.createQueryBuilder('b').where('b.id IN (:...ids)', {
853
- ids: branchIds
854
- }).andWhere('b.company_id = :companyId', {
855
- companyId
856
- }).andWhere('b.is_active = :active', {
857
- active: true
858
- }).orderBy('b.serial', 'ASC').addOrderBy('b.name', 'ASC').getMany();
859
- }
860
- async getCompanyById(companyId) {
861
- const companyRepository = await this.getCompanyScopedRepository(_companyentity.Company);
862
- if (!companyRepository) {
863
- return null;
864
- }
865
- return companyRepository.findOne({
866
- where: {
867
- id: companyId
868
- }
869
- });
870
- }
871
- async getBranchById(branchId) {
872
- const branchRepository = await this.getCompanyScopedRepository(_companybranchentity.CompanyBranch);
873
- if (!branchRepository) {
874
- return null;
875
- }
876
- return branchRepository.findOne({
877
- where: {
878
- id: branchId
879
- }
880
- });
881
- }
882
- async getUserInfo(userId, companyId, branchId) {
883
- const userRepository = await this.getUserRepository();
884
- const user = await userRepository.findOne({
885
- where: {
886
- id: userId
887
- }
888
- });
889
- if (!user) throw new _common.UnauthorizedException({
890
- message: 'User not found',
891
- messageKey: _config.USER_MESSAGES.NOT_FOUND
892
- });
893
- const response = {
894
- user: (0, _helpers.toUserInfo)(user)
895
- };
896
- if (this.isCompanyFeatureEnabled()) {
897
- if (!companyId) {
898
- throw new _common.UnauthorizedException({
899
- message: 'Company feature is enabled but user has no company assigned.',
900
- messageKey: _config.AUTH_MESSAGES.COMPANY_REQUIRED
901
- });
902
- }
903
- const company = await this.getCompanyById(companyId);
904
- if (!company) throw new _common.UnauthorizedException({
905
- message: 'Company not found.',
906
- messageKey: _config.AUTH_MESSAGES.COMPANY_NOT_FOUND
907
- });
908
- response.company = (0, _helpers.toCompanyInfo)(company);
909
- if (branchId) {
910
- const branch = await this.getBranchById(branchId);
911
- if (!branch) throw new _common.UnauthorizedException({
912
- message: 'Branch not found.',
913
- messageKey: _config.AUTH_MESSAGES.BRANCH_NOT_FOUND
914
- });
915
- response.branch = (0, _helpers.toBranchInfo)(branch);
916
- }
917
- }
918
- return response;
919
- }
920
- ensureCompanyFeatureEnabled() {
921
- if (!this.isCompanyFeatureEnabled()) {
922
- throw new _common.BadRequestException({
923
- message: 'Company feature is not enabled',
924
- messageKey: _config.AUTH_MESSAGES.COMPANY_FEATURE_NOT_ENABLED
925
- });
926
- }
927
- }
928
- async validateUser(email, password) {
929
- const userRepository = await this.getUserRepository();
930
- const user = await userRepository.findOne({
931
- where: {
932
- email
933
- }
934
- });
935
- if (!user || !await _bcrypt.compare(password, user.password || '')) {
936
- throw new _common.UnauthorizedException({
937
- message: 'Invalid credentials',
938
- messageKey: _config.AUTH_MESSAGES.LOGIN_INVALID_CREDENTIALS
939
- });
940
- }
941
- user.lastLoginAt = new Date();
942
- await userRepository.save(user);
943
- return user;
944
- }
945
- generateLoginResponse(user) {
946
- const { accessToken, refreshToken } = (0, _helpers.generateTokens)(this.jwtService, this.authConfig, {
947
- id: user.id,
948
- email: user.email,
949
- type: 'access'
950
- });
951
- this.sendLoginNotification(user.id);
952
- this.publishAuthEvent(_config.AUTH_EVENT_ENTITIES.SESSION, _config.AUTH_EVENT_ACTIONS.LOGGED_IN, user);
953
- return {
954
- accessToken,
955
- refreshToken,
956
- user: (0, _helpers.toUserInfo)(user)
957
- };
958
- }
959
- generateLoginResponseWithCompany(user, company, branch) {
960
- const { accessToken, refreshToken } = (0, _helpers.generateTokens)(this.jwtService, this.authConfig, {
961
- id: user.id,
962
- email: user.email,
963
- type: 'access',
964
- companyId: company.id,
965
- branchId: branch?.id
966
- });
967
- this.sendLoginNotification(user.id, company.id);
968
- this.publishAuthEvent(_config.AUTH_EVENT_ENTITIES.SESSION, _config.AUTH_EVENT_ACTIONS.LOGGED_IN, user, {
969
- companyId: company.id,
970
- branchId: branch?.id ?? null
971
- });
972
- return {
973
- accessToken,
974
- refreshToken,
975
- user: (0, _helpers.toUserInfo)(user),
976
- company: (0, _helpers.toCompanyInfo)(company),
977
- branch: branch ? (0, _helpers.toBranchInfo)(branch) : undefined
978
- };
979
- }
980
- sendLoginNotification(userId, companyId) {
981
- if (!this.notificationAdapter) return;
982
- this.notificationAdapter.send({
983
- userId,
984
- title: 'Login successful',
985
- message: 'You have successfully logged in to your account.',
986
- type: _enums.NotificationType.INFO,
987
- companyId,
988
- realtime: false
989
- }).catch(()=>{
990
- // Silent failure - notification is non-critical
991
- });
992
- }
993
- async generateCompanySelectionResponse(user, companies, branches) {
994
- if (!this.sessionService) {
995
- throw new _common.BadRequestException({
996
- message: 'Session service not available',
997
- messageKey: _config.AUTH_MESSAGES.SESSION_NOT_AVAILABLE
998
- });
999
- }
1000
- const sessionId = await this.sessionService.createSession(user.id);
1001
- const companiesWithBranches = companies.map((company)=>({
1002
- ...(0, _helpers.toCompanyInfo)(company),
1003
- isActive: company.isActive,
1004
- branches: branches.filter((b)=>b.companyId === company.id).map((b)=>({
1005
- ...(0, _helpers.toBranchInfo)(b),
1006
- isActive: b.isActive
1007
- }))
1008
- }));
1009
- return {
1010
- requiresSelection: true,
1011
- sessionId,
1012
- expiresAt: new Date(Date.now() + 5 * 60 * 1000),
1013
- user: (0, _helpers.toUserInfo)(user),
1014
- companies: companiesWithBranches
1015
- };
1016
- }
1017
- generateRegistrationResponse(user) {
1018
- const response = {
1019
- ...this.generateLoginResponse(user),
1020
- requiresEmailVerification: false
1021
- };
1022
- this.publishAuthEvent(_config.AUTH_EVENT_ENTITIES.USER, _config.AUTH_EVENT_ACTIONS.REGISTERED, user);
1023
- return response;
1024
- }
1025
- generateRegistrationResponseWithCompany(user, company, branch) {
1026
- const response = {
1027
- ...this.generateLoginResponseWithCompany(user, company, branch),
1028
- requiresEmailVerification: false
1029
- };
1030
- this.publishAuthEvent(_config.AUTH_EVENT_ENTITIES.USER, _config.AUTH_EVENT_ACTIONS.REGISTERED, user, {
1031
- companyId: company.id,
1032
- branchId: branch?.id ?? null
1033
- });
1034
- return response;
1035
- }
1036
- /** Never awaited - a login must not wait on, or fail because of, the event bus */ publishAuthEvent(entity, action, user, metadata = {}) {
1037
- void (0, _classes.publishDomainEvent)({
1038
- module: _config.AUTH_EVENT_MODULE,
1039
- entity,
1040
- action,
1041
- ids: [
1042
- user.id
1043
- ],
1044
- metadata: {
1045
- email: user.email,
1046
- ...metadata
1047
- },
1048
- user: {
1049
- id: user.id,
1050
- email: user.email
1051
- }
1052
- });
1053
- }
1054
- // NOTE: @Inject() required for bundled code - type metadata may be lost during esbuild
1055
- constructor(jwtService, authConfig, cacheManager, dataSourceProvider, sessionService, authEmailService, userEnricher, notificationAdapter){
1056
- _define_property(this, "jwtService", void 0);
1057
- _define_property(this, "authConfig", void 0);
1058
- _define_property(this, "cacheManager", void 0);
1059
- _define_property(this, "dataSourceProvider", void 0);
1060
- _define_property(this, "sessionService", void 0);
1061
- _define_property(this, "authEmailService", void 0);
1062
- _define_property(this, "userEnricher", void 0);
1063
- _define_property(this, "notificationAdapter", void 0);
1064
- this.jwtService = jwtService;
1065
- this.authConfig = authConfig;
1066
- this.cacheManager = cacheManager;
1067
- this.dataSourceProvider = dataSourceProvider;
1068
- this.sessionService = sessionService;
1069
- this.authEmailService = authEmailService;
1070
- this.userEnricher = userEnricher;
1071
- this.notificationAdapter = notificationAdapter;
1072
- }
1073
- };
1074
- _ts_decorate([
1075
- (0, _nestjsshared.LogAction)({
1076
- action: 'auth.login',
1077
- module: 'auth',
1078
- includeParams: false
1079
- }),
1080
- _ts_metadata("design:type", Function),
1081
- _ts_metadata("design:paramtypes", [
1082
- String,
1083
- String
1084
- ]),
1085
- _ts_metadata("design:returntype", Promise)
1086
- ], AuthenticationService.prototype, "login", null);
1087
- _ts_decorate([
1088
- (0, _nestjsshared.LogAction)({
1089
- action: 'auth.register',
1090
- module: 'auth',
1091
- includeParams: false
1092
- }),
1093
- _ts_metadata("design:type", Function),
1094
- _ts_metadata("design:paramtypes", [
1095
- typeof _authenticationdto.RegistrationDto === "undefined" ? Object : _authenticationdto.RegistrationDto,
1096
- String
1097
- ]),
1098
- _ts_metadata("design:returntype", Promise)
1099
- ], AuthenticationService.prototype, "register", null);
1100
- _ts_decorate([
1101
- (0, _nestjsshared.LogAction)({
1102
- action: 'auth.createUser',
1103
- module: 'auth',
1104
- includeParams: false
1105
- }),
1106
- _ts_metadata("design:type", Function),
1107
- _ts_metadata("design:paramtypes", [
1108
- typeof _authenticationdto.RegistrationDto === "undefined" ? Object : _authenticationdto.RegistrationDto
1109
- ]),
1110
- _ts_metadata("design:returntype", Promise)
1111
- ], AuthenticationService.prototype, "createUserDirectly", null);
1112
- _ts_decorate([
1113
- (0, _nestjsshared.LogAction)({
1114
- action: 'auth.createUserFromPending',
1115
- module: 'auth',
1116
- includeParams: false
1117
- }),
1118
- _ts_metadata("design:type", Function),
1119
- _ts_metadata("design:paramtypes", [
1120
- typeof _pendingregistrationentity.PendingRegistration === "undefined" ? Object : _pendingregistrationentity.PendingRegistration
1121
- ]),
1122
- _ts_metadata("design:returntype", Promise)
1123
- ], AuthenticationService.prototype, "createUserFromPendingRegistration", null);
1124
- _ts_decorate([
1125
- (0, _nestjsshared.LogAction)({
1126
- action: 'auth.companySwitch',
1127
- module: 'auth'
1128
- }),
1129
- _ts_metadata("design:type", Function),
1130
- _ts_metadata("design:paramtypes", [
1131
- String,
1132
- String,
1133
- String
1134
- ]),
1135
- _ts_metadata("design:returntype", Promise)
1136
- ], AuthenticationService.prototype, "validateAndLoginWithCompany", null);
1137
- _ts_decorate([
1138
- (0, _nestjsshared.LogAction)({
1139
- action: 'auth.refreshToken',
1140
- module: 'auth',
1141
- includeParams: false
1142
- }),
1143
- _ts_metadata("design:type", Function),
1144
- _ts_metadata("design:paramtypes", [
1145
- String
1146
- ]),
1147
- _ts_metadata("design:returntype", Promise)
1148
- ], AuthenticationService.prototype, "refreshToken", null);
1149
- _ts_decorate([
1150
- (0, _nestjsshared.LogAction)({
1151
- action: 'auth.changePassword',
1152
- module: 'auth',
1153
- includeParams: false
1154
- }),
1155
- _ts_metadata("design:type", Function),
1156
- _ts_metadata("design:paramtypes", [
1157
- String,
1158
- String,
1159
- String
1160
- ]),
1161
- _ts_metadata("design:returntype", Promise)
1162
- ], AuthenticationService.prototype, "changePassword", null);
1163
- _ts_decorate([
1164
- (0, _nestjsshared.LogAction)({
1165
- action: 'auth.logout',
1166
- module: 'auth'
1167
- }),
1168
- _ts_metadata("design:type", Function),
1169
- _ts_metadata("design:paramtypes", [
1170
- String
1171
- ]),
1172
- _ts_metadata("design:returntype", Promise)
1173
- ], AuthenticationService.prototype, "logout", null);
1174
- AuthenticationService = _ts_decorate([
1175
- (0, _common.Injectable)({
1176
- scope: _common.Scope.REQUEST
1177
- }),
1178
- _ts_param(0, (0, _common.Inject)(_jwt.JwtService)),
1179
- _ts_param(1, (0, _common.Inject)(_authconfigservice.AuthConfigService)),
1180
- _ts_param(2, (0, _common.Optional)()),
1181
- _ts_param(2, (0, _common.Inject)('CACHE_INSTANCE')),
1182
- _ts_param(3, (0, _common.Optional)()),
1183
- _ts_param(3, (0, _common.Inject)(_authdatasourceprovider.AuthDataSourceProvider)),
1184
- _ts_param(4, (0, _common.Optional)()),
1185
- _ts_param(4, (0, _common.Inject)(_companyselectionsessionservice.CompanySelectionSessionService)),
1186
- _ts_param(5, (0, _common.Optional)()),
1187
- _ts_param(5, (0, _common.Inject)(_authemailservice.AuthEmailService)),
1188
- _ts_param(6, (0, _common.Optional)()),
1189
- _ts_param(6, (0, _common.Inject)(_config.USER_ENRICHER)),
1190
- _ts_param(7, (0, _common.Optional)()),
1191
- _ts_param(7, (0, _common.Inject)(_interfaces.NOTIFICATION_ADAPTER)),
1192
- _ts_metadata("design:type", Function),
1193
- _ts_metadata("design:paramtypes", [
1194
- typeof _jwt.JwtService === "undefined" ? Object : _jwt.JwtService,
1195
- typeof _authconfigservice.AuthConfigService === "undefined" ? Object : _authconfigservice.AuthConfigService,
1196
- typeof _classes.HybridCache === "undefined" ? Object : _classes.HybridCache,
1197
- typeof _authdatasourceprovider.AuthDataSourceProvider === "undefined" ? Object : _authdatasourceprovider.AuthDataSourceProvider,
1198
- typeof _companyselectionsessionservice.CompanySelectionSessionService === "undefined" ? Object : _companyselectionsessionservice.CompanySelectionSessionService,
1199
- typeof _authemailservice.AuthEmailService === "undefined" ? Object : _authemailservice.AuthEmailService,
1200
- typeof _userenricherinterface.IUserEnricher === "undefined" ? Object : _userenricherinterface.IUserEnricher,
1201
- typeof _interfaces.INotificationAdapter === "undefined" ? Object : _interfaces.INotificationAdapter
1202
- ])
1203
- ], AuthenticationService);