@flusys/nestjs-auth 0.1.0-beta.3 → 1.0.0-rc

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 (102) hide show
  1. package/README.md +274 -301
  2. package/cjs/config/auth.constants.js +22 -4
  3. package/cjs/controllers/authentication.controller.js +222 -38
  4. package/cjs/controllers/branch.controller.js +46 -4
  5. package/cjs/controllers/company-selection.controller.js +27 -20
  6. package/cjs/controllers/company.controller.js +46 -4
  7. package/cjs/controllers/user-permission.controller.js +40 -37
  8. package/cjs/controllers/user.controller.js +222 -23
  9. package/cjs/dtos/authentication.dto.js +119 -13
  10. package/cjs/dtos/user-permission.dto.js +28 -0
  11. package/cjs/dtos/user.dto.js +19 -4
  12. package/cjs/entities/index.js +5 -1
  13. package/cjs/entities/pending-registration.entity.js +125 -0
  14. package/cjs/entities/user-company-permission.entity.js +0 -6
  15. package/cjs/entities/user-token.entity.js +129 -0
  16. package/cjs/guards/auth-throttler.guard.js +53 -0
  17. package/cjs/interceptors/clear-token.interceptor.js +3 -6
  18. package/cjs/interceptors/set-token.interceptor.js +38 -31
  19. package/cjs/interfaces/auth-email-provider.interface.js +45 -0
  20. package/cjs/interfaces/authentication.interface.js +0 -3
  21. package/cjs/interfaces/index.js +2 -0
  22. package/cjs/interfaces/user-enricher.interface.js +4 -0
  23. package/cjs/modules/auth.module.js +8 -20
  24. package/cjs/services/auth-config.service.js +42 -47
  25. package/cjs/services/auth-datasource.provider.js +18 -34
  26. package/cjs/services/auth-email.service.js +471 -0
  27. package/cjs/services/authentication.service.js +240 -153
  28. package/cjs/services/branch.service.js +15 -48
  29. package/cjs/services/company-selection-session.service.js +1 -1
  30. package/cjs/services/company.service.js +7 -36
  31. package/cjs/services/index.js +1 -0
  32. package/cjs/services/user-permission.service.js +9 -29
  33. package/cjs/services/user.service.js +228 -107
  34. package/cjs/strategies/jwt.strategy.js +14 -1
  35. package/cjs/validators/password.validator.js +45 -0
  36. package/config/auth.constants.d.ts +5 -0
  37. package/controllers/authentication.controller.d.ts +13 -9
  38. package/controllers/company-selection.controller.d.ts +6 -2
  39. package/controllers/user.controller.d.ts +33 -0
  40. package/dtos/authentication.dto.d.ts +21 -3
  41. package/dtos/company-branch.dto.d.ts +0 -1
  42. package/dtos/company.dto.d.ts +0 -1
  43. package/dtos/user-permission.dto.d.ts +4 -0
  44. package/dtos/user.dto.d.ts +1 -2
  45. package/entities/index.d.ts +7 -3
  46. package/entities/pending-registration.entity.d.ts +17 -0
  47. package/entities/user-company-permission.entity.d.ts +0 -2
  48. package/entities/user-token.entity.d.ts +15 -0
  49. package/fesm/config/auth.constants.js +11 -8
  50. package/fesm/controllers/authentication.controller.js +224 -40
  51. package/fesm/controllers/branch.controller.js +49 -7
  52. package/fesm/controllers/company-selection.controller.js +28 -21
  53. package/fesm/controllers/company.controller.js +49 -7
  54. package/fesm/controllers/user-permission.controller.js +41 -38
  55. package/fesm/controllers/user.controller.js +225 -26
  56. package/fesm/dtos/authentication.dto.js +123 -111
  57. package/fesm/dtos/user-permission.dto.js +28 -0
  58. package/fesm/dtos/user.dto.js +20 -5
  59. package/fesm/entities/index.js +7 -1
  60. package/fesm/entities/pending-registration.entity.js +115 -0
  61. package/fesm/entities/user-company-permission.entity.js +0 -6
  62. package/fesm/entities/user-token.entity.js +113 -0
  63. package/fesm/guards/auth-throttler.guard.js +43 -0
  64. package/fesm/interceptors/clear-token.interceptor.js +2 -5
  65. package/fesm/interceptors/set-token.interceptor.js +37 -30
  66. package/fesm/interfaces/auth-email-provider.interface.js +38 -0
  67. package/fesm/interfaces/authentication.interface.js +1 -7
  68. package/fesm/interfaces/index.js +2 -0
  69. package/fesm/interfaces/user-enricher.interface.js +26 -0
  70. package/fesm/modules/auth.module.js +10 -22
  71. package/fesm/services/auth-config.service.js +42 -47
  72. package/fesm/services/auth-datasource.provider.js +19 -35
  73. package/fesm/services/auth-email.service.js +420 -0
  74. package/fesm/services/authentication.service.js +238 -151
  75. package/fesm/services/branch.service.js +16 -49
  76. package/fesm/services/company-selection-session.service.js +1 -1
  77. package/fesm/services/company.service.js +8 -37
  78. package/fesm/services/index.js +1 -0
  79. package/fesm/services/user-permission.service.js +10 -30
  80. package/fesm/services/user.service.js +229 -108
  81. package/fesm/strategies/jwt.strategy.js +14 -1
  82. package/fesm/validators/password.validator.js +48 -0
  83. package/guards/auth-throttler.guard.d.ts +7 -0
  84. package/interceptors/set-token.interceptor.d.ts +1 -0
  85. package/interfaces/auth-email-provider.interface.d.ts +6 -0
  86. package/interfaces/auth-module-options.interface.d.ts +4 -1
  87. package/interfaces/authentication.interface.d.ts +14 -0
  88. package/interfaces/index.d.ts +2 -0
  89. package/interfaces/user-enricher.interface.d.ts +64 -0
  90. package/interfaces/user.interface.d.ts +1 -0
  91. package/modules/auth.module.d.ts +0 -1
  92. package/package.json +4 -4
  93. package/services/auth-config.service.d.ts +5 -1
  94. package/services/auth-email.service.d.ts +51 -0
  95. package/services/authentication.service.d.ts +21 -12
  96. package/services/branch.service.d.ts +2 -5
  97. package/services/company-selection-session.service.d.ts +1 -1
  98. package/services/company.service.d.ts +1 -4
  99. package/services/index.d.ts +1 -0
  100. package/services/user-permission.service.d.ts +0 -1
  101. package/services/user.service.d.ts +20 -6
  102. package/validators/password.validator.d.ts +10 -0
@@ -26,17 +26,14 @@ function _ts_param(paramIndex, decorator) {
26
26
  };
27
27
  }
28
28
  import { MultiTenantDataSourceService } from '@flusys/nestjs-shared/modules';
29
- import { Inject, Injectable, Logger, Optional, Scope } from '@nestjs/common';
29
+ import { Inject, Injectable, InternalServerErrorException, Logger, Optional, Scope } from '@nestjs/common';
30
30
  import { REQUEST } from '@nestjs/core';
31
31
  import { Request } from 'express';
32
32
  import { AuthModuleOptions } from '../interfaces/auth-module-options.interface';
33
33
  import { AUTH_MODULE_OPTIONS } from '../config/auth.constants';
34
34
  export class AuthDataSourceProvider extends MultiTenantDataSourceService {
35
- // ==================== Override Static Cache Access Methods ====================
36
- /**
37
- * CRITICAL: Override to access Auth-specific static properties
38
- * Without this, parent class methods would access parent's static properties
39
- */ async getSingleDataSource() {
35
+ // Override Static Cache Access Methods
36
+ /** Override to access Auth-specific static properties */ async getSingleDataSource() {
40
37
  if (!AuthDataSourceProvider.singleDataSource) {
41
38
  if (AuthDataSourceProvider.singleConnectionLock) {
42
39
  return AuthDataSourceProvider.singleConnectionLock;
@@ -44,7 +41,7 @@ export class AuthDataSourceProvider extends MultiTenantDataSourceService {
44
41
  const lockPromise = (async ()=>{
45
42
  const config = this.getDefaultDatabaseConfig();
46
43
  if (!config) {
47
- throw new Error('Default database config is not available');
44
+ throw new InternalServerErrorException('Default database config is not available');
48
45
  }
49
46
  const ds = await this.createDataSourceFromConfig(config);
50
47
  AuthDataSourceProvider.singleDataSource = ds;
@@ -60,9 +57,7 @@ export class AuthDataSourceProvider extends MultiTenantDataSourceService {
60
57
  }
61
58
  return AuthDataSourceProvider.singleDataSource;
62
59
  }
63
- /**
64
- * CRITICAL: Override to use Auth-specific static cache for tenant connections
65
- */ async getOrCreateTenantConnection(tenant) {
60
+ /** Override to use Auth-specific static cache for tenant connections */ async getOrCreateTenantConnection(tenant) {
66
61
  // Return existing initialized connection from Auth-specific cache
67
62
  const existing = AuthDataSourceProvider.tenantConnections.get(tenant.id);
68
63
  if (existing?.isInitialized) {
@@ -85,10 +80,8 @@ export class AuthDataSourceProvider extends MultiTenantDataSourceService {
85
80
  AuthDataSourceProvider.connectionLocks.delete(tenant.id);
86
81
  }
87
82
  }
88
- // ==================== Factory Methods ====================
89
- /**
90
- * Build parent options from AuthModuleOptions
91
- */ static buildParentOptions(options) {
83
+ // Factory Methods
84
+ /** Build parent options from AuthModuleOptions */ static buildParentOptions(options) {
92
85
  return {
93
86
  bootstrapAppConfig: options.bootstrapAppConfig,
94
87
  defaultDatabaseConfig: options.config?.defaultDatabaseConfig,
@@ -96,31 +89,24 @@ export class AuthDataSourceProvider extends MultiTenantDataSourceService {
96
89
  tenants: options.config?.tenants
97
90
  };
98
91
  }
99
- // ==================== Feature Flags ====================
100
- /**
101
- * Get global enable company feature flag
102
- */ getEnableCompanyFeature() {
92
+ // Feature Flags
93
+ /** Get global enable company feature flag */ getEnableCompanyFeature() {
103
94
  return this.authOptions.bootstrapAppConfig?.enableCompanyFeature ?? false;
104
95
  }
105
- /**
106
- * Get enable company feature for specific tenant
107
- * Falls back to global setting if not specified per-tenant
108
- */ getEnableCompanyFeatureForTenant(tenant) {
96
+ /** Get enable company feature for specific tenant. Falls back to global setting. */ getEnableCompanyFeatureForTenant(tenant) {
109
97
  return tenant?.enableCompanyFeature ?? this.getEnableCompanyFeature();
110
98
  }
111
- /**
112
- * Get enable company feature for current request context
113
- */ getEnableCompanyFeatureForCurrentTenant() {
99
+ /** Get enable company feature for current request context */ getEnableCompanyFeatureForCurrentTenant() {
114
100
  return this.getEnableCompanyFeatureForTenant(this.getCurrentTenant() ?? undefined);
115
101
  }
116
- // ==================== Entity Management ====================
117
- /**
118
- * Get auth entities based on company feature flag
119
- */ async getAuthEntities(enableCompanyFeature) {
102
+ // Entity Management
103
+ /** Get auth entities based on company feature flag */ async getAuthEntities(enableCompanyFeature) {
120
104
  const enable = enableCompanyFeature ?? this.getEnableCompanyFeature();
121
- const { Company, CompanyBranch, User, UserCompanyPermission } = await import('../entities');
105
+ const { Company, CompanyBranch, User, UserCompanyPermission, UserToken, PendingRegistration } = await import('../entities');
122
106
  const coreEntities = [
123
- User
107
+ User,
108
+ UserToken,
109
+ PendingRegistration
124
110
  ];
125
111
  const companyEntities = enable ? [
126
112
  Company,
@@ -132,10 +118,8 @@ export class AuthDataSourceProvider extends MultiTenantDataSourceService {
132
118
  ...companyEntities
133
119
  ];
134
120
  }
135
- // ==================== Overrides ====================
136
- /**
137
- * Override to dynamically set entities based on tenant config
138
- */ async createDataSourceFromConfig(config) {
121
+ // Overrides
122
+ /** Override to dynamically set entities based on tenant config */ async createDataSourceFromConfig(config) {
139
123
  const currentTenant = this.getCurrentTenant();
140
124
  const enableCompanyFeature = this.getEnableCompanyFeatureForTenant(currentTenant ?? undefined);
141
125
  const entities = await this.getAuthEntities(enableCompanyFeature);
@@ -0,0 +1,420 @@
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value: value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+ return obj;
13
+ }
14
+ function _ts_decorate(decorators, target, key, desc) {
15
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
16
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
17
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
18
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
19
+ }
20
+ function _ts_metadata(k, v) {
21
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
22
+ }
23
+ function _ts_param(paramIndex, decorator) {
24
+ return function(target, key) {
25
+ decorator(target, key, paramIndex);
26
+ };
27
+ }
28
+ import { BadRequestException, Inject, Injectable, InternalServerErrorException, Logger, Optional, Scope } from '@nestjs/common';
29
+ import * as bcrypt from 'bcrypt';
30
+ import * as crypto from 'crypto';
31
+ import { LessThan } from 'typeorm';
32
+ import { AuthDataSourceProvider } from './auth-datasource.provider';
33
+ import { PendingRegistration } from '../entities/pending-registration.entity';
34
+ import { TokenType, UserToken } from '../entities/user-token.entity';
35
+ import { User } from '../entities/user.entity';
36
+ import { AUTH_EMAIL_PROVIDER, IAuthEmailProvider } from '../interfaces';
37
+ import { BCRYPT_SALT_ROUNDS } from '../config';
38
+ export class AuthEmailService {
39
+ async getUserRepository() {
40
+ if (this.dataSourceProvider) {
41
+ return this.dataSourceProvider.getRepository(User);
42
+ }
43
+ throw new InternalServerErrorException('User repository not available');
44
+ }
45
+ async getUserTokenRepository() {
46
+ if (this.dataSourceProvider) {
47
+ return this.dataSourceProvider.getRepository(UserToken);
48
+ }
49
+ throw new InternalServerErrorException('UserToken repository not available');
50
+ }
51
+ async getPendingRegistrationRepository() {
52
+ if (this.dataSourceProvider) {
53
+ return this.dataSourceProvider.getRepository(PendingRegistration);
54
+ }
55
+ throw new InternalServerErrorException('PendingRegistration repository not available');
56
+ }
57
+ isEmailEnabled() {
58
+ return !!this.emailProvider;
59
+ }
60
+ generateToken() {
61
+ return crypto.randomBytes(32).toString('hex');
62
+ }
63
+ /** Hash token for secure storage - prevents token theft if database is compromised */ hashToken(token) {
64
+ return crypto.createHash('sha256').update(token).digest('hex');
65
+ }
66
+ // ============================================
67
+ // Pending Registration (New Users)
68
+ // ============================================
69
+ /**
70
+ * Create pending registration - stores data until email verified
71
+ */ async createPendingRegistration(data) {
72
+ if (!this.emailProvider) {
73
+ throw new BadRequestException('Email service is not configured');
74
+ }
75
+ const userRepository = await this.getUserRepository();
76
+ const pendingRepository = await this.getPendingRegistrationRepository();
77
+ // Check if user already exists
78
+ const existingUser = await userRepository.findOne({
79
+ where: {
80
+ email: data.email
81
+ }
82
+ });
83
+ if (existingUser) {
84
+ throw new BadRequestException('Registration failed. Please try again or contact support.');
85
+ }
86
+ // Delete any existing pending registration for this email
87
+ await pendingRepository.delete({
88
+ email: data.email
89
+ });
90
+ // Create pending registration with hashed token for secure storage
91
+ const token = this.generateToken();
92
+ const tokenHash = this.hashToken(token);
93
+ const passwordHash = await bcrypt.hash(data.password, BCRYPT_SALT_ROUNDS);
94
+ const expiresAt = new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY);
95
+ const pending = pendingRepository.create({
96
+ email: data.email,
97
+ name: data.name ?? null,
98
+ phone: data.phone ?? null,
99
+ passwordHash,
100
+ token: tokenHash,
101
+ expiresAt,
102
+ companyData: data.companyData ?? null
103
+ });
104
+ await pendingRepository.save(pending);
105
+ // Send verification email with raw token (user receives this)
106
+ const verifyUrl = `${data.verifyUrlBase}?token=${token}`;
107
+ try {
108
+ await this.emailProvider.sendVerificationEmail(data.email, token, verifyUrl);
109
+ this.logger.log(`Registration verification email sent to: ${data.email}`);
110
+ } catch (error) {
111
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
112
+ this.logger.error(`Failed to send verification email: ${errorMessage}`);
113
+ throw new BadRequestException('Failed to send verification email. Please try again.');
114
+ }
115
+ return {
116
+ success: true,
117
+ message: 'Please check your email to verify your registration.'
118
+ };
119
+ }
120
+ // ============================================
121
+ // Password Reset (Existing Users)
122
+ // ============================================
123
+ /**
124
+ * Request password reset - sends reset email
125
+ */ async forgotPassword(email, resetUrlBase) {
126
+ if (!this.emailProvider) {
127
+ throw new BadRequestException('Email service is not configured');
128
+ }
129
+ const userRepository = await this.getUserRepository();
130
+ const tokenRepository = await this.getUserTokenRepository();
131
+ const user = await userRepository.findOne({
132
+ where: {
133
+ email
134
+ }
135
+ });
136
+ // Always return success to prevent email enumeration
137
+ if (!user || !user.isActive) {
138
+ this.logger.warn(`Password reset requested for non-existent/inactive email: ${email}`);
139
+ return {
140
+ success: true,
141
+ message: 'If the email exists, a password reset link has been sent.'
142
+ };
143
+ }
144
+ // Invalidate existing password reset tokens for this user
145
+ await tokenRepository.delete({
146
+ userId: user.id,
147
+ type: TokenType.PASSWORD_RESET
148
+ });
149
+ // Create new token with hashed storage
150
+ const token = this.generateToken();
151
+ const tokenHash = this.hashToken(token);
152
+ const userToken = tokenRepository.create({
153
+ userId: user.id,
154
+ type: TokenType.PASSWORD_RESET,
155
+ token: tokenHash,
156
+ expiresAt: new Date(Date.now() + this.PASSWORD_RESET_EXPIRY)
157
+ });
158
+ await tokenRepository.save(userToken);
159
+ // Send email with raw token
160
+ const resetUrl = `${resetUrlBase}?token=${token}`;
161
+ try {
162
+ await this.emailProvider.sendPasswordResetEmail(email, token, resetUrl);
163
+ this.logger.log(`Password reset email sent to: ${email}`);
164
+ } catch (error) {
165
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
166
+ this.logger.error(`Failed to send password reset email: ${errorMessage}`);
167
+ // Don't silently fail - but still use same message to prevent enumeration
168
+ throw new BadRequestException('Failed to process request. Please try again later.');
169
+ }
170
+ return {
171
+ success: true,
172
+ message: 'If the email exists, a password reset link has been sent.'
173
+ };
174
+ }
175
+ /**
176
+ * Reset password using token
177
+ */ async resetPassword(token, newPassword) {
178
+ const userRepository = await this.getUserRepository();
179
+ const tokenRepository = await this.getUserTokenRepository();
180
+ // Hash the incoming token to compare with stored hash
181
+ const tokenHash = this.hashToken(token);
182
+ const userToken = await tokenRepository.findOne({
183
+ where: {
184
+ token: tokenHash,
185
+ type: TokenType.PASSWORD_RESET
186
+ }
187
+ });
188
+ if (!userToken) {
189
+ throw new BadRequestException('Invalid or expired reset token');
190
+ }
191
+ if (userToken.expiresAt < new Date()) {
192
+ await tokenRepository.delete({
193
+ id: userToken.id
194
+ });
195
+ throw new BadRequestException('Reset token has expired. Please request a new one.');
196
+ }
197
+ if (userToken.usedAt) {
198
+ throw new BadRequestException('This reset token has already been used.');
199
+ }
200
+ const user = await userRepository.findOne({
201
+ where: {
202
+ id: userToken.userId
203
+ }
204
+ });
205
+ if (!user) {
206
+ throw new BadRequestException('User not found');
207
+ }
208
+ // Update password
209
+ user.password = await bcrypt.hash(newPassword, BCRYPT_SALT_ROUNDS);
210
+ await userRepository.save(user);
211
+ // Mark token as used
212
+ userToken.usedAt = new Date();
213
+ await tokenRepository.save(userToken);
214
+ this.logger.log(`Password reset successful for user: ${user.email}`);
215
+ return {
216
+ success: true,
217
+ message: 'Password has been reset successfully.'
218
+ };
219
+ }
220
+ // ============================================
221
+ // Email Verification
222
+ // ============================================
223
+ /**
224
+ * Verify email using token
225
+ * Handles both pending registration and existing user verification
226
+ */ async verifyEmail(token) {
227
+ const pendingRepository = await this.getPendingRegistrationRepository();
228
+ const userRepository = await this.getUserRepository();
229
+ const tokenRepository = await this.getUserTokenRepository();
230
+ // Hash the incoming token to compare with stored hash
231
+ const tokenHash = this.hashToken(token);
232
+ // Check for pending registration first
233
+ const pending = await pendingRepository.findOne({
234
+ where: {
235
+ token: tokenHash
236
+ }
237
+ });
238
+ if (pending) {
239
+ if (pending.expiresAt < new Date()) {
240
+ await pendingRepository.delete({
241
+ id: pending.id
242
+ });
243
+ throw new BadRequestException('Verification token has expired. Please register again.');
244
+ }
245
+ // Delete pending registration (will be consumed by caller to create user)
246
+ await pendingRepository.delete({
247
+ id: pending.id
248
+ });
249
+ return {
250
+ type: 'pending',
251
+ pending
252
+ };
253
+ }
254
+ // Check for existing user email verification token (token already hashed above)
255
+ const userToken = await tokenRepository.findOne({
256
+ where: {
257
+ token: tokenHash,
258
+ type: TokenType.EMAIL_VERIFICATION
259
+ }
260
+ });
261
+ if (!userToken) {
262
+ throw new BadRequestException('Invalid or expired verification token');
263
+ }
264
+ if (userToken.expiresAt < new Date()) {
265
+ await tokenRepository.delete({
266
+ id: userToken.id
267
+ });
268
+ throw new BadRequestException('Verification token has expired. Please request a new one.');
269
+ }
270
+ if (userToken.usedAt) {
271
+ return {
272
+ type: 'verified',
273
+ message: 'Email has already been verified.'
274
+ };
275
+ }
276
+ const user = await userRepository.findOne({
277
+ where: {
278
+ id: userToken.userId
279
+ }
280
+ });
281
+ if (!user) {
282
+ throw new BadRequestException('User not found');
283
+ }
284
+ // Mark email as verified
285
+ user.emailVerified = true;
286
+ await userRepository.save(user);
287
+ // Mark token as used
288
+ userToken.usedAt = new Date();
289
+ await tokenRepository.save(userToken);
290
+ this.logger.log(`Email verified for user: ${user.email}`);
291
+ return {
292
+ type: 'verified',
293
+ message: 'Email has been verified successfully.'
294
+ };
295
+ }
296
+ /**
297
+ * Resend verification email - handles both pending registrations and existing users
298
+ */ async resendVerificationEmail(email, verifyUrlBase) {
299
+ if (!this.emailProvider) {
300
+ throw new BadRequestException('Email service is not configured');
301
+ }
302
+ const pendingRepository = await this.getPendingRegistrationRepository();
303
+ const userRepository = await this.getUserRepository();
304
+ const tokenRepository = await this.getUserTokenRepository();
305
+ // Check pending registration first
306
+ const pending = await pendingRepository.findOne({
307
+ where: {
308
+ email
309
+ }
310
+ });
311
+ if (pending) {
312
+ const token = this.generateToken();
313
+ const tokenHash = this.hashToken(token);
314
+ pending.token = tokenHash; // Store hashed token
315
+ pending.expiresAt = new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY);
316
+ await pendingRepository.save(pending);
317
+ const verifyUrl = `${verifyUrlBase}?token=${token}`;
318
+ try {
319
+ await this.emailProvider.sendVerificationEmail(email, token, verifyUrl);
320
+ this.logger.log(`Re-sent registration verification email to: ${email}`);
321
+ } catch (error) {
322
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
323
+ this.logger.error(`Failed to resend verification email: ${errorMessage}`);
324
+ throw new BadRequestException('Failed to send verification email. Please try again.');
325
+ }
326
+ return {
327
+ success: true,
328
+ message: 'If the email requires verification, a link has been sent.'
329
+ };
330
+ }
331
+ // Check existing user
332
+ const user = await userRepository.findOne({
333
+ where: {
334
+ email
335
+ }
336
+ });
337
+ if (!user || user.emailVerified) {
338
+ return {
339
+ success: true,
340
+ message: 'If the email requires verification, a link has been sent.'
341
+ };
342
+ }
343
+ // Invalidate existing tokens and create new one
344
+ await tokenRepository.delete({
345
+ userId: user.id,
346
+ type: TokenType.EMAIL_VERIFICATION
347
+ });
348
+ const token = this.generateToken();
349
+ const tokenHash = this.hashToken(token);
350
+ const userToken = tokenRepository.create({
351
+ userId: user.id,
352
+ type: TokenType.EMAIL_VERIFICATION,
353
+ token: tokenHash,
354
+ expiresAt: new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY)
355
+ });
356
+ await tokenRepository.save(userToken);
357
+ const verifyUrl = `${verifyUrlBase}?token=${token}`;
358
+ try {
359
+ await this.emailProvider.sendVerificationEmail(user.email, token, verifyUrl);
360
+ this.logger.log(`Verification email sent to: ${user.email}`);
361
+ } catch (error) {
362
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
363
+ this.logger.error(`Failed to send verification email: ${errorMessage}`);
364
+ throw new BadRequestException('Failed to send verification email. Please try again.');
365
+ }
366
+ return {
367
+ success: true,
368
+ message: 'If the email requires verification, a link has been sent.'
369
+ };
370
+ }
371
+ // ============================================
372
+ // Cleanup
373
+ // ============================================
374
+ /**
375
+ * Clean up expired tokens and pending registrations
376
+ */ async cleanupExpired() {
377
+ const tokenRepository = await this.getUserTokenRepository();
378
+ const pendingRepository = await this.getPendingRegistrationRepository();
379
+ const now = new Date();
380
+ const tokenResult = await tokenRepository.delete({
381
+ expiresAt: LessThan(now)
382
+ });
383
+ const pendingResult = await pendingRepository.delete({
384
+ expiresAt: LessThan(now)
385
+ });
386
+ const deletedTokens = tokenResult.affected ?? 0;
387
+ const deletedPending = pendingResult.affected ?? 0;
388
+ this.logger.log(`Cleaned up ${deletedTokens} expired tokens and ${deletedPending} expired pending registrations`);
389
+ return {
390
+ deletedTokens,
391
+ deletedPending
392
+ };
393
+ }
394
+ constructor(dataSourceProvider, emailProvider){
395
+ _define_property(this, "dataSourceProvider", void 0);
396
+ _define_property(this, "emailProvider", void 0);
397
+ _define_property(this, "logger", void 0);
398
+ _define_property(this, "PASSWORD_RESET_EXPIRY", void 0); // 1 hour
399
+ _define_property(this, "EMAIL_VERIFICATION_EXPIRY", void 0); // 24 hours
400
+ this.dataSourceProvider = dataSourceProvider;
401
+ this.emailProvider = emailProvider;
402
+ this.logger = new Logger(AuthEmailService.name);
403
+ this.PASSWORD_RESET_EXPIRY = 60 * 60 * 1000;
404
+ this.EMAIL_VERIFICATION_EXPIRY = 24 * 60 * 60 * 1000;
405
+ }
406
+ }
407
+ AuthEmailService = _ts_decorate([
408
+ Injectable({
409
+ scope: Scope.REQUEST
410
+ }),
411
+ _ts_param(0, Optional()),
412
+ _ts_param(0, Inject(AuthDataSourceProvider)),
413
+ _ts_param(1, Optional()),
414
+ _ts_param(1, Inject(AUTH_EMAIL_PROVIDER)),
415
+ _ts_metadata("design:type", Function),
416
+ _ts_metadata("design:paramtypes", [
417
+ typeof AuthDataSourceProvider === "undefined" ? Object : AuthDataSourceProvider,
418
+ typeof IAuthEmailProvider === "undefined" ? Object : IAuthEmailProvider
419
+ ])
420
+ ], AuthEmailService);