@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
@@ -1,620 +0,0 @@
1
- function _define_property(obj, key, value) {
2
- if (key in obj) {
3
- Object.defineProperty(obj, key, {
4
- value: value,
5
- enumerable: true,
6
- configurable: true,
7
- writable: true
8
- });
9
- } else {
10
- obj[key] = value;
11
- }
12
- return obj;
13
- }
14
- function _ts_decorate(decorators, target, key, desc) {
15
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
17
- 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;
18
- return c > 3 && r && Object.defineProperty(target, key, r), r;
19
- }
20
- function _ts_metadata(k, v) {
21
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22
- }
23
- function _ts_param(paramIndex, decorator) {
24
- return function(target, key) {
25
- decorator(target, key, paramIndex);
26
- };
27
- }
28
- import { LogAction } from '@flusys/nestjs-shared';
29
- import { createModuleLogger, HybridCache, ApiService } from '@flusys/nestjs-shared/classes';
30
- import { SYSTEM_MESSAGES } from '@flusys/nestjs-shared/constants';
31
- import { ILoggedUserInfo } from '@flusys/nestjs-shared/interfaces';
32
- import { UtilsService } from '@flusys/nestjs-shared/modules';
33
- import { BadRequestException, ForbiddenException, Inject, Injectable, NotFoundException, Optional, Scope } from '@nestjs/common';
34
- import * as bcrypt from 'bcrypt';
35
- import { AUTH_EVENT_ENTITIES, AUTH_EVENT_MODULE, AUTH_MESSAGES, BCRYPT_SALT_ROUNDS, USER_ENRICHER, USER_MESSAGES, USER_PERMISSION_MESSAGES } from '../config';
36
- import { CreateUserDto } from '../dtos/user.dto';
37
- import { AppUser } from '../entities/app-user.entity';
38
- import { UserCompanyPermission } from '../entities/user-company-permission.entity';
39
- import { PermissionType } from '../enums';
40
- import { IUserEnricher } from '../interfaces/user-enricher.interface';
41
- import { AuthConfigService } from './auth-config.service';
42
- import { AuthDataSourceProvider } from './auth-datasource.provider';
43
- export class UserService extends ApiService {
44
- async ensureDataSourceRepository() {
45
- await super.ensureDataSourceRepository();
46
- const isCompanyFeatureEnabled = this.authConfig.isCompanyFeatureEnabled();
47
- if (isCompanyFeatureEnabled && !this.permissionRepository) {
48
- [this.permissionRepository] = await this.resolveRepositories([
49
- UserCompanyPermission
50
- ]);
51
- }
52
- if (!this.dataSource) {
53
- this.dataSource = await this.getDataSourceProvider().getDataSource();
54
- }
55
- }
56
- async getUserForProfile(userId, user) {
57
- if (userId !== user.id) {
58
- throw new ForbiddenException({
59
- message: "Cannot access another user's profile",
60
- messageKey: AUTH_MESSAGES.PROFILE_ACCESS_DENIED
61
- });
62
- }
63
- await this.ensureDataSourceRepository();
64
- const userEntity = await this.repository.findOne({
65
- where: {
66
- id: userId
67
- }
68
- });
69
- if (!userEntity) {
70
- throw new NotFoundException({
71
- message: 'User not found',
72
- messageKey: USER_MESSAGES.NOT_FOUND
73
- });
74
- }
75
- return userEntity;
76
- }
77
- async verifyEmail(id) {
78
- await this.ensureDataSourceRepository();
79
- await this.repository.update(id, {
80
- emailVerified: true
81
- });
82
- await Promise.all([
83
- this.clearCacheForAll(),
84
- this.clearCacheForId([
85
- {
86
- id
87
- }
88
- ])
89
- ]);
90
- }
91
- async verifyPhone(id) {
92
- await this.ensureDataSourceRepository();
93
- await this.repository.update(id, {
94
- phoneVerified: true
95
- });
96
- await Promise.all([
97
- this.clearCacheForAll(),
98
- this.clearCacheForId([
99
- {
100
- id
101
- }
102
- ])
103
- ]);
104
- }
105
- async updateStatus(id, isActive, user) {
106
- await this.ensureDataSourceRepository();
107
- const isCompanyFeatureEnabled = this.authConfig.isCompanyFeatureEnabled();
108
- if (isCompanyFeatureEnabled && user?.companyId && this.permissionRepository) {
109
- const permission = await this.permissionRepository.findOne({
110
- where: {
111
- userId: id,
112
- permissionType: PermissionType.COMPANY,
113
- targetId: user.companyId
114
- }
115
- });
116
- if (!permission) {
117
- throw new NotFoundException({
118
- message: 'User company permission not found',
119
- messageKey: USER_PERMISSION_MESSAGES.PERMISSION_NOT_FOUND,
120
- messageVariables: {
121
- type: 'User company'
122
- }
123
- });
124
- }
125
- permission.isActive = isActive;
126
- await this.permissionRepository.save(permission);
127
- } else {
128
- await this.repository.update(id, {
129
- isActive
130
- });
131
- }
132
- await Promise.all([
133
- this.clearCacheForAll(),
134
- this.clearCacheForId([
135
- {
136
- id
137
- }
138
- ])
139
- ]);
140
- }
141
- async convertSingleDtoToEntity(dto, user) {
142
- const entity = await super.convertSingleDtoToEntity(dto, user);
143
- if ('password' in dto && dto.password) {
144
- entity.password = await bcrypt.hash(dto.password, BCRYPT_SALT_ROUNDS);
145
- }
146
- return entity;
147
- }
148
- convertEntityToResponseDto(entity, isRaw) {
149
- if (isRaw) {
150
- return this.convertRawToResponseDto(entity);
151
- }
152
- return this.convertEntityToDto(entity);
153
- }
154
- convertRawToResponseDto(raw) {
155
- const isActive = raw.appuser_companyIsActive !== undefined ? Boolean(raw.appuser_companyIsActive) : raw.appuser_is_active;
156
- return {
157
- id: raw.appuser_id,
158
- name: raw.appuser_name,
159
- phone: raw.appuser_phone,
160
- email: raw.appuser_email,
161
- profilePictureId: raw.appuser_profile_picture_id,
162
- isActive,
163
- emailVerified: raw.appuser_email_verified,
164
- phoneVerified: raw.appuser_phone_verified,
165
- lastLoginAt: raw.appuser_last_login_at,
166
- additionalFields: raw.appuser_additional_fields,
167
- createdAt: raw.appuser_created_at,
168
- updatedAt: raw.appuser_updated_at,
169
- deletedAt: raw.appuser_deleted_at,
170
- createdById: raw.appuser_created_by_id,
171
- updatedById: raw.appuser_updated_by_id,
172
- deletedById: raw.appuser_deleted_by_id
173
- };
174
- }
175
- convertEntityToDto(entity) {
176
- return {
177
- id: entity.id,
178
- name: entity.name,
179
- phone: entity.phone,
180
- email: entity.email,
181
- profilePictureId: entity.profilePictureId,
182
- isActive: entity.isActive,
183
- emailVerified: entity.emailVerified,
184
- phoneVerified: entity.phoneVerified,
185
- lastLoginAt: entity.lastLoginAt,
186
- additionalFields: entity.additionalFields,
187
- createdAt: entity.createdAt,
188
- updatedAt: entity.updatedAt,
189
- deletedAt: entity.deletedAt,
190
- createdById: entity.createdById,
191
- updatedById: entity.updatedById,
192
- deletedById: entity.deletedById
193
- };
194
- }
195
- convertEntityListToResponseListDto(entities, isRaw) {
196
- return entities.map((entity)=>this.convertEntityToResponseDto(entity, isRaw));
197
- }
198
- async getFilterQuery(query, filter, _user) {
199
- for (const [key, value] of Object.entries(filter)){
200
- if (key === 'actionCode' || key === 'isActive') {
201
- continue; // real continue
202
- }
203
- query.andWhere(`${this.entityName}.${key} = :value`, {
204
- value
205
- });
206
- }
207
- return {
208
- query,
209
- isRaw: false
210
- };
211
- }
212
- async getGlobalSearchQuery(query, search, _user) {
213
- query.andWhere('(appuser.name LIKE :search OR appuser.email LIKE :search OR appuser.phone LIKE :search)', {
214
- search: `%${search}%`
215
- });
216
- return {
217
- query,
218
- isRaw: false
219
- };
220
- }
221
- async getExtraManipulateQuery(query, filterAndPaginationDto, user) {
222
- const superQuery = await super.getExtraManipulateQuery(query, filterAndPaginationDto, user);
223
- const isCompanyFeatureEnabled = this.authConfig.isCompanyFeatureEnabled();
224
- const filter = filterAndPaginationDto?.filter;
225
- // --- Action code filter (applies regardless of company feature) ---
226
- if (filter?.actionCode) {
227
- const actionCode = filter.actionCode;
228
- const companyId = isCompanyFeatureEnabled ? user?.companyId : undefined;
229
- if (isCompanyFeatureEnabled && !companyId) {
230
- // Company feature is on but no companyId — no results should match
231
- query.andWhere('1 = 0');
232
- return {
233
- query,
234
- isRaw: true
235
- };
236
- }
237
- const isPermissionModeFound = this.authConfig.isPermissionModeFound();
238
- if (!isPermissionModeFound) {
239
- // Optionally log a warning so the caller knows the filter was ignored
240
- this.logAdapter.warn(`actionCode filter was requested but permission mode is not set to 'found' — filter ignored`);
241
- } else {
242
- query.andWhere(`EXISTS (
243
- SELECT 1 FROM user_iam_permission perm
244
- WHERE perm.permission_type = 'user_role'
245
- AND perm.source_id = appuser.id
246
- AND perm.target_id IN (
247
- SELECT source_id FROM user_iam_permission
248
- WHERE permission_type = 'role_action'
249
- AND target_id = (SELECT id FROM action WHERE code = :actionCode)
250
- ${isCompanyFeatureEnabled ? 'AND company_id = :actionCompanyId' : ''}
251
- )
252
- ) OR EXISTS (
253
- SELECT 1 FROM user_iam_permission perm
254
- WHERE perm.permission_type = 'user_action'
255
- AND perm.source_id = appuser.id
256
- AND perm.target_id = (SELECT id FROM action WHERE code = :actionCode)
257
- ${isCompanyFeatureEnabled ? 'AND company_id = :actionCompanyId' : ''}
258
- )`, {
259
- actionCode,
260
- ...isCompanyFeatureEnabled && {
261
- actionCompanyId: companyId
262
- }
263
- });
264
- }
265
- }
266
- // --- Non-company path ---
267
- if (!isCompanyFeatureEnabled) {
268
- if (filter?.isActive !== undefined) {
269
- query.andWhere(`${this.entityName}.isActive = :value`, {
270
- value: filter.isActive
271
- });
272
- }
273
- return superQuery;
274
- }
275
- // --- Company feature path ---
276
- if (!user?.companyId || !this.permissionRepository) {
277
- return superQuery;
278
- }
279
- // Add companyIsActive as a selected column
280
- query.addSelect(`(SELECT perm.is_active FROM user_company_permissions perm
281
- WHERE perm.user_id = appuser.id
282
- AND perm.permission_type = :permissionType
283
- AND perm.target_id = :companyId
284
- LIMIT 1)`, 'user_companyIsActive');
285
- query.setParameter('permissionType', PermissionType.COMPANY);
286
- query.setParameter('companyId', user.companyId);
287
- // Filter by isActive within the company if requested
288
- if (filter?.isActive !== undefined) {
289
- query.andWhere(`EXISTS (
290
- SELECT 1 FROM user_company_permissions perm
291
- WHERE perm.user_id = appuser.id
292
- AND perm.permission_type = :permissionType
293
- AND perm.target_id = :companyId
294
- AND perm.is_active = :isActiveValue
295
- )`, {
296
- permissionType: PermissionType.COMPANY,
297
- companyId: user.companyId,
298
- isActiveValue: filter.isActive
299
- });
300
- }
301
- // Always restrict to users belonging to this company
302
- query.andWhere(`EXISTS (
303
- SELECT 1 FROM user_company_permissions perm
304
- WHERE perm.user_id = appuser.id
305
- AND perm.permission_type = :permissionType
306
- AND perm.target_id = :companyId
307
- )`, {
308
- permissionType: PermissionType.COMPANY,
309
- companyId: user.companyId
310
- });
311
- return {
312
- query,
313
- isRaw: true
314
- };
315
- }
316
- async insert(dto, user) {
317
- const isCompanyFeatureEnabled = this.authConfig.isCompanyFeatureEnabled();
318
- if (!isCompanyFeatureEnabled || !this.dataSource || !user?.companyId || !this.permissionRepository) {
319
- return await super.insert(dto, user);
320
- }
321
- const queryRunner = this.dataSource.createQueryRunner();
322
- await queryRunner.connect();
323
- await queryRunner.startTransaction();
324
- try {
325
- const userEntity = await this.convertSingleDtoToEntity(dto, user);
326
- const savedUser = await queryRunner.manager.save(this.repository.target, userEntity);
327
- const existingPermission = await queryRunner.manager.findOne(this.permissionRepository.target, {
328
- where: {
329
- userId: savedUser.id,
330
- permissionType: PermissionType.COMPANY,
331
- targetId: user.companyId
332
- }
333
- });
334
- if (!existingPermission) {
335
- const permission = queryRunner.manager.create(this.permissionRepository.target, {
336
- userId: savedUser.id,
337
- permissionType: PermissionType.COMPANY,
338
- targetId: user.companyId,
339
- isActive: dto.isActive ?? true
340
- });
341
- await queryRunner.manager.save(this.permissionRepository.target, permission);
342
- }
343
- if (user.branchId) {
344
- const existingBranchPermission = await queryRunner.manager.findOne(this.permissionRepository.target, {
345
- where: {
346
- userId: savedUser.id,
347
- permissionType: PermissionType.BRANCH,
348
- targetId: user.branchId
349
- }
350
- });
351
- if (!existingBranchPermission) {
352
- const branchPermission = queryRunner.manager.create(this.permissionRepository.target, {
353
- userId: savedUser.id,
354
- permissionType: PermissionType.BRANCH,
355
- targetId: user.branchId,
356
- isActive: dto.isActive ?? true
357
- });
358
- await queryRunner.manager.save(this.permissionRepository.target, branchPermission);
359
- }
360
- }
361
- await queryRunner.commitTransaction();
362
- await Promise.all([
363
- this.clearCacheForAll(),
364
- this.clearCacheForId([
365
- savedUser
366
- ])
367
- ]);
368
- return this.convertEntityToResponseDto(savedUser, false);
369
- } catch (error) {
370
- await queryRunner.rollbackTransaction();
371
- throw error;
372
- } finally{
373
- await queryRunner.release();
374
- }
375
- }
376
- async getProfileWithExtras(userId, user) {
377
- const userEntity = await this.getUserForProfile(userId, user);
378
- const userData = this.convertEntityToResponseDto(userEntity, false);
379
- let extras;
380
- if (this.userEnricher?.getProfileExtras) {
381
- extras = await this.userEnricher.getProfileExtras(userId, user);
382
- }
383
- return {
384
- user: userData,
385
- extras
386
- };
387
- }
388
- async getAll(search, filterAndPaginationDto, user) {
389
- const result = await super.getAll(search, filterAndPaginationDto, user);
390
- const enrichedData = await this.getEnrichedList(result.data, user);
391
- return {
392
- data: enrichedData,
393
- total: result.total
394
- };
395
- }
396
- async getEnrichedList(users, user) {
397
- if (this.userEnricher?.enrichListItems) {
398
- return this.userEnricher.enrichListItems(users, user);
399
- }
400
- return users;
401
- }
402
- async getProfileSections() {
403
- if (this.userEnricher?.getProfileSections) {
404
- return this.userEnricher.getProfileSections();
405
- }
406
- return [];
407
- }
408
- async getProfileSectionData(userId, sectionId, user) {
409
- await this.getUserForProfile(userId, user);
410
- if (this.userEnricher?.getProfileSectionData) {
411
- return this.userEnricher.getProfileSectionData(userId, sectionId, user);
412
- }
413
- return null;
414
- }
415
- async updateProfileSection(userId, sectionId, data, user) {
416
- const userEntity = await this.getUserForProfile(userId, user);
417
- if (!this.dataSource) {
418
- throw new BadRequestException({
419
- message: 'DataSource not available',
420
- messageKey: SYSTEM_MESSAGES.DATASOURCE_NOT_AVAILABLE
421
- });
422
- }
423
- if (!this.userEnricher?.updateProfileSection) {
424
- throw new BadRequestException({
425
- message: 'Profile sections not supported',
426
- messageKey: AUTH_MESSAGES.PROFILE_SECTIONS_NOT_SUPPORTED
427
- });
428
- }
429
- const queryRunner = this.dataSource.createQueryRunner();
430
- await queryRunner.connect();
431
- await queryRunner.startTransaction();
432
- try {
433
- await this.userEnricher.updateProfileSection(userId, sectionId, data, queryRunner);
434
- await queryRunner.commitTransaction();
435
- await Promise.all([
436
- this.clearCacheForAll(),
437
- this.clearCacheForId([
438
- userEntity
439
- ])
440
- ]);
441
- } catch (error) {
442
- await queryRunner.rollbackTransaction();
443
- throw error;
444
- } finally{
445
- await queryRunner.release();
446
- }
447
- }
448
- async getProfileCompletion(userId, user) {
449
- await this.getUserForProfile(userId, user);
450
- if (this.userEnricher?.calculateProfileCompletion) {
451
- return this.userEnricher.calculateProfileCompletion(userId, user);
452
- }
453
- return 100;
454
- }
455
- async profile(dto, user) {
456
- await this.ensureDataSourceRepository();
457
- if (!this.dataSource) {
458
- throw new BadRequestException({
459
- message: 'DataSource not available',
460
- messageKey: SYSTEM_MESSAGES.DATASOURCE_NOT_AVAILABLE
461
- });
462
- }
463
- const userId = dto.id ?? user.id;
464
- if (dto.extras && this.userEnricher?.validateProfileExtras) {
465
- await this.userEnricher.validateProfileExtras(userId, dto.extras, user);
466
- }
467
- const queryRunner = this.dataSource.createQueryRunner();
468
- await queryRunner.connect();
469
- await queryRunner.startTransaction();
470
- try {
471
- const findUser = await queryRunner.manager.findOne(this.repository.target, {
472
- where: {
473
- id: userId
474
- }
475
- });
476
- if (!findUser) {
477
- throw new NotFoundException({
478
- message: 'User not found',
479
- messageKey: USER_MESSAGES.NOT_FOUND
480
- });
481
- }
482
- if (dto.password) {
483
- const isOwnProfile = !dto.id || dto.id === user.id;
484
- if (isOwnProfile) {
485
- if (!dto.oldPassword) {
486
- throw new BadRequestException({
487
- message: 'Current password is required to change your password',
488
- messageKey: AUTH_MESSAGES.PASSWORD_CHANGE_CURRENT_REQUIRED
489
- });
490
- }
491
- const isPasswordValid = await bcrypt.compare(dto.oldPassword, findUser.password);
492
- if (!isPasswordValid) {
493
- throw new BadRequestException({
494
- message: 'Current password is incorrect',
495
- messageKey: AUTH_MESSAGES.PASSWORD_CHANGE_INVALID_CURRENT
496
- });
497
- }
498
- }
499
- findUser.password = await bcrypt.hash(dto.password, BCRYPT_SALT_ROUNDS);
500
- }
501
- const { password, oldPassword, extras, emailVerified, phoneVerified, isActive, ...restDto } = dto;
502
- Object.assign(findUser, restDto);
503
- await queryRunner.manager.save(this.repository.target, findUser);
504
- if (extras && this.userEnricher?.updateProfileExtras) {
505
- await this.userEnricher.updateProfileExtras(userId, extras, queryRunner);
506
- }
507
- await queryRunner.commitTransaction();
508
- await Promise.all([
509
- this.clearCacheForAll(),
510
- this.clearCacheForId([
511
- findUser
512
- ])
513
- ]);
514
- return findUser.id;
515
- } catch (error) {
516
- await queryRunner.rollbackTransaction();
517
- throw error;
518
- } finally{
519
- await queryRunner.release();
520
- }
521
- }
522
- constructor(cacheManager, utilsService, dataSourceProvider, authConfig, userEnricher){
523
- super(AUTH_EVENT_ENTITIES.USER, cacheManager, utilsService, UserService.name, true, AUTH_EVENT_MODULE, dataSourceProvider, AppUser), _define_property(this, "cacheManager", void 0), _define_property(this, "utilsService", void 0), _define_property(this, "authConfig", void 0), _define_property(this, "userEnricher", void 0), _define_property(this, "permissionRepository", void 0), _define_property(this, "dataSource", void 0), _define_property(this, "logAdapter", void 0), this.cacheManager = cacheManager, this.utilsService = utilsService, this.authConfig = authConfig, this.userEnricher = userEnricher, this.logAdapter = createModuleLogger(this.constructor.name);
524
- }
525
- }
526
- _ts_decorate([
527
- LogAction({
528
- action: 'user.verifyEmail',
529
- module: 'auth'
530
- }),
531
- _ts_metadata("design:type", Function),
532
- _ts_metadata("design:paramtypes", [
533
- String
534
- ]),
535
- _ts_metadata("design:returntype", Promise)
536
- ], UserService.prototype, "verifyEmail", null);
537
- _ts_decorate([
538
- LogAction({
539
- action: 'user.verifyPhone',
540
- module: 'auth'
541
- }),
542
- _ts_metadata("design:type", Function),
543
- _ts_metadata("design:paramtypes", [
544
- String
545
- ]),
546
- _ts_metadata("design:returntype", Promise)
547
- ], UserService.prototype, "verifyPhone", null);
548
- _ts_decorate([
549
- LogAction({
550
- action: 'user.updateStatus',
551
- module: 'auth'
552
- }),
553
- _ts_metadata("design:type", Function),
554
- _ts_metadata("design:paramtypes", [
555
- String,
556
- Boolean,
557
- Object
558
- ]),
559
- _ts_metadata("design:returntype", Promise)
560
- ], UserService.prototype, "updateStatus", null);
561
- _ts_decorate([
562
- LogAction({
563
- action: 'user.create',
564
- module: 'auth',
565
- includeParams: false
566
- }),
567
- _ts_metadata("design:type", Function),
568
- _ts_metadata("design:paramtypes", [
569
- typeof CreateUserDto === "undefined" ? Object : CreateUserDto,
570
- Object
571
- ]),
572
- _ts_metadata("design:returntype", Promise)
573
- ], UserService.prototype, "insert", null);
574
- _ts_decorate([
575
- LogAction({
576
- action: 'user.updateProfileSection',
577
- module: 'auth',
578
- includeParams: false
579
- }),
580
- _ts_metadata("design:type", Function),
581
- _ts_metadata("design:paramtypes", [
582
- String,
583
- String,
584
- typeof Record === "undefined" ? Object : Record,
585
- typeof ILoggedUserInfo === "undefined" ? Object : ILoggedUserInfo
586
- ]),
587
- _ts_metadata("design:returntype", Promise)
588
- ], UserService.prototype, "updateProfileSection", null);
589
- _ts_decorate([
590
- LogAction({
591
- action: 'user.updateProfile',
592
- module: 'auth',
593
- includeParams: false
594
- }),
595
- _ts_metadata("design:type", Function),
596
- _ts_metadata("design:paramtypes", [
597
- Object,
598
- typeof ILoggedUserInfo === "undefined" ? Object : ILoggedUserInfo
599
- ]),
600
- _ts_metadata("design:returntype", Promise)
601
- ], UserService.prototype, "profile", null);
602
- UserService = _ts_decorate([
603
- Injectable({
604
- scope: Scope.REQUEST
605
- }),
606
- _ts_param(0, Inject('CACHE_INSTANCE')),
607
- _ts_param(1, Inject(UtilsService)),
608
- _ts_param(2, Inject(AuthDataSourceProvider)),
609
- _ts_param(3, Inject(AuthConfigService)),
610
- _ts_param(4, Optional()),
611
- _ts_param(4, Inject(USER_ENRICHER)),
612
- _ts_metadata("design:type", Function),
613
- _ts_metadata("design:paramtypes", [
614
- typeof HybridCache === "undefined" ? Object : HybridCache,
615
- typeof UtilsService === "undefined" ? Object : UtilsService,
616
- typeof AuthDataSourceProvider === "undefined" ? Object : AuthDataSourceProvider,
617
- typeof AuthConfigService === "undefined" ? Object : AuthConfigService,
618
- typeof IUserEnricher === "undefined" ? Object : IUserEnricher
619
- ])
620
- ], UserService);