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