@flusys/nestjs-auth 6.0.2 → 6.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) 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/index.spec.js +73 -0
  10. package/cjs/helpers/auth-response.mapper.js +46 -0
  11. package/cjs/helpers/auth-response.mapper.spec.js +139 -0
  12. package/cjs/helpers/index.js +19 -0
  13. package/cjs/helpers/token.helper.js +58 -0
  14. package/cjs/helpers/token.helper.spec.js +86 -0
  15. package/cjs/index.js +1 -0
  16. package/cjs/interceptors/clear-token.interceptor.spec.js +107 -0
  17. package/cjs/interceptors/set-token.interceptor.spec.js +165 -0
  18. package/cjs/modules/auth.module.spec.js +243 -0
  19. package/cjs/services/auth-config.service.spec.js +97 -0
  20. package/cjs/services/auth-datasource.provider.spec.js +161 -0
  21. package/cjs/services/auth-email.service.spec.js +404 -0
  22. package/cjs/services/authentication.service.js +37 -109
  23. package/cjs/services/authentication.service.spec.js +904 -0
  24. package/cjs/services/branch.service.spec.js +154 -0
  25. package/cjs/services/company-selection-session.service.spec.js +90 -0
  26. package/cjs/services/company.service.spec.js +113 -0
  27. package/cjs/services/user-permission.service.spec.js +202 -0
  28. package/cjs/services/user.service.spec.js +704 -0
  29. package/cjs/strategies/jwt.strategy.js +1 -1
  30. package/cjs/strategies/jwt.strategy.spec.js +166 -0
  31. package/cjs/validators/password.validator.spec.js +161 -0
  32. package/entities/pending-registration.entity.d.ts +2 -7
  33. package/fesm/controllers/authentication.controller.spec.js +215 -0
  34. package/fesm/controllers/branch.controller.spec.js +130 -0
  35. package/fesm/controllers/company-selection.controller.spec.js +80 -0
  36. package/fesm/controllers/company.controller.spec.js +127 -0
  37. package/fesm/controllers/email-verification.controller.spec.js +138 -0
  38. package/fesm/controllers/user-permission.controller.spec.js +134 -0
  39. package/fesm/controllers/user.controller.spec.js +200 -0
  40. package/fesm/docs/auth-swagger.config.spec.js +126 -0
  41. package/fesm/entities/index.spec.js +69 -0
  42. package/fesm/helpers/auth-response.mapper.js +25 -0
  43. package/fesm/helpers/auth-response.mapper.spec.js +135 -0
  44. package/fesm/helpers/index.js +2 -0
  45. package/fesm/helpers/token.helper.js +40 -0
  46. package/fesm/helpers/token.helper.spec.js +82 -0
  47. package/fesm/index.js +1 -0
  48. package/fesm/interceptors/clear-token.interceptor.spec.js +103 -0
  49. package/fesm/interceptors/set-token.interceptor.spec.js +161 -0
  50. package/fesm/interfaces/authentication.interface.js +1 -1
  51. package/fesm/modules/auth.module.spec.js +239 -0
  52. package/fesm/services/auth-config.service.spec.js +93 -0
  53. package/fesm/services/auth-datasource.provider.spec.js +157 -0
  54. package/fesm/services/auth-email.service.spec.js +359 -0
  55. package/fesm/services/authentication.service.js +37 -109
  56. package/fesm/services/authentication.service.spec.js +859 -0
  57. package/fesm/services/branch.service.spec.js +150 -0
  58. package/fesm/services/company-selection-session.service.spec.js +86 -0
  59. package/fesm/services/company.service.spec.js +109 -0
  60. package/fesm/services/user-permission.service.spec.js +198 -0
  61. package/fesm/services/user.service.spec.js +659 -0
  62. package/fesm/strategies/jwt.strategy.js +1 -1
  63. package/fesm/strategies/jwt.strategy.spec.js +162 -0
  64. package/fesm/validators/password.validator.spec.js +157 -0
  65. package/helpers/auth-response.mapper.d.ts +22 -0
  66. package/helpers/index.d.ts +2 -0
  67. package/helpers/token.helper.d.ts +8 -0
  68. package/index.d.ts +1 -0
  69. package/interfaces/authentication.interface.d.ts +7 -0
  70. package/package.json +8 -3
  71. package/services/authentication.service.d.ts +1 -8
@@ -0,0 +1,157 @@
1
+ import { MultiTenantDataSourceService } from '@flusys/nestjs-shared';
2
+ import { AuthDataSourceProvider } from './auth-datasource.provider';
3
+ function buildOptions(overrides = {}) {
4
+ return {
5
+ global: false,
6
+ includeController: true,
7
+ bootstrapAppConfig: {
8
+ databaseMode: 'single',
9
+ enableCompanyFeature: false,
10
+ enableEmailVerification: true
11
+ },
12
+ ...overrides
13
+ };
14
+ }
15
+ describe('AuthDataSourceProvider', ()=>{
16
+ afterEach(()=>{
17
+ jest.restoreAllMocks();
18
+ });
19
+ describe('isCompanyFeatureEnabled', ()=>{
20
+ it('returns false by default when bootstrap config disables it', ()=>{
21
+ const provider = new AuthDataSourceProvider(buildOptions());
22
+ expect(provider.isCompanyFeatureEnabled()).toBe(false);
23
+ });
24
+ it('returns true when bootstrap config enables it', ()=>{
25
+ const provider = new AuthDataSourceProvider(buildOptions({
26
+ bootstrapAppConfig: {
27
+ databaseMode: 'single',
28
+ enableCompanyFeature: true
29
+ }
30
+ }));
31
+ expect(provider.isCompanyFeatureEnabled()).toBe(true);
32
+ });
33
+ it('prefers the tenant override over bootstrap config', ()=>{
34
+ const provider = new AuthDataSourceProvider(buildOptions({
35
+ bootstrapAppConfig: {
36
+ databaseMode: 'multi-tenant',
37
+ enableCompanyFeature: false
38
+ }
39
+ }));
40
+ expect(provider.isCompanyFeatureEnabled({
41
+ enableCompanyFeature: true
42
+ })).toBe(true);
43
+ });
44
+ it('defaults to false when no bootstrap config and no tenant override is present', ()=>{
45
+ const provider = new AuthDataSourceProvider(buildOptions({
46
+ bootstrapAppConfig: undefined
47
+ }));
48
+ expect(provider.isCompanyFeatureEnabled()).toBe(false);
49
+ });
50
+ });
51
+ describe('isEmailVerificationEnabled', ()=>{
52
+ it('returns true by default (feature defaults to enabled)', ()=>{
53
+ const provider = new AuthDataSourceProvider(buildOptions({
54
+ bootstrapAppConfig: undefined
55
+ }));
56
+ expect(provider.isEmailVerificationEnabled()).toBe(true);
57
+ });
58
+ it('returns false when bootstrap config disables it', ()=>{
59
+ const provider = new AuthDataSourceProvider(buildOptions({
60
+ bootstrapAppConfig: {
61
+ databaseMode: 'single',
62
+ enableCompanyFeature: false,
63
+ enableEmailVerification: false
64
+ }
65
+ }));
66
+ expect(provider.isEmailVerificationEnabled()).toBe(false);
67
+ });
68
+ it('prefers the tenant override over bootstrap config', ()=>{
69
+ const provider = new AuthDataSourceProvider(buildOptions({
70
+ bootstrapAppConfig: {
71
+ databaseMode: 'multi-tenant',
72
+ enableCompanyFeature: true,
73
+ enableEmailVerification: true
74
+ }
75
+ }));
76
+ expect(provider.isEmailVerificationEnabled({
77
+ enableEmailVerification: false
78
+ })).toBe(false);
79
+ });
80
+ });
81
+ describe('getAuthEntities', ()=>{
82
+ it('returns only base entities when company feature and email verification are disabled', async ()=>{
83
+ const provider = new AuthDataSourceProvider(buildOptions({
84
+ bootstrapAppConfig: {
85
+ databaseMode: 'single',
86
+ enableCompanyFeature: false,
87
+ enableEmailVerification: false
88
+ }
89
+ }));
90
+ const entities = await provider.getAuthEntities();
91
+ const names = entities.map((e)=>e.name);
92
+ expect(names).toEqual(expect.arrayContaining([
93
+ 'AppUser',
94
+ 'UserToken'
95
+ ]));
96
+ expect(names).not.toContain('Company');
97
+ expect(names).not.toContain('PendingRegistration');
98
+ });
99
+ it('includes company entities when company feature is enabled', async ()=>{
100
+ const provider = new AuthDataSourceProvider(buildOptions({
101
+ bootstrapAppConfig: {
102
+ databaseMode: 'single',
103
+ enableCompanyFeature: true,
104
+ enableEmailVerification: false
105
+ }
106
+ }));
107
+ const entities = await provider.getAuthEntities();
108
+ const names = entities.map((e)=>e.name);
109
+ expect(names).toEqual(expect.arrayContaining([
110
+ 'AppUser',
111
+ 'UserToken',
112
+ 'Company',
113
+ 'CompanyBranch',
114
+ 'UserCompanyPermission'
115
+ ]));
116
+ });
117
+ it('includes pending registration entity when email verification is enabled', async ()=>{
118
+ const provider = new AuthDataSourceProvider(buildOptions({
119
+ bootstrapAppConfig: {
120
+ databaseMode: 'single',
121
+ enableCompanyFeature: false,
122
+ enableEmailVerification: true
123
+ }
124
+ }));
125
+ const entities = await provider.getAuthEntities();
126
+ const names = entities.map((e)=>e.name);
127
+ expect(names).toContain('PendingRegistration');
128
+ });
129
+ });
130
+ describe('createDataSourceFromConfig', ()=>{
131
+ it('forwards the config and resolved auth entities to the parent implementation', async ()=>{
132
+ const fakeDataSource = {
133
+ isInitialized: true
134
+ };
135
+ const parentSpy = jest.spyOn(MultiTenantDataSourceService.prototype, 'createDataSourceFromConfig').mockResolvedValue(fakeDataSource);
136
+ const provider = new AuthDataSourceProvider(buildOptions({
137
+ bootstrapAppConfig: {
138
+ databaseMode: 'single',
139
+ enableCompanyFeature: true,
140
+ enableEmailVerification: true
141
+ }
142
+ }));
143
+ const config = {
144
+ type: 'postgres',
145
+ host: 'localhost'
146
+ };
147
+ const result = await provider.createDataSourceFromConfig(config);
148
+ expect(result).toBe(fakeDataSource);
149
+ expect(parentSpy).toHaveBeenCalledWith(config, expect.any(Array));
150
+ const forwardedEntityNames = parentSpy.mock.calls[0][1].map((e)=>e.name);
151
+ expect(forwardedEntityNames).toEqual(expect.arrayContaining([
152
+ 'AppUser',
153
+ 'Company'
154
+ ]));
155
+ });
156
+ });
157
+ });
@@ -0,0 +1,359 @@
1
+ import { BadRequestException, InternalServerErrorException } from '@nestjs/common';
2
+ import * as bcrypt from 'bcrypt';
3
+ import { createMockDataSourceProvider, createMockRepository } from '@test-utils/mocks/repository.mock';
4
+ import { AuthEmailService } from './auth-email.service';
5
+ import { AppUser } from '../entities/app-user.entity';
6
+ import { PendingRegistration } from '../entities/pending-registration.entity';
7
+ import { TokenType, UserToken } from '../entities/user-token.entity';
8
+ jest.mock('bcrypt', ()=>({
9
+ hash: jest.fn().mockResolvedValue('hashed-password')
10
+ }));
11
+ function buildUser(overrides = {}) {
12
+ return {
13
+ id: 'user-1',
14
+ email: 'user@example.com',
15
+ isActive: true,
16
+ emailVerified: false,
17
+ password: 'hashed',
18
+ ...overrides
19
+ };
20
+ }
21
+ function buildUserToken(overrides = {}) {
22
+ return {
23
+ id: 'token-1',
24
+ userId: 'user-1',
25
+ type: TokenType.PASSWORD_RESET,
26
+ token: 'hashed-token',
27
+ expiresAt: new Date(Date.now() + 60_000),
28
+ usedAt: null,
29
+ createdAt: new Date(),
30
+ ...overrides
31
+ };
32
+ }
33
+ describe('AuthEmailService', ()=>{
34
+ let service;
35
+ let userRepo;
36
+ let pendingRepo;
37
+ let tokenRepo;
38
+ let mockEmailProvider;
39
+ beforeEach(()=>{
40
+ userRepo = createMockRepository();
41
+ pendingRepo = createMockRepository();
42
+ tokenRepo = createMockRepository();
43
+ const dataSourceProvider = {
44
+ getRepository: jest.fn().mockImplementation(async (entity)=>{
45
+ if (entity === AppUser) return userRepo;
46
+ if (entity === PendingRegistration) return pendingRepo;
47
+ if (entity === UserToken) return tokenRepo;
48
+ throw new Error(`Unexpected entity requested: ${String(entity)}`);
49
+ }),
50
+ getDataSource: jest.fn()
51
+ };
52
+ mockEmailProvider = {
53
+ sendPasswordResetEmail: jest.fn().mockResolvedValue(undefined),
54
+ sendVerificationEmail: jest.fn().mockResolvedValue(undefined)
55
+ };
56
+ service = new AuthEmailService(dataSourceProvider, mockEmailProvider);
57
+ });
58
+ afterEach(()=>jest.clearAllMocks());
59
+ describe('isEmailEnabled', ()=>{
60
+ it('returns true when an email provider is configured', ()=>{
61
+ expect(service.isEmailEnabled()).toBe(true);
62
+ });
63
+ it('returns false when no email provider is configured', ()=>{
64
+ const noEmailService = new AuthEmailService(createMockDataSourceProvider(userRepo), undefined);
65
+ expect(noEmailService.isEmailEnabled()).toBe(false);
66
+ });
67
+ });
68
+ describe('hasPendingRegistration', ()=>{
69
+ it('returns false when email is disabled without querying', async ()=>{
70
+ const noEmailService = new AuthEmailService(createMockDataSourceProvider(pendingRepo), undefined);
71
+ const result = await noEmailService.hasPendingRegistration('user@example.com');
72
+ expect(result).toBe(false);
73
+ });
74
+ it('returns true when a non-expired pending registration exists', async ()=>{
75
+ pendingRepo.findOne.mockResolvedValue({
76
+ expiresAt: new Date(Date.now() + 60_000)
77
+ });
78
+ const result = await service.hasPendingRegistration('user@example.com');
79
+ expect(result).toBe(true);
80
+ });
81
+ it('returns false when the pending registration has expired', async ()=>{
82
+ pendingRepo.findOne.mockResolvedValue({
83
+ expiresAt: new Date(Date.now() - 60_000)
84
+ });
85
+ const result = await service.hasPendingRegistration('user@example.com');
86
+ expect(result).toBe(false);
87
+ });
88
+ it('returns false when no pending registration exists', async ()=>{
89
+ pendingRepo.findOne.mockResolvedValue(null);
90
+ const result = await service.hasPendingRegistration('user@example.com');
91
+ expect(result).toBe(false);
92
+ });
93
+ });
94
+ describe('createPendingRegistration', ()=>{
95
+ it('throws BadRequestException when email service is not configured', async ()=>{
96
+ const noEmailService = new AuthEmailService(createMockDataSourceProvider(userRepo), undefined);
97
+ await expect(noEmailService.createPendingRegistration({
98
+ email: 'new@example.com',
99
+ password: 'Password1!',
100
+ verifyUrlBase: 'https://app.test/verify'
101
+ })).rejects.toThrow(BadRequestException);
102
+ });
103
+ it('throws BadRequestException when the user already exists', async ()=>{
104
+ userRepo.findOne.mockResolvedValue(buildUser());
105
+ await expect(service.createPendingRegistration({
106
+ email: 'user@example.com',
107
+ password: 'Password1!',
108
+ verifyUrlBase: 'https://app.test/verify'
109
+ })).rejects.toThrow(BadRequestException);
110
+ });
111
+ it('creates a pending registration, hashes the password, and sends verification email', async ()=>{
112
+ userRepo.findOne.mockResolvedValue(null);
113
+ pendingRepo.create.mockImplementation((data)=>data);
114
+ pendingRepo.save.mockResolvedValue({});
115
+ const result = await service.createPendingRegistration({
116
+ email: 'new@example.com',
117
+ name: 'New User',
118
+ password: 'Password1!',
119
+ verifyUrlBase: 'https://app.test/verify'
120
+ });
121
+ expect(pendingRepo.delete).toHaveBeenCalledWith({
122
+ email: 'new@example.com'
123
+ });
124
+ expect(bcrypt.hash).toHaveBeenCalledWith('Password1!', 12);
125
+ expect(pendingRepo.save).toHaveBeenCalled();
126
+ expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalledWith('new@example.com', expect.any(String), expect.stringContaining('https://app.test/verify?token='));
127
+ expect(result.success).toBe(true);
128
+ });
129
+ it('wraps a failed verification email send in BadRequestException', async ()=>{
130
+ userRepo.findOne.mockResolvedValue(null);
131
+ pendingRepo.create.mockImplementation((data)=>data);
132
+ pendingRepo.save.mockResolvedValue({});
133
+ mockEmailProvider.sendVerificationEmail.mockRejectedValue(new Error('smtp down'));
134
+ await expect(service.createPendingRegistration({
135
+ email: 'new@example.com',
136
+ password: 'Password1!',
137
+ verifyUrlBase: 'https://app.test/verify'
138
+ })).rejects.toThrow(BadRequestException);
139
+ });
140
+ });
141
+ describe('forgotPassword', ()=>{
142
+ it('returns a generic success message when the user does not exist (prevents enumeration)', async ()=>{
143
+ userRepo.findOne.mockResolvedValue(null);
144
+ const result = await service.forgotPassword('missing@example.com', 'https://app.test/reset');
145
+ expect(result.success).toBe(true);
146
+ expect(tokenRepo.save).not.toHaveBeenCalled();
147
+ });
148
+ it('returns a generic success message when the user is inactive (prevents enumeration)', async ()=>{
149
+ userRepo.findOne.mockResolvedValue(buildUser({
150
+ isActive: false
151
+ }));
152
+ const result = await service.forgotPassword('user@example.com', 'https://app.test/reset');
153
+ expect(result.success).toBe(true);
154
+ expect(tokenRepo.save).not.toHaveBeenCalled();
155
+ });
156
+ it('invalidates existing tokens and creates a new hashed reset token for an active user', async ()=>{
157
+ userRepo.findOne.mockResolvedValue(buildUser());
158
+ tokenRepo.create.mockImplementation((data)=>data);
159
+ tokenRepo.save.mockResolvedValue({});
160
+ const result = await service.forgotPassword('user@example.com', 'https://app.test/reset');
161
+ expect(tokenRepo.delete).toHaveBeenCalledWith({
162
+ userId: 'user-1',
163
+ type: TokenType.PASSWORD_RESET
164
+ });
165
+ expect(tokenRepo.save).toHaveBeenCalled();
166
+ expect(mockEmailProvider.sendPasswordResetEmail).toHaveBeenCalledWith('user@example.com', expect.any(String), expect.stringContaining('https://app.test/reset?token='));
167
+ expect(result.success).toBe(true);
168
+ });
169
+ it('wraps a failed password-reset email send in BadRequestException', async ()=>{
170
+ userRepo.findOne.mockResolvedValue(buildUser());
171
+ tokenRepo.create.mockImplementation((data)=>data);
172
+ tokenRepo.save.mockResolvedValue({});
173
+ mockEmailProvider.sendPasswordResetEmail.mockRejectedValue(new Error('smtp down'));
174
+ await expect(service.forgotPassword('user@example.com', 'https://app.test/reset')).rejects.toThrow(BadRequestException);
175
+ });
176
+ });
177
+ describe('resetPassword', ()=>{
178
+ it('throws BadRequestException when the token is not found', async ()=>{
179
+ tokenRepo.findOne.mockResolvedValue(null);
180
+ await expect(service.resetPassword('bad-token', 'NewPassword1!')).rejects.toThrow(BadRequestException);
181
+ });
182
+ it('throws BadRequestException when the token has expired', async ()=>{
183
+ tokenRepo.findOne.mockResolvedValue(buildUserToken({
184
+ expiresAt: new Date(Date.now() - 60_000)
185
+ }));
186
+ await expect(service.resetPassword('token', 'NewPassword1!')).rejects.toThrow(BadRequestException);
187
+ });
188
+ it('throws BadRequestException when the token has already been used', async ()=>{
189
+ tokenRepo.findOne.mockResolvedValue(buildUserToken({
190
+ usedAt: new Date()
191
+ }));
192
+ await expect(service.resetPassword('token', 'NewPassword1!')).rejects.toThrow(BadRequestException);
193
+ });
194
+ it('throws BadRequestException when the associated user no longer exists', async ()=>{
195
+ tokenRepo.findOne.mockResolvedValue(buildUserToken());
196
+ userRepo.findOne.mockResolvedValue(null);
197
+ await expect(service.resetPassword('token', 'NewPassword1!')).rejects.toThrow(BadRequestException);
198
+ });
199
+ it('hashes the new password, saves the user, and marks the token as used', async ()=>{
200
+ const token = buildUserToken();
201
+ tokenRepo.findOne.mockResolvedValue(token);
202
+ userRepo.findOne.mockResolvedValue(buildUser());
203
+ userRepo.save.mockResolvedValue(buildUser());
204
+ tokenRepo.save.mockResolvedValue(token);
205
+ const result = await service.resetPassword('raw-token', 'NewPassword1!');
206
+ expect(bcrypt.hash).toHaveBeenCalledWith('NewPassword1!', 12);
207
+ expect(userRepo.save).toHaveBeenCalled();
208
+ expect(tokenRepo.save).toHaveBeenCalledWith(expect.objectContaining({
209
+ usedAt: expect.any(Date)
210
+ }));
211
+ expect(result.success).toBe(true);
212
+ });
213
+ });
214
+ describe('verifyEmail', ()=>{
215
+ it('resolves a pending registration and deletes it', async ()=>{
216
+ const pending = {
217
+ id: 'pending-1',
218
+ email: 'new@example.com',
219
+ expiresAt: new Date(Date.now() + 60_000)
220
+ };
221
+ pendingRepo.findOne.mockResolvedValue(pending);
222
+ const result = await service.verifyEmail('raw-token');
223
+ expect(result).toEqual({
224
+ type: 'pending',
225
+ pending
226
+ });
227
+ expect(pendingRepo.delete).toHaveBeenCalledWith({
228
+ id: 'pending-1'
229
+ });
230
+ });
231
+ it('deletes and throws when the pending registration has expired', async ()=>{
232
+ const pending = {
233
+ id: 'pending-1',
234
+ expiresAt: new Date(Date.now() - 60_000)
235
+ };
236
+ pendingRepo.findOne.mockResolvedValue(pending);
237
+ await expect(service.verifyEmail('raw-token')).rejects.toThrow(BadRequestException);
238
+ expect(pendingRepo.delete).toHaveBeenCalledWith({
239
+ id: 'pending-1'
240
+ });
241
+ });
242
+ it('throws BadRequestException when no pending registration or user token is found', async ()=>{
243
+ pendingRepo.findOne.mockResolvedValue(null);
244
+ tokenRepo.findOne.mockResolvedValue(null);
245
+ await expect(service.verifyEmail('raw-token')).rejects.toThrow(BadRequestException);
246
+ });
247
+ it('deletes and throws when the user token has expired', async ()=>{
248
+ pendingRepo.findOne.mockResolvedValue(null);
249
+ tokenRepo.findOne.mockResolvedValue(buildUserToken({
250
+ type: TokenType.EMAIL_VERIFICATION,
251
+ expiresAt: new Date(Date.now() - 60_000)
252
+ }));
253
+ await expect(service.verifyEmail('raw-token')).rejects.toThrow(BadRequestException);
254
+ expect(tokenRepo.delete).toHaveBeenCalled();
255
+ });
256
+ it('returns already-verified message when the token has already been used', async ()=>{
257
+ pendingRepo.findOne.mockResolvedValue(null);
258
+ tokenRepo.findOne.mockResolvedValue(buildUserToken({
259
+ type: TokenType.EMAIL_VERIFICATION,
260
+ usedAt: new Date()
261
+ }));
262
+ const result = await service.verifyEmail('raw-token');
263
+ expect(result).toEqual(expect.objectContaining({
264
+ type: 'verified',
265
+ message: 'Email has already been verified.'
266
+ }));
267
+ });
268
+ it('throws BadRequestException when the user for the token no longer exists', async ()=>{
269
+ pendingRepo.findOne.mockResolvedValue(null);
270
+ tokenRepo.findOne.mockResolvedValue(buildUserToken({
271
+ type: TokenType.EMAIL_VERIFICATION
272
+ }));
273
+ userRepo.findOne.mockResolvedValue(null);
274
+ await expect(service.verifyEmail('raw-token')).rejects.toThrow(BadRequestException);
275
+ });
276
+ it('marks the user email verified and the token used on success', async ()=>{
277
+ const token = buildUserToken({
278
+ type: TokenType.EMAIL_VERIFICATION
279
+ });
280
+ pendingRepo.findOne.mockResolvedValue(null);
281
+ tokenRepo.findOne.mockResolvedValue(token);
282
+ userRepo.findOne.mockResolvedValue(buildUser({
283
+ emailVerified: false
284
+ }));
285
+ userRepo.save.mockResolvedValue({});
286
+ tokenRepo.save.mockResolvedValue({});
287
+ const result = await service.verifyEmail('raw-token');
288
+ expect(userRepo.save).toHaveBeenCalledWith(expect.objectContaining({
289
+ emailVerified: true
290
+ }));
291
+ expect(tokenRepo.save).toHaveBeenCalledWith(expect.objectContaining({
292
+ usedAt: expect.any(Date)
293
+ }));
294
+ expect(result).toEqual(expect.objectContaining({
295
+ type: 'verified'
296
+ }));
297
+ });
298
+ });
299
+ describe('resendVerificationEmail', ()=>{
300
+ it('throws BadRequestException when email service is not configured', async ()=>{
301
+ const noEmailService = new AuthEmailService(createMockDataSourceProvider(pendingRepo), undefined);
302
+ await expect(noEmailService.resendVerificationEmail('user@example.com', 'https://app.test/verify')).rejects.toThrow(BadRequestException);
303
+ });
304
+ it('resends verification for a pending registration', async ()=>{
305
+ const pending = {
306
+ email: 'new@example.com',
307
+ token: 'old-hash',
308
+ expiresAt: new Date()
309
+ };
310
+ pendingRepo.findOne.mockResolvedValue(pending);
311
+ pendingRepo.save.mockResolvedValue(pending);
312
+ const result = await service.resendVerificationEmail('new@example.com', 'https://app.test/verify');
313
+ expect(pendingRepo.save).toHaveBeenCalled();
314
+ expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalled();
315
+ expect(result.success).toBe(true);
316
+ });
317
+ it('returns generic success without sending when the user does not exist (prevents enumeration)', async ()=>{
318
+ pendingRepo.findOne.mockResolvedValue(null);
319
+ userRepo.findOne.mockResolvedValue(null);
320
+ const result = await service.resendVerificationEmail('missing@example.com', 'https://app.test/verify');
321
+ expect(result.success).toBe(true);
322
+ expect(mockEmailProvider.sendVerificationEmail).not.toHaveBeenCalled();
323
+ });
324
+ it('returns generic success without sending when the user is already verified', async ()=>{
325
+ pendingRepo.findOne.mockResolvedValue(null);
326
+ userRepo.findOne.mockResolvedValue(buildUser({
327
+ emailVerified: true
328
+ }));
329
+ const result = await service.resendVerificationEmail('user@example.com', 'https://app.test/verify');
330
+ expect(result.success).toBe(true);
331
+ expect(mockEmailProvider.sendVerificationEmail).not.toHaveBeenCalled();
332
+ });
333
+ it('invalidates old tokens and sends a new verification token for an unverified user', async ()=>{
334
+ pendingRepo.findOne.mockResolvedValue(null);
335
+ userRepo.findOne.mockResolvedValue(buildUser({
336
+ emailVerified: false
337
+ }));
338
+ tokenRepo.create.mockImplementation((data)=>data);
339
+ tokenRepo.save.mockResolvedValue({});
340
+ const result = await service.resendVerificationEmail('user@example.com', 'https://app.test/verify');
341
+ expect(tokenRepo.delete).toHaveBeenCalledWith({
342
+ userId: 'user-1',
343
+ type: TokenType.EMAIL_VERIFICATION
344
+ });
345
+ expect(mockEmailProvider.sendVerificationEmail).toHaveBeenCalled();
346
+ expect(result.success).toBe(true);
347
+ });
348
+ });
349
+ describe('getRepository failure path', ()=>{
350
+ it('throws InternalServerErrorException when the data source provider is unavailable', async ()=>{
351
+ const noDataSourceService = new AuthEmailService(undefined, mockEmailProvider);
352
+ await expect(noDataSourceService.createPendingRegistration({
353
+ email: 'new@example.com',
354
+ password: 'Password1!',
355
+ verifyUrlBase: 'https://app.test/verify'
356
+ })).rejects.toThrow(InternalServerErrorException);
357
+ });
358
+ });
359
+ });