@flusys/nestjs-auth 7.1.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/README.md +1 -1
  2. package/config/index.d.ts +3 -3
  3. package/config/message-keys.d.ts +4 -0
  4. package/controllers/authentication.controller.d.ts +5 -5
  5. package/controllers/branch.controller.d.ts +2 -2
  6. package/controllers/company-selection.controller.d.ts +4 -4
  7. package/controllers/company.controller.d.ts +2 -2
  8. package/controllers/email-verification.controller.d.ts +6 -6
  9. package/controllers/index.d.ts +9 -9
  10. package/controllers/social-auth-config.controller.d.ts +2 -2
  11. package/controllers/social-auth.controller.d.ts +3 -3
  12. package/controllers/user-permission.controller.d.ts +7 -4
  13. package/controllers/user.controller.d.ts +7 -7
  14. package/docs/auth-swagger.config.d.ts +2 -2
  15. package/docs/index.d.ts +1 -1
  16. package/dtos/index.d.ts +6 -6
  17. package/dtos/social-auth.dto.d.ts +1 -1
  18. package/dtos/user-permission.dto.d.ts +30 -0
  19. package/entities/company-branch.entity.d.ts +1 -1
  20. package/entities/company.entity.d.ts +1 -1
  21. package/entities/index.d.ts +14 -14
  22. package/entities/pending-registration.entity.d.ts +1 -1
  23. package/entities/user-company-permission.entity.d.ts +4 -4
  24. package/enums/index.d.ts +2 -2
  25. package/fesm/118.js +1404 -0
  26. package/fesm/120.js +2265 -0
  27. package/fesm/24.js +4422 -0
  28. package/fesm/370.js +1163 -0
  29. package/fesm/446.js +877 -0
  30. package/fesm/chunks/117.js +69 -0
  31. package/fesm/config/index.js +246 -3
  32. package/fesm/controllers/index.js +27 -9
  33. package/fesm/docs/index.js +479 -1
  34. package/fesm/dtos/index.js +135 -6
  35. package/fesm/entities/index.js +68 -22
  36. package/fesm/enums/index.js +53 -2
  37. package/fesm/helpers/index.js +115 -2
  38. package/fesm/index.js +1455 -13
  39. package/fesm/interceptors/index.js +510 -2
  40. package/fesm/interfaces/index.js +75 -8
  41. package/fesm/modules/index.js +546 -1
  42. package/fesm/runtime.js +134 -0
  43. package/fesm/services/index.js +67 -11
  44. package/helpers/auth-response.mapper.d.ts +3 -3
  45. package/helpers/index.d.ts +2 -2
  46. package/helpers/token.helper.d.ts +2 -2
  47. package/index.d.ts +13 -13
  48. package/interceptors/clear-token.interceptor.d.ts +2 -2
  49. package/interceptors/index.d.ts +2 -2
  50. package/interceptors/set-token.interceptor.d.ts +2 -2
  51. package/interfaces/auth-module-options.interface.d.ts +3 -3
  52. package/interfaces/authentication.interface.d.ts +3 -3
  53. package/interfaces/company-branch.interface.d.ts +2 -2
  54. package/interfaces/company.interface.d.ts +1 -1
  55. package/interfaces/index.d.ts +8 -8
  56. package/interfaces/social-auth.interface.d.ts +2 -2
  57. package/interfaces/user-enricher.interface.d.ts +3 -3
  58. package/modules/auth.module.d.ts +4 -4
  59. package/modules/index.d.ts +1 -1
  60. package/package.json +32 -39
  61. package/providers/facebook.social-provider.d.ts +2 -2
  62. package/providers/google.social-provider.d.ts +2 -2
  63. package/providers/index.d.ts +1 -1
  64. package/providers/linkedin.social-provider.d.ts +2 -2
  65. package/providers/microsoft.social-provider.d.ts +2 -2
  66. package/providers/social-provider.registry.d.ts +2 -2
  67. package/services/auth-config.service.d.ts +3 -3
  68. package/services/auth-datasource.provider.d.ts +3 -3
  69. package/services/auth-email.service.d.ts +3 -3
  70. package/services/authentication.service.d.ts +12 -12
  71. package/services/branch.service.d.ts +7 -7
  72. package/services/company.service.d.ts +6 -6
  73. package/services/index.d.ts +11 -11
  74. package/services/social-auth-config.service.d.ts +6 -6
  75. package/services/social-auth.service.d.ts +5 -5
  76. package/services/user-permission.service.d.ts +10 -4
  77. package/services/user.service.d.ts +7 -7
  78. package/strategies/jwt.strategy.d.ts +4 -4
  79. package/validators/password.validator.d.ts +1 -1
  80. package/cjs/config/auth.constants.js +0 -49
  81. package/cjs/config/event-actions.js +0 -47
  82. package/cjs/config/index.js +0 -20
  83. package/cjs/config/message-keys.js +0 -135
  84. package/cjs/controllers/authentication.controller.js +0 -427
  85. package/cjs/controllers/authentication.controller.spec.js +0 -219
  86. package/cjs/controllers/branch.controller.js +0 -102
  87. package/cjs/controllers/branch.controller.spec.js +0 -134
  88. package/cjs/controllers/company-selection.controller.js +0 -198
  89. package/cjs/controllers/company-selection.controller.spec.js +0 -84
  90. package/cjs/controllers/company.controller.js +0 -102
  91. package/cjs/controllers/company.controller.spec.js +0 -131
  92. package/cjs/controllers/email-verification.controller.js +0 -224
  93. package/cjs/controllers/email-verification.controller.spec.js +0 -142
  94. package/cjs/controllers/index.js +0 -26
  95. package/cjs/controllers/social-auth-config.controller.js +0 -107
  96. package/cjs/controllers/social-auth.controller.js +0 -175
  97. package/cjs/controllers/social-auth.controller.spec.js +0 -79
  98. package/cjs/controllers/user-permission.controller.js +0 -223
  99. package/cjs/controllers/user-permission.controller.spec.js +0 -138
  100. package/cjs/controllers/user.controller.js +0 -438
  101. package/cjs/controllers/user.controller.spec.js +0 -204
  102. package/cjs/docs/auth-swagger.config.js +0 -461
  103. package/cjs/docs/auth-swagger.config.spec.js +0 -130
  104. package/cjs/docs/index.js +0 -18
  105. package/cjs/dtos/authentication.dto.js +0 -755
  106. package/cjs/dtos/company-branch.dto.js +0 -294
  107. package/cjs/dtos/company.dto.js +0 -298
  108. package/cjs/dtos/index.js +0 -23
  109. package/cjs/dtos/social-auth.dto.js +0 -318
  110. package/cjs/dtos/user-permission.dto.js +0 -358
  111. package/cjs/dtos/user.dto.js +0 -413
  112. package/cjs/entities/app-user.entity.js +0 -25
  113. package/cjs/entities/company-branch.entity.js +0 -163
  114. package/cjs/entities/company.entity.js +0 -146
  115. package/cjs/entities/index.js +0 -67
  116. package/cjs/entities/index.spec.js +0 -84
  117. package/cjs/entities/pending-registration.entity.js +0 -135
  118. package/cjs/entities/social-auth-config.entity.js +0 -102
  119. package/cjs/entities/user-company-permission.entity.js +0 -153
  120. package/cjs/entities/user-token.entity.js +0 -120
  121. package/cjs/enums/index.js +0 -19
  122. package/cjs/enums/social-provider-type.enum.js +0 -17
  123. package/cjs/enums/user-org-permission-type.enum.js +0 -15
  124. package/cjs/helpers/auth-response.mapper.js +0 -46
  125. package/cjs/helpers/auth-response.mapper.spec.js +0 -139
  126. package/cjs/helpers/index.js +0 -19
  127. package/cjs/helpers/token.helper.js +0 -58
  128. package/cjs/helpers/token.helper.spec.js +0 -86
  129. package/cjs/index.js +0 -30
  130. package/cjs/interceptors/clear-token.interceptor.js +0 -73
  131. package/cjs/interceptors/clear-token.interceptor.spec.js +0 -107
  132. package/cjs/interceptors/index.js +0 -19
  133. package/cjs/interceptors/set-token.interceptor.js +0 -107
  134. package/cjs/interceptors/set-token.interceptor.spec.js +0 -165
  135. package/cjs/interfaces/auth-email-provider.interface.js +0 -45
  136. package/cjs/interfaces/auth-module-options.interface.js +0 -4
  137. package/cjs/interfaces/authentication.interface.js +0 -4
  138. package/cjs/interfaces/company-branch.interface.js +0 -4
  139. package/cjs/interfaces/company.interface.js +0 -4
  140. package/cjs/interfaces/index.js +0 -25
  141. package/cjs/interfaces/social-auth.interface.js +0 -4
  142. package/cjs/interfaces/user-enricher.interface.js +0 -4
  143. package/cjs/interfaces/user.interface.js +0 -4
  144. package/cjs/modules/auth.module.js +0 -208
  145. package/cjs/modules/auth.module.spec.js +0 -258
  146. package/cjs/modules/index.js +0 -18
  147. package/cjs/providers/facebook.social-provider.js +0 -73
  148. package/cjs/providers/google.social-provider.js +0 -68
  149. package/cjs/providers/index.js +0 -18
  150. package/cjs/providers/linkedin.social-provider.js +0 -66
  151. package/cjs/providers/microsoft.social-provider.js +0 -78
  152. package/cjs/providers/oauth-http.util.js +0 -107
  153. package/cjs/providers/social-provider.registry.js +0 -24
  154. package/cjs/providers/social-provider.registry.spec.js +0 -135
  155. package/cjs/services/auth-config.service.js +0 -113
  156. package/cjs/services/auth-config.service.spec.js +0 -100
  157. package/cjs/services/auth-datasource.provider.js +0 -138
  158. package/cjs/services/auth-datasource.provider.spec.js +0 -191
  159. package/cjs/services/auth-email.service.js +0 -539
  160. package/cjs/services/auth-email.service.spec.js +0 -456
  161. package/cjs/services/authentication.service.js +0 -1203
  162. package/cjs/services/authentication.service.spec.js +0 -1020
  163. package/cjs/services/branch.service.js +0 -153
  164. package/cjs/services/branch.service.spec.js +0 -169
  165. package/cjs/services/company-selection-session.service.js +0 -121
  166. package/cjs/services/company-selection-session.service.spec.js +0 -90
  167. package/cjs/services/company.service.js +0 -140
  168. package/cjs/services/company.service.spec.js +0 -127
  169. package/cjs/services/index.js +0 -28
  170. package/cjs/services/social-auth-config.service.js +0 -103
  171. package/cjs/services/social-auth-config.service.spec.js +0 -71
  172. package/cjs/services/social-auth.service.js +0 -310
  173. package/cjs/services/social-auth.service.spec.js +0 -310
  174. package/cjs/services/user-permission.service.js +0 -236
  175. package/cjs/services/user-permission.service.spec.js +0 -254
  176. package/cjs/services/user.service.js +0 -671
  177. package/cjs/services/user.service.spec.js +0 -718
  178. package/cjs/strategies/jwt.strategy.js +0 -140
  179. package/cjs/strategies/jwt.strategy.spec.js +0 -166
  180. package/cjs/validators/password.validator.js +0 -45
  181. package/cjs/validators/password.validator.spec.js +0 -161
  182. package/fesm/config/auth.constants.js +0 -14
  183. package/fesm/config/event-actions.js +0 -26
  184. package/fesm/config/message-keys.js +0 -99
  185. package/fesm/controllers/authentication.controller.js +0 -417
  186. package/fesm/controllers/authentication.controller.spec.js +0 -215
  187. package/fesm/controllers/branch.controller.js +0 -92
  188. package/fesm/controllers/branch.controller.spec.js +0 -130
  189. package/fesm/controllers/company-selection.controller.js +0 -188
  190. package/fesm/controllers/company-selection.controller.spec.js +0 -80
  191. package/fesm/controllers/company.controller.js +0 -92
  192. package/fesm/controllers/company.controller.spec.js +0 -127
  193. package/fesm/controllers/email-verification.controller.js +0 -214
  194. package/fesm/controllers/email-verification.controller.spec.js +0 -138
  195. package/fesm/controllers/social-auth-config.controller.js +0 -97
  196. package/fesm/controllers/social-auth.controller.js +0 -165
  197. package/fesm/controllers/social-auth.controller.spec.js +0 -75
  198. package/fesm/controllers/user-permission.controller.js +0 -213
  199. package/fesm/controllers/user-permission.controller.spec.js +0 -134
  200. package/fesm/controllers/user.controller.js +0 -428
  201. package/fesm/controllers/user.controller.spec.js +0 -200
  202. package/fesm/docs/auth-swagger.config.js +0 -454
  203. package/fesm/docs/auth-swagger.config.spec.js +0 -126
  204. package/fesm/dtos/authentication.dto.js +0 -683
  205. package/fesm/dtos/company-branch.dto.js +0 -279
  206. package/fesm/dtos/company.dto.js +0 -283
  207. package/fesm/dtos/social-auth.dto.js +0 -282
  208. package/fesm/dtos/user-permission.dto.js +0 -339
  209. package/fesm/dtos/user.dto.js +0 -391
  210. package/fesm/entities/app-user.entity.js +0 -15
  211. package/fesm/entities/company-branch.entity.js +0 -153
  212. package/fesm/entities/company.entity.js +0 -136
  213. package/fesm/entities/index.spec.js +0 -80
  214. package/fesm/entities/pending-registration.entity.js +0 -125
  215. package/fesm/entities/social-auth-config.entity.js +0 -92
  216. package/fesm/entities/user-company-permission.entity.js +0 -136
  217. package/fesm/entities/user-token.entity.js +0 -104
  218. package/fesm/enums/social-provider-type.enum.js +0 -7
  219. package/fesm/enums/user-org-permission-type.enum.js +0 -5
  220. package/fesm/helpers/auth-response.mapper.js +0 -25
  221. package/fesm/helpers/auth-response.mapper.spec.js +0 -135
  222. package/fesm/helpers/token.helper.js +0 -40
  223. package/fesm/helpers/token.helper.spec.js +0 -82
  224. package/fesm/interceptors/clear-token.interceptor.js +0 -63
  225. package/fesm/interceptors/clear-token.interceptor.spec.js +0 -103
  226. package/fesm/interceptors/set-token.interceptor.js +0 -98
  227. package/fesm/interceptors/set-token.interceptor.spec.js +0 -161
  228. package/fesm/interfaces/auth-email-provider.interface.js +0 -38
  229. package/fesm/interfaces/auth-module-options.interface.js +0 -3
  230. package/fesm/interfaces/authentication.interface.js +0 -1
  231. package/fesm/interfaces/company-branch.interface.js +0 -1
  232. package/fesm/interfaces/company.interface.js +0 -1
  233. package/fesm/interfaces/social-auth.interface.js +0 -1
  234. package/fesm/interfaces/user-enricher.interface.js +0 -4
  235. package/fesm/interfaces/user.interface.js +0 -1
  236. package/fesm/modules/auth.module.js +0 -198
  237. package/fesm/modules/auth.module.spec.js +0 -254
  238. package/fesm/providers/facebook.social-provider.js +0 -63
  239. package/fesm/providers/google.social-provider.js +0 -58
  240. package/fesm/providers/index.js +0 -1
  241. package/fesm/providers/linkedin.social-provider.js +0 -56
  242. package/fesm/providers/microsoft.social-provider.js +0 -68
  243. package/fesm/providers/oauth-http.util.js +0 -77
  244. package/fesm/providers/social-provider.registry.js +0 -14
  245. package/fesm/providers/social-provider.registry.spec.js +0 -131
  246. package/fesm/services/auth-config.service.js +0 -103
  247. package/fesm/services/auth-config.service.spec.js +0 -96
  248. package/fesm/services/auth-datasource.provider.js +0 -87
  249. package/fesm/services/auth-datasource.provider.spec.js +0 -187
  250. package/fesm/services/auth-email.service.js +0 -488
  251. package/fesm/services/auth-email.service.spec.js +0 -411
  252. package/fesm/services/authentication.service.js +0 -1152
  253. package/fesm/services/authentication.service.spec.js +0 -975
  254. package/fesm/services/branch.service.js +0 -143
  255. package/fesm/services/branch.service.spec.js +0 -165
  256. package/fesm/services/company-selection-session.service.js +0 -111
  257. package/fesm/services/company-selection-session.service.spec.js +0 -86
  258. package/fesm/services/company.service.js +0 -130
  259. package/fesm/services/company.service.spec.js +0 -123
  260. package/fesm/services/social-auth-config.service.js +0 -93
  261. package/fesm/services/social-auth-config.service.spec.js +0 -67
  262. package/fesm/services/social-auth.service.js +0 -300
  263. package/fesm/services/social-auth.service.spec.js +0 -265
  264. package/fesm/services/user-permission.service.js +0 -226
  265. package/fesm/services/user-permission.service.spec.js +0 -250
  266. package/fesm/services/user.service.js +0 -620
  267. package/fesm/services/user.service.spec.js +0 -673
  268. package/fesm/strategies/jwt.strategy.js +0 -130
  269. package/fesm/strategies/jwt.strategy.spec.js +0 -162
  270. package/fesm/validators/password.validator.js +0 -48
  271. package/fesm/validators/password.validator.spec.js +0 -157
@@ -1,975 +0,0 @@
1
- import { BadRequestException, ForbiddenException, NotFoundException, UnauthorizedException } from '@nestjs/common';
2
- import * as bcrypt from 'bcrypt';
3
- import { createMockRepository } from '@test-utils/mocks/repository.mock';
4
- import { EventBusRegistry } from '@flusys/nestjs-shared/classes';
5
- import { AuthenticationService } from './authentication.service';
6
- import { AppUser } from '../entities/app-user.entity';
7
- import { Company } from '../entities/company.entity';
8
- import { CompanyBranch } from '../entities/company-branch.entity';
9
- import { PermissionType, UserCompanyPermission } from '../entities/user-company-permission.entity';
10
- jest.mock('bcrypt', ()=>({
11
- hash: jest.fn().mockResolvedValue('hashed-password'),
12
- compare: jest.fn().mockResolvedValue(true)
13
- }));
14
- function buildUser(overrides = {}) {
15
- return {
16
- id: 'user-1',
17
- email: 'user@example.com',
18
- name: 'Test User',
19
- phone: null,
20
- password: 'hashed',
21
- isActive: true,
22
- emailVerified: true,
23
- phoneVerified: false,
24
- profilePictureId: null,
25
- lastLoginAt: null,
26
- additionalFields: null,
27
- createdAt: new Date(),
28
- updatedAt: new Date(),
29
- deletedAt: null,
30
- createdById: null,
31
- updatedById: null,
32
- deletedById: null,
33
- ...overrides
34
- };
35
- }
36
- function buildCompany(overrides = {}) {
37
- return {
38
- id: 'company-1',
39
- name: 'Acme Corp',
40
- slug: 'acme-corp',
41
- logoId: null,
42
- isActive: true,
43
- readOnly: false,
44
- address: null,
45
- phone: null,
46
- email: null,
47
- website: null,
48
- serial: null,
49
- settings: null,
50
- additionalFields: null,
51
- branches: [],
52
- ...overrides
53
- };
54
- }
55
- function buildBranch(overrides = {}) {
56
- return {
57
- id: 'branch-1',
58
- name: 'Main Branch',
59
- slug: 'main-branch',
60
- companyId: 'company-1',
61
- logoId: null,
62
- isActive: true,
63
- readOnly: false,
64
- address: null,
65
- phone: null,
66
- email: null,
67
- serial: null,
68
- additionalFields: null,
69
- parentId: null,
70
- parent: null,
71
- children: [],
72
- ...overrides
73
- };
74
- }
75
- describe('AuthenticationService', ()=>{
76
- let userRepo;
77
- let companyRepo;
78
- let branchRepo;
79
- let permissionRepo;
80
- let mockJwtService;
81
- let mockAuthConfig;
82
- let mockCacheManager;
83
- let mockDataSourceProvider;
84
- let mockSessionService;
85
- let mockAuthEmailService;
86
- let mockUserEnricher;
87
- let companyFeatureEnabled;
88
- let emailVerificationEnabled;
89
- let signUpEnabled;
90
- function buildService(overrides = {}) {
91
- return new AuthenticationService(mockJwtService, mockAuthConfig, 'cacheManager' in overrides ? overrides.cacheManager : mockCacheManager, 'dataSourceProvider' in overrides ? overrides.dataSourceProvider : mockDataSourceProvider, 'sessionService' in overrides ? overrides.sessionService : mockSessionService, 'authEmailService' in overrides ? overrides.authEmailService : mockAuthEmailService, 'userEnricher' in overrides ? overrides.userEnricher : mockUserEnricher, 'notificationAdapter' in overrides ? overrides.notificationAdapter : undefined);
92
- }
93
- beforeEach(()=>{
94
- jest.clearAllMocks();
95
- bcrypt.compare.mockResolvedValue(true);
96
- bcrypt.hash.mockResolvedValue('hashed-password');
97
- userRepo = createMockRepository();
98
- companyRepo = createMockRepository();
99
- branchRepo = createMockRepository();
100
- permissionRepo = createMockRepository();
101
- Object.assign(branchRepo.createQueryBuilder(), {
102
- leftJoinAndSelect: jest.fn().mockReturnThis()
103
- });
104
- companyFeatureEnabled = false;
105
- emailVerificationEnabled = false;
106
- signUpEnabled = true;
107
- mockJwtService = {
108
- sign: jest.fn().mockReturnValue('signed-token'),
109
- verify: jest.fn()
110
- };
111
- mockAuthConfig = {
112
- isCompanyFeatureEnabled: jest.fn().mockImplementation(()=>companyFeatureEnabled),
113
- isEmailVerificationEnabled: jest.fn().mockImplementation(()=>emailVerificationEnabled),
114
- isSignUpEnabled: jest.fn().mockImplementation(()=>signUpEnabled),
115
- getJwtSecret: jest.fn().mockReturnValue('jwt-secret'),
116
- getJwtExpiration: jest.fn().mockReturnValue('1h'),
117
- getRefreshTokenSecret: jest.fn().mockReturnValue('refresh-secret'),
118
- getRefreshTokenExpiration: jest.fn().mockReturnValue('7d')
119
- };
120
- mockCacheManager = {
121
- get: jest.fn(),
122
- set: jest.fn(),
123
- del: jest.fn()
124
- };
125
- mockDataSourceProvider = {
126
- isCompanyFeatureEnabled: jest.fn().mockImplementation(()=>companyFeatureEnabled),
127
- isEmailVerificationEnabled: jest.fn().mockImplementation(()=>emailVerificationEnabled),
128
- isSignUpEnabled: jest.fn().mockImplementation(()=>signUpEnabled),
129
- getRepository: jest.fn().mockImplementation(async (entity)=>{
130
- if (entity === AppUser) return userRepo;
131
- if (entity === Company) return companyRepo;
132
- if (entity === CompanyBranch) return branchRepo;
133
- if (entity === UserCompanyPermission) return permissionRepo;
134
- throw new Error(`Unexpected entity: ${String(entity)}`);
135
- }),
136
- getDataSource: jest.fn()
137
- };
138
- mockSessionService = {
139
- createSession: jest.fn().mockResolvedValue('session-1'),
140
- consumeSession: jest.fn()
141
- };
142
- mockAuthEmailService = {
143
- isEmailEnabled: jest.fn().mockReturnValue(true),
144
- hasPendingRegistration: jest.fn().mockResolvedValue(false),
145
- createPendingRegistration: jest.fn()
146
- };
147
- mockUserEnricher = {
148
- onUserCreated: jest.fn()
149
- };
150
- });
151
- describe('login', ()=>{
152
- it('throws UnauthorizedException for a non-existent user (invalid credentials)', async ()=>{
153
- userRepo.findOne.mockResolvedValue(null);
154
- const service = buildService();
155
- await expect(service.login('missing@example.com', 'password')).rejects.toThrow(UnauthorizedException);
156
- });
157
- it('throws UnauthorizedException when the password does not match', async ()=>{
158
- userRepo.findOne.mockResolvedValue(buildUser());
159
- bcrypt.compare.mockResolvedValue(false);
160
- const service = buildService();
161
- await expect(service.login('user@example.com', 'wrong-password')).rejects.toThrow(UnauthorizedException);
162
- });
163
- it('throws ForbiddenException when the account is deactivated', async ()=>{
164
- userRepo.findOne.mockResolvedValue(buildUser({
165
- isActive: false
166
- }));
167
- userRepo.save.mockResolvedValue(buildUser({
168
- isActive: false
169
- }));
170
- const service = buildService();
171
- await expect(service.login('user@example.com', 'password')).rejects.toThrow(ForbiddenException);
172
- });
173
- it('returns requiresEmailVerification when a pending registration exists for the email', async ()=>{
174
- emailVerificationEnabled = true;
175
- mockAuthEmailService.hasPendingRegistration.mockResolvedValue(true);
176
- const service = buildService();
177
- const result = await service.login('pending@example.com', 'password');
178
- expect(result).toEqual(expect.objectContaining({
179
- requiresEmailVerification: true,
180
- email: 'pending@example.com'
181
- }));
182
- expect(userRepo.findOne).not.toHaveBeenCalled();
183
- });
184
- it('returns requiresEmailVerification when the user has not verified their email', async ()=>{
185
- emailVerificationEnabled = true;
186
- userRepo.findOne.mockResolvedValue(buildUser({
187
- emailVerified: false
188
- }));
189
- userRepo.save.mockResolvedValue(buildUser({
190
- emailVerified: false
191
- }));
192
- const service = buildService();
193
- const result = await service.login('user@example.com', 'password');
194
- expect(result).toEqual(expect.objectContaining({
195
- requiresEmailVerification: true
196
- }));
197
- });
198
- it('logs in successfully without the company feature enabled', async ()=>{
199
- userRepo.findOne.mockResolvedValue(buildUser());
200
- userRepo.save.mockResolvedValue(buildUser());
201
- const service = buildService();
202
- const result = await service.login('user@example.com', 'password');
203
- expect(result).toEqual(expect.objectContaining({
204
- accessToken: 'signed-token',
205
- refreshToken: 'signed-token',
206
- user: expect.objectContaining({
207
- id: 'user-1'
208
- })
209
- }));
210
- expect(userRepo.save).toHaveBeenCalledWith(expect.objectContaining({
211
- lastLoginAt: expect.any(Date)
212
- }));
213
- });
214
- it('auto-logs in with company/branch when the user has exactly one of each', async ()=>{
215
- companyFeatureEnabled = true;
216
- userRepo.findOne.mockResolvedValue(buildUser());
217
- userRepo.save.mockResolvedValue(buildUser());
218
- permissionRepo.find.mockImplementation(async ({ where })=>{
219
- if (where.permissionType === PermissionType.COMPANY) {
220
- return [
221
- {
222
- targetId: 'company-1'
223
- }
224
- ];
225
- }
226
- return [
227
- {
228
- targetId: 'branch-1'
229
- }
230
- ];
231
- });
232
- companyRepo.createQueryBuilder().getMany.mockResolvedValue([
233
- buildCompany()
234
- ]);
235
- branchRepo.createQueryBuilder().getMany.mockResolvedValue([
236
- buildBranch()
237
- ]);
238
- const service = buildService();
239
- const result = await service.login('user@example.com', 'password');
240
- expect(result).toEqual(expect.objectContaining({
241
- company: expect.objectContaining({
242
- id: 'company-1'
243
- }),
244
- branch: expect.objectContaining({
245
- id: 'branch-1'
246
- })
247
- }));
248
- });
249
- it('returns a company selection response when the user has multiple companies', async ()=>{
250
- companyFeatureEnabled = true;
251
- userRepo.findOne.mockResolvedValue(buildUser());
252
- userRepo.save.mockResolvedValue(buildUser());
253
- permissionRepo.find.mockImplementation(async ({ where })=>{
254
- if (where.permissionType === PermissionType.COMPANY) {
255
- return [
256
- {
257
- targetId: 'company-1'
258
- },
259
- {
260
- targetId: 'company-2'
261
- }
262
- ];
263
- }
264
- return [];
265
- });
266
- companyRepo.createQueryBuilder().getMany.mockResolvedValue([
267
- buildCompany(),
268
- buildCompany({
269
- id: 'company-2'
270
- })
271
- ]);
272
- const service = buildService();
273
- const result = await service.login('user@example.com', 'password');
274
- expect(result).toEqual(expect.objectContaining({
275
- requiresSelection: true,
276
- sessionId: 'session-1'
277
- }));
278
- expect(mockSessionService.createSession).toHaveBeenCalledWith('user-1');
279
- });
280
- it('falls back to a plain login response when company feature is enabled but the user has no company', async ()=>{
281
- companyFeatureEnabled = true;
282
- userRepo.findOne.mockResolvedValue(buildUser());
283
- userRepo.save.mockResolvedValue(buildUser());
284
- permissionRepo.find.mockResolvedValue([]);
285
- const service = buildService();
286
- const result = await service.login('user@example.com', 'password');
287
- expect(result).toEqual(expect.objectContaining({
288
- accessToken: 'signed-token'
289
- }));
290
- expect(result.company).toBeUndefined();
291
- });
292
- });
293
- describe('register', ()=>{
294
- it('throws BadRequestException when the email exists and company feature is disabled', async ()=>{
295
- userRepo.findOne.mockResolvedValue(buildUser());
296
- const service = buildService();
297
- await expect(service.register({
298
- email: 'user@example.com',
299
- name: 'Test',
300
- password: 'Password1!'
301
- })).rejects.toThrow(BadRequestException);
302
- });
303
- it('throws BadRequestException when the email belongs to a permanently deleted account', async ()=>{
304
- userRepo.findOne.mockResolvedValue(buildUser({
305
- deletedAt: new Date()
306
- }));
307
- const service = buildService();
308
- await expect(service.register({
309
- email: 'user@example.com',
310
- name: 'Test',
311
- password: 'Password1!'
312
- })).rejects.toThrow(BadRequestException);
313
- expect(userRepo.findOne).toHaveBeenCalledWith(expect.objectContaining({
314
- withDeleted: true
315
- }));
316
- });
317
- it('routes existing users to company registration when the company feature is enabled', async ()=>{
318
- companyFeatureEnabled = true;
319
- userRepo.findOne.mockResolvedValue(buildUser());
320
- companyRepo.findOne.mockResolvedValue(null);
321
- companyRepo.createQueryBuilder().getMany.mockResolvedValue([]);
322
- companyRepo.create.mockReturnValue(buildCompany());
323
- companyRepo.save.mockResolvedValue(buildCompany());
324
- branchRepo.create.mockReturnValue(buildBranch());
325
- branchRepo.save.mockResolvedValue(buildBranch());
326
- permissionRepo.save.mockResolvedValue({});
327
- const service = buildService();
328
- const result = await service.register({
329
- email: 'user@example.com',
330
- name: 'Test',
331
- password: 'Password1!',
332
- newCompanyName: 'New Co'
333
- });
334
- expect(result).toEqual(expect.objectContaining({
335
- accessToken: expect.any(String)
336
- }));
337
- });
338
- it('throws BadRequestException for a new user when sign-up is disabled', async ()=>{
339
- signUpEnabled = false;
340
- userRepo.findOne.mockResolvedValue(null);
341
- const service = buildService();
342
- await expect(service.register({
343
- email: 'new@example.com',
344
- name: 'New User',
345
- password: 'Password1!'
346
- })).rejects.toThrow(BadRequestException);
347
- });
348
- it('sends a verification email and returns requiresEmailVerification when email verification is enabled', async ()=>{
349
- emailVerificationEnabled = true;
350
- userRepo.findOne.mockResolvedValue(null);
351
- mockAuthEmailService.createPendingRegistration.mockResolvedValue({
352
- success: true,
353
- message: 'sent',
354
- messageKey: 'email.verification.sent'
355
- });
356
- const service = buildService();
357
- const result = await service.register({
358
- email: 'new@example.com',
359
- name: 'New User',
360
- password: 'Password1!'
361
- }, 'https://app.test/verify');
362
- expect(result).toEqual(expect.objectContaining({
363
- requiresEmailVerification: true
364
- }));
365
- expect(mockAuthEmailService.createPendingRegistration).toHaveBeenCalled();
366
- });
367
- it('creates the user directly and hashes the password when email verification is not required', async ()=>{
368
- userRepo.findOne.mockResolvedValue(null);
369
- const queryRunner = {
370
- connect: jest.fn(),
371
- startTransaction: jest.fn(),
372
- commitTransaction: jest.fn(),
373
- rollbackTransaction: jest.fn(),
374
- release: jest.fn(),
375
- manager: {
376
- create: jest.fn().mockReturnValue(buildUser()),
377
- save: jest.fn().mockResolvedValue(buildUser())
378
- }
379
- };
380
- mockDataSourceProvider.getDataSource.mockResolvedValue({
381
- createQueryRunner: ()=>queryRunner
382
- });
383
- const service = buildService();
384
- const result = await service.register({
385
- email: 'new@example.com',
386
- name: 'New User',
387
- password: 'Password1!'
388
- });
389
- expect(bcrypt.hash).toHaveBeenCalledWith('Password1!', 12);
390
- expect(queryRunner.commitTransaction).toHaveBeenCalled();
391
- expect(result).toEqual(expect.objectContaining({
392
- accessToken: expect.any(String)
393
- }));
394
- });
395
- it('rolls back the transaction and rethrows a BadRequestException on failure', async ()=>{
396
- userRepo.findOne.mockResolvedValue(null);
397
- const queryRunner = {
398
- connect: jest.fn(),
399
- startTransaction: jest.fn(),
400
- commitTransaction: jest.fn(),
401
- rollbackTransaction: jest.fn(),
402
- release: jest.fn(),
403
- manager: {
404
- create: jest.fn().mockReturnValue(buildUser()),
405
- save: jest.fn().mockRejectedValue(new Error('db error'))
406
- }
407
- };
408
- mockDataSourceProvider.getDataSource.mockResolvedValue({
409
- createQueryRunner: ()=>queryRunner
410
- });
411
- const service = buildService();
412
- await expect(service.register({
413
- email: 'new@example.com',
414
- name: 'New',
415
- password: 'Password1!'
416
- })).rejects.toThrow(BadRequestException);
417
- expect(queryRunner.rollbackTransaction).toHaveBeenCalled();
418
- expect(queryRunner.release).toHaveBeenCalled();
419
- });
420
- });
421
- describe('refreshToken', ()=>{
422
- it('throws UnauthorizedException when the token is malformed/invalid', async ()=>{
423
- mockJwtService.verify.mockImplementation(()=>{
424
- throw new Error('invalid signature');
425
- });
426
- const service = buildService();
427
- await expect(service.refreshToken('bad-token')).rejects.toThrow(UnauthorizedException);
428
- });
429
- it('throws UnauthorizedException when the token has been revoked', async ()=>{
430
- mockJwtService.verify.mockReturnValue({
431
- id: 'user-1',
432
- iat: 1000
433
- });
434
- mockCacheManager.get.mockResolvedValue(2000);
435
- const service = buildService();
436
- await expect(service.refreshToken('revoked-token')).rejects.toThrow(UnauthorizedException);
437
- });
438
- it('throws UnauthorizedException when the user no longer exists or is inactive', async ()=>{
439
- mockJwtService.verify.mockReturnValue({
440
- id: 'user-1',
441
- iat: 1000
442
- });
443
- mockCacheManager.get.mockResolvedValue(undefined);
444
- userRepo.findOne.mockResolvedValue(null);
445
- const service = buildService();
446
- await expect(service.refreshToken('token')).rejects.toThrow(UnauthorizedException);
447
- });
448
- it('issues a new token pair for a valid non-company refresh token', async ()=>{
449
- mockJwtService.verify.mockReturnValue({
450
- id: 'user-1',
451
- iat: 1000
452
- });
453
- mockCacheManager.get.mockResolvedValue(undefined);
454
- userRepo.findOne.mockResolvedValue(buildUser());
455
- const service = buildService();
456
- const result = await service.refreshToken('token');
457
- expect(result).toEqual({
458
- accessToken: 'signed-token',
459
- refreshToken: 'signed-token'
460
- });
461
- });
462
- it('throws UnauthorizedException when the company from the payload no longer exists', async ()=>{
463
- mockJwtService.verify.mockReturnValue({
464
- id: 'user-1',
465
- iat: 1000,
466
- companyId: 'company-1'
467
- });
468
- mockCacheManager.get.mockResolvedValue(undefined);
469
- userRepo.findOne.mockResolvedValue(buildUser());
470
- companyFeatureEnabled = true;
471
- companyRepo.findOne.mockResolvedValue(null);
472
- const service = buildService();
473
- await expect(service.refreshToken('token')).rejects.toThrow(UnauthorizedException);
474
- });
475
- it('throws UnauthorizedException when the user no longer has access to the payload company', async ()=>{
476
- mockJwtService.verify.mockReturnValue({
477
- id: 'user-1',
478
- iat: 1000,
479
- companyId: 'company-1'
480
- });
481
- mockCacheManager.get.mockResolvedValue(undefined);
482
- userRepo.findOne.mockResolvedValue(buildUser());
483
- companyFeatureEnabled = true;
484
- companyRepo.findOne.mockResolvedValue(buildCompany());
485
- permissionRepo.findOne.mockResolvedValue(null);
486
- const service = buildService();
487
- await expect(service.refreshToken('token')).rejects.toThrow(UnauthorizedException);
488
- });
489
- it('validates branch access when a branchId is present in the payload', async ()=>{
490
- mockJwtService.verify.mockReturnValue({
491
- id: 'user-1',
492
- iat: 1000,
493
- companyId: 'company-1',
494
- branchId: 'branch-1'
495
- });
496
- mockCacheManager.get.mockResolvedValue(undefined);
497
- userRepo.findOne.mockResolvedValue(buildUser());
498
- companyFeatureEnabled = true;
499
- companyRepo.findOne.mockResolvedValue(buildCompany());
500
- permissionRepo.findOne.mockResolvedValue({});
501
- branchRepo.findOne.mockResolvedValue(null);
502
- const service = buildService();
503
- await expect(service.refreshToken('token')).rejects.toThrow(UnauthorizedException);
504
- });
505
- it('issues a new token pair when company and branch access is valid', async ()=>{
506
- mockJwtService.verify.mockReturnValue({
507
- id: 'user-1',
508
- iat: 1000,
509
- companyId: 'company-1',
510
- branchId: 'branch-1'
511
- });
512
- mockCacheManager.get.mockResolvedValue(undefined);
513
- userRepo.findOne.mockResolvedValue(buildUser());
514
- companyFeatureEnabled = true;
515
- companyRepo.findOne.mockResolvedValue(buildCompany());
516
- permissionRepo.findOne.mockResolvedValue({});
517
- branchRepo.findOne.mockResolvedValue(buildBranch());
518
- const service = buildService();
519
- const result = await service.refreshToken('token');
520
- expect(result).toEqual({
521
- accessToken: 'signed-token',
522
- refreshToken: 'signed-token'
523
- });
524
- });
525
- });
526
- describe('changePassword', ()=>{
527
- it('throws UnauthorizedException when the user does not exist', async ()=>{
528
- userRepo.findOne.mockResolvedValue(null);
529
- const service = buildService();
530
- await expect(service.changePassword('user-1', 'old', 'NewPass1!')).rejects.toThrow(UnauthorizedException);
531
- });
532
- it('throws UnauthorizedException when the current password is incorrect', async ()=>{
533
- userRepo.findOne.mockResolvedValue(buildUser());
534
- bcrypt.compare.mockResolvedValue(false);
535
- const service = buildService();
536
- await expect(service.changePassword('user-1', 'wrong', 'NewPass1!')).rejects.toThrow(UnauthorizedException);
537
- });
538
- it('hashes and saves the new password on success', async ()=>{
539
- userRepo.findOne.mockResolvedValue(buildUser());
540
- userRepo.save.mockResolvedValue(buildUser());
541
- const service = buildService();
542
- await service.changePassword('user-1', 'old', 'NewPass1!');
543
- expect(bcrypt.hash).toHaveBeenCalledWith('NewPass1!', 12);
544
- expect(userRepo.save).toHaveBeenCalledWith(expect.objectContaining({
545
- password: 'hashed-password'
546
- }));
547
- });
548
- });
549
- describe('logout', ()=>{
550
- it('throws BadRequestException when the cache manager is unavailable', async ()=>{
551
- const service = buildService({
552
- cacheManager: undefined
553
- });
554
- await expect(service.logout('user-1')).rejects.toThrow(BadRequestException);
555
- });
556
- it('records the revocation timestamp in the cache', async ()=>{
557
- const service = buildService();
558
- await service.logout('user-1');
559
- expect(mockCacheManager.set).toHaveBeenCalledWith('auth:revoked:user-1', expect.any(Number), expect.any(Number));
560
- });
561
- });
562
- describe('isTokenRevoked', ()=>{
563
- it('returns false when there is no cache manager', async ()=>{
564
- const service = buildService({
565
- cacheManager: undefined
566
- });
567
- expect(await service.isTokenRevoked('user-1', 1000)).toBe(false);
568
- });
569
- it('returns false when tokenIssuedAt is not provided', async ()=>{
570
- const service = buildService();
571
- expect(await service.isTokenRevoked('user-1')).toBe(false);
572
- });
573
- it('returns false when nothing has been revoked', async ()=>{
574
- mockCacheManager.get.mockResolvedValue(undefined);
575
- const service = buildService();
576
- expect(await service.isTokenRevoked('user-1', 1000)).toBe(false);
577
- });
578
- it('returns true when the token was issued before the revocation time', async ()=>{
579
- mockCacheManager.get.mockResolvedValue(2000);
580
- const service = buildService();
581
- expect(await service.isTokenRevoked('user-1', 1000)).toBe(true);
582
- });
583
- it('returns false when the token was issued after the revocation time', async ()=>{
584
- mockCacheManager.get.mockResolvedValue(500);
585
- const service = buildService();
586
- expect(await service.isTokenRevoked('user-1', 1000)).toBe(false);
587
- });
588
- });
589
- describe('getUserCompanies / getUserBranches', ()=>{
590
- it('throws BadRequestException when the company feature is disabled', async ()=>{
591
- const service = buildService();
592
- await expect(service.getUserCompanies('user-1')).rejects.toThrow(BadRequestException);
593
- });
594
- it('returns an empty array when the user has no company permissions', async ()=>{
595
- companyFeatureEnabled = true;
596
- permissionRepo.find.mockResolvedValue([]);
597
- const service = buildService();
598
- expect(await service.getUserCompanies('user-1')).toEqual([]);
599
- });
600
- it('returns companies the user has access to', async ()=>{
601
- companyFeatureEnabled = true;
602
- permissionRepo.find.mockResolvedValue([
603
- {
604
- targetId: 'company-1'
605
- }
606
- ]);
607
- companyRepo.createQueryBuilder().getMany.mockResolvedValue([
608
- buildCompany()
609
- ]);
610
- const service = buildService();
611
- const result = await service.getUserCompanies('user-1');
612
- expect(result).toEqual([
613
- buildCompany()
614
- ]);
615
- });
616
- it('throws UnauthorizedException from getUserBranches when the user lacks company access', async ()=>{
617
- companyFeatureEnabled = true;
618
- permissionRepo.findOne.mockResolvedValue(null);
619
- const service = buildService();
620
- await expect(service.getUserBranches('user-1', 'company-1')).rejects.toThrow(UnauthorizedException);
621
- });
622
- it('returns branches the user has access to within the company', async ()=>{
623
- companyFeatureEnabled = true;
624
- permissionRepo.findOne.mockResolvedValue({});
625
- permissionRepo.find.mockResolvedValue([
626
- {
627
- targetId: 'branch-1'
628
- }
629
- ]);
630
- branchRepo.createQueryBuilder().getMany.mockResolvedValue([
631
- buildBranch()
632
- ]);
633
- const service = buildService();
634
- const result = await service.getUserBranches('user-1', 'company-1');
635
- expect(result).toEqual([
636
- buildBranch()
637
- ]);
638
- });
639
- });
640
- describe('getCompanyById / getBranchById', ()=>{
641
- it('getCompanyById returns null when the company feature is disabled (scoped repo unavailable)', async ()=>{
642
- companyFeatureEnabled = false;
643
- const service = buildService();
644
- expect(await service.getCompanyById('company-1')).toBeNull();
645
- expect(companyRepo.findOne).not.toHaveBeenCalled();
646
- });
647
- it('getCompanyById returns the company by id when found', async ()=>{
648
- companyFeatureEnabled = true;
649
- companyRepo.findOne.mockResolvedValue(buildCompany());
650
- const service = buildService();
651
- const result = await service.getCompanyById('company-1');
652
- expect(companyRepo.findOne).toHaveBeenCalledWith({
653
- where: {
654
- id: 'company-1'
655
- }
656
- });
657
- expect(result).toEqual(buildCompany());
658
- });
659
- it('getCompanyById returns null when no company matches', async ()=>{
660
- companyFeatureEnabled = true;
661
- companyRepo.findOne.mockResolvedValue(null);
662
- const service = buildService();
663
- expect(await service.getCompanyById('missing')).toBeNull();
664
- });
665
- it('getBranchById returns null when the company feature is disabled (scoped repo unavailable)', async ()=>{
666
- companyFeatureEnabled = false;
667
- const service = buildService();
668
- expect(await service.getBranchById('branch-1')).toBeNull();
669
- expect(branchRepo.findOne).not.toHaveBeenCalled();
670
- });
671
- it('getBranchById returns the branch by id when found', async ()=>{
672
- companyFeatureEnabled = true;
673
- branchRepo.findOne.mockResolvedValue(buildBranch());
674
- const service = buildService();
675
- const result = await service.getBranchById('branch-1');
676
- expect(branchRepo.findOne).toHaveBeenCalledWith({
677
- where: {
678
- id: 'branch-1'
679
- }
680
- });
681
- expect(result).toEqual(buildBranch());
682
- });
683
- });
684
- describe('select', ()=>{
685
- it('throws BadRequestException when the company feature is disabled', async ()=>{
686
- const service = buildService();
687
- await expect(service.select('session-1', 'company-1', 'branch-1')).rejects.toThrow(BadRequestException);
688
- });
689
- it('throws UnauthorizedException when the session is invalid or expired', async ()=>{
690
- companyFeatureEnabled = true;
691
- mockSessionService.consumeSession.mockResolvedValue(null);
692
- const service = buildService();
693
- await expect(service.select('bad-session', 'company-1', 'branch-1')).rejects.toThrow(UnauthorizedException);
694
- });
695
- it('logs in with the selected company/branch when the session is valid', async ()=>{
696
- companyFeatureEnabled = true;
697
- mockSessionService.consumeSession.mockResolvedValue({
698
- sessionId: 'session-1',
699
- userId: 'user-1',
700
- createdAt: new Date(),
701
- expiresAt: new Date()
702
- });
703
- userRepo.findOne.mockResolvedValue(buildUser());
704
- permissionRepo.findOne.mockResolvedValue({});
705
- companyRepo.findOne.mockResolvedValue(buildCompany());
706
- branchRepo.findOne.mockResolvedValue(buildBranch());
707
- const service = buildService();
708
- const result = await service.select('session-1', 'company-1', 'branch-1');
709
- expect(result).toEqual(expect.objectContaining({
710
- accessToken: 'signed-token'
711
- }));
712
- });
713
- });
714
- describe('switchCompany / validateAndLoginWithCompany', ()=>{
715
- it('throws NotFoundException when the user does not exist', async ()=>{
716
- companyFeatureEnabled = true;
717
- userRepo.findOne.mockResolvedValue(null);
718
- const service = buildService();
719
- await expect(service.switchCompany('user-1', 'company-1', 'branch-1')).rejects.toThrow(NotFoundException);
720
- });
721
- it('throws ForbiddenException when the user has no access to the company', async ()=>{
722
- companyFeatureEnabled = true;
723
- userRepo.findOne.mockResolvedValue(buildUser());
724
- permissionRepo.findOne.mockResolvedValue(null);
725
- const service = buildService();
726
- await expect(service.switchCompany('user-1', 'company-1', 'branch-1')).rejects.toThrow(ForbiddenException);
727
- });
728
- it('throws NotFoundException when the company is inactive or missing', async ()=>{
729
- companyFeatureEnabled = true;
730
- userRepo.findOne.mockResolvedValue(buildUser());
731
- permissionRepo.findOne.mockResolvedValueOnce({}).mockResolvedValueOnce(null);
732
- companyRepo.findOne.mockResolvedValue(null);
733
- const service = buildService();
734
- await expect(service.switchCompany('user-1', 'company-1', 'branch-1')).rejects.toThrow(NotFoundException);
735
- });
736
- it('throws ForbiddenException when the user has no access to the branch', async ()=>{
737
- companyFeatureEnabled = true;
738
- userRepo.findOne.mockResolvedValue(buildUser());
739
- companyRepo.findOne.mockResolvedValue(buildCompany());
740
- permissionRepo.findOne.mockResolvedValueOnce({}).mockResolvedValueOnce(null);
741
- const service = buildService();
742
- await expect(service.switchCompany('user-1', 'company-1', 'branch-1')).rejects.toThrow(ForbiddenException);
743
- });
744
- it('throws NotFoundException when the branch is inactive or missing', async ()=>{
745
- companyFeatureEnabled = true;
746
- userRepo.findOne.mockResolvedValue(buildUser());
747
- companyRepo.findOne.mockResolvedValue(buildCompany());
748
- permissionRepo.findOne.mockResolvedValue({});
749
- branchRepo.findOne.mockResolvedValue(null);
750
- const service = buildService();
751
- await expect(service.switchCompany('user-1', 'company-1', 'branch-1')).rejects.toThrow(NotFoundException);
752
- });
753
- it('returns a new login response when switching succeeds', async ()=>{
754
- companyFeatureEnabled = true;
755
- userRepo.findOne.mockResolvedValue(buildUser());
756
- companyRepo.findOne.mockResolvedValue(buildCompany());
757
- permissionRepo.findOne.mockResolvedValue({});
758
- branchRepo.findOne.mockResolvedValue(buildBranch());
759
- const service = buildService();
760
- const result = await service.switchCompany('user-1', 'company-1', 'branch-1');
761
- expect(result).toEqual(expect.objectContaining({
762
- accessToken: 'signed-token',
763
- company: expect.objectContaining({
764
- id: 'company-1'
765
- }),
766
- branch: expect.objectContaining({
767
- id: 'branch-1'
768
- })
769
- }));
770
- });
771
- });
772
- describe('getUserInfo', ()=>{
773
- it('throws UnauthorizedException when the user does not exist', async ()=>{
774
- userRepo.findOne.mockResolvedValue(null);
775
- const service = buildService();
776
- await expect(service.getUserInfo('user-1')).rejects.toThrow(UnauthorizedException);
777
- });
778
- it('returns only user info when the company feature is disabled', async ()=>{
779
- userRepo.findOne.mockResolvedValue(buildUser());
780
- const service = buildService();
781
- const result = await service.getUserInfo('user-1');
782
- expect(result).toEqual({
783
- user: expect.objectContaining({
784
- id: 'user-1'
785
- })
786
- });
787
- });
788
- it('throws UnauthorizedException when the company feature is enabled but no companyId is given', async ()=>{
789
- companyFeatureEnabled = true;
790
- userRepo.findOne.mockResolvedValue(buildUser());
791
- const service = buildService();
792
- await expect(service.getUserInfo('user-1')).rejects.toThrow(UnauthorizedException);
793
- });
794
- it('throws UnauthorizedException when the company cannot be found', async ()=>{
795
- companyFeatureEnabled = true;
796
- userRepo.findOne.mockResolvedValue(buildUser());
797
- companyRepo.findOne.mockResolvedValue(null);
798
- const service = buildService();
799
- await expect(service.getUserInfo('user-1', 'company-1')).rejects.toThrow(UnauthorizedException);
800
- });
801
- it('throws UnauthorizedException when the branch cannot be found', async ()=>{
802
- companyFeatureEnabled = true;
803
- userRepo.findOne.mockResolvedValue(buildUser());
804
- companyRepo.findOne.mockResolvedValue(buildCompany());
805
- branchRepo.findOne.mockResolvedValue(null);
806
- const service = buildService();
807
- await expect(service.getUserInfo('user-1', 'company-1', 'branch-1')).rejects.toThrow(UnauthorizedException);
808
- });
809
- it('returns user, company, and branch info when everything resolves', async ()=>{
810
- companyFeatureEnabled = true;
811
- userRepo.findOne.mockResolvedValue(buildUser());
812
- companyRepo.findOne.mockResolvedValue(buildCompany());
813
- branchRepo.findOne.mockResolvedValue(buildBranch());
814
- const service = buildService();
815
- const result = await service.getUserInfo('user-1', 'company-1', 'branch-1');
816
- expect(result).toEqual({
817
- user: expect.objectContaining({
818
- id: 'user-1'
819
- }),
820
- company: expect.objectContaining({
821
- id: 'company-1'
822
- }),
823
- branch: expect.objectContaining({
824
- id: 'branch-1'
825
- })
826
- });
827
- });
828
- });
829
- describe('createUserFromPendingRegistration', ()=>{
830
- it('throws BadRequestException when the email is already registered', async ()=>{
831
- const queryRunner = {
832
- connect: jest.fn(),
833
- startTransaction: jest.fn(),
834
- commitTransaction: jest.fn(),
835
- rollbackTransaction: jest.fn(),
836
- release: jest.fn(),
837
- manager: {
838
- findOne: jest.fn().mockResolvedValue(buildUser()),
839
- create: jest.fn(),
840
- save: jest.fn()
841
- }
842
- };
843
- mockDataSourceProvider.getDataSource.mockResolvedValue({
844
- createQueryRunner: ()=>queryRunner
845
- });
846
- const service = buildService();
847
- await expect(service.createUserFromPendingRegistration({
848
- email: 'user@example.com',
849
- name: 'Test',
850
- passwordHash: 'hash'
851
- })).rejects.toThrow(BadRequestException);
852
- expect(queryRunner.rollbackTransaction).toHaveBeenCalled();
853
- });
854
- it('throws BadRequestException when the email belongs to a permanently deleted account', async ()=>{
855
- const queryRunner = {
856
- connect: jest.fn(),
857
- startTransaction: jest.fn(),
858
- commitTransaction: jest.fn(),
859
- rollbackTransaction: jest.fn(),
860
- release: jest.fn(),
861
- manager: {
862
- findOne: jest.fn().mockResolvedValue(buildUser({
863
- deletedAt: new Date()
864
- })),
865
- create: jest.fn(),
866
- save: jest.fn()
867
- }
868
- };
869
- mockDataSourceProvider.getDataSource.mockResolvedValue({
870
- createQueryRunner: ()=>queryRunner
871
- });
872
- const service = buildService();
873
- await expect(service.createUserFromPendingRegistration({
874
- email: 'user@example.com',
875
- name: 'Test',
876
- passwordHash: 'hash'
877
- })).rejects.toThrow(BadRequestException);
878
- expect(queryRunner.manager.findOne).toHaveBeenCalledWith(AppUser, expect.objectContaining({
879
- withDeleted: true
880
- }));
881
- expect(queryRunner.manager.create).not.toHaveBeenCalled();
882
- expect(queryRunner.rollbackTransaction).toHaveBeenCalled();
883
- });
884
- it('creates the user with the email marked as verified', async ()=>{
885
- const queryRunner = {
886
- connect: jest.fn(),
887
- startTransaction: jest.fn(),
888
- commitTransaction: jest.fn(),
889
- rollbackTransaction: jest.fn(),
890
- release: jest.fn(),
891
- manager: {
892
- findOne: jest.fn().mockResolvedValue(null),
893
- create: jest.fn().mockReturnValue(buildUser({
894
- emailVerified: true
895
- })),
896
- save: jest.fn().mockResolvedValue(buildUser({
897
- emailVerified: true
898
- }))
899
- }
900
- };
901
- mockDataSourceProvider.getDataSource.mockResolvedValue({
902
- createQueryRunner: ()=>queryRunner
903
- });
904
- const service = buildService();
905
- const result = await service.createUserFromPendingRegistration({
906
- email: 'new@example.com',
907
- name: 'New User',
908
- passwordHash: 'hash'
909
- });
910
- expect(queryRunner.manager.create).toHaveBeenCalledWith(AppUser, expect.objectContaining({
911
- emailVerified: true
912
- }));
913
- expect(result).toEqual(expect.objectContaining({
914
- accessToken: expect.any(String)
915
- }));
916
- });
917
- });
918
- describe('domain events', ()=>{
919
- let publish;
920
- beforeEach(()=>{
921
- publish = jest.fn().mockResolvedValue(undefined);
922
- EventBusRegistry.reset();
923
- EventBusRegistry.setBus({
924
- publish,
925
- subscribe: jest.fn(),
926
- close: jest.fn()
927
- });
928
- EventBusRegistry.configureModule('auth', {
929
- enabled: true
930
- });
931
- });
932
- afterEach(()=>{
933
- EventBusRegistry.reset();
934
- });
935
- it('publishes auth.session.logged-in when a session is issued', async ()=>{
936
- userRepo.findOne.mockResolvedValue(buildUser());
937
- bcrypt.compare.mockResolvedValue(true);
938
- const service = buildService();
939
- await service.login('user@example.com', 'password');
940
- expect(publish).toHaveBeenCalledWith(expect.objectContaining({
941
- name: 'auth.session.logged-in',
942
- action: 'logged-in',
943
- payload: expect.objectContaining({
944
- ids: [
945
- 'user-1'
946
- ]
947
- })
948
- }));
949
- });
950
- it('publishes auth.session.logged-out on logout', async ()=>{
951
- const service = buildService();
952
- await service.logout('user-1');
953
- expect(publish).toHaveBeenCalledWith(expect.objectContaining({
954
- name: 'auth.session.logged-out'
955
- }));
956
- });
957
- it('publishes auth.appuser.password-changed after a successful password change', async ()=>{
958
- userRepo.findOne.mockResolvedValue(buildUser());
959
- bcrypt.compare.mockResolvedValue(true);
960
- const service = buildService();
961
- await service.changePassword('user-1', 'old', 'new');
962
- expect(publish).toHaveBeenCalledWith(expect.objectContaining({
963
- name: 'auth.appuser.password-changed'
964
- }));
965
- });
966
- it('does not publish when the auth module has events disabled', async ()=>{
967
- EventBusRegistry.configureModule('auth', {
968
- enabled: false
969
- });
970
- const service = buildService();
971
- await service.logout('user-1');
972
- expect(publish).not.toHaveBeenCalled();
973
- });
974
- });
975
- });