@flusys/nestjs-auth 1.0.0-beta → 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 (95) hide show
  1. package/README.md +274 -291
  2. package/cjs/config/auth.constants.js +12 -0
  3. package/cjs/controllers/authentication.controller.js +219 -10
  4. package/cjs/controllers/branch.controller.js +44 -1
  5. package/cjs/controllers/company-selection.controller.js +27 -20
  6. package/cjs/controllers/company.controller.js +44 -1
  7. package/cjs/controllers/user-permission.controller.js +40 -25
  8. package/cjs/controllers/user.controller.js +211 -7
  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/index.js +2 -0
  21. package/cjs/interfaces/user-enricher.interface.js +4 -0
  22. package/cjs/modules/auth.module.js +8 -20
  23. package/cjs/services/auth-config.service.js +23 -2
  24. package/cjs/services/auth-datasource.provider.js +5 -3
  25. package/cjs/services/auth-email.service.js +471 -0
  26. package/cjs/services/authentication.service.js +169 -77
  27. package/cjs/services/branch.service.js +6 -5
  28. package/cjs/services/company-selection-session.service.js +1 -1
  29. package/cjs/services/index.js +1 -0
  30. package/cjs/services/user-permission.service.js +0 -2
  31. package/cjs/services/user.service.js +213 -34
  32. package/cjs/validators/password.validator.js +45 -0
  33. package/config/auth.constants.d.ts +3 -0
  34. package/controllers/authentication.controller.d.ts +13 -9
  35. package/controllers/company-selection.controller.d.ts +6 -2
  36. package/controllers/user.controller.d.ts +33 -0
  37. package/dtos/authentication.dto.d.ts +21 -3
  38. package/dtos/company-branch.dto.d.ts +0 -1
  39. package/dtos/company.dto.d.ts +0 -1
  40. package/dtos/user-permission.dto.d.ts +4 -0
  41. package/dtos/user.dto.d.ts +1 -2
  42. package/entities/index.d.ts +7 -3
  43. package/entities/pending-registration.entity.d.ts +17 -0
  44. package/entities/user-company-permission.entity.d.ts +0 -2
  45. package/entities/user-token.entity.d.ts +15 -0
  46. package/fesm/config/auth.constants.js +6 -2
  47. package/fesm/controllers/authentication.controller.js +221 -12
  48. package/fesm/controllers/branch.controller.js +45 -2
  49. package/fesm/controllers/company-selection.controller.js +28 -21
  50. package/fesm/controllers/company.controller.js +45 -2
  51. package/fesm/controllers/user-permission.controller.js +41 -26
  52. package/fesm/controllers/user.controller.js +214 -10
  53. package/fesm/dtos/authentication.dto.js +106 -14
  54. package/fesm/dtos/user-permission.dto.js +28 -0
  55. package/fesm/dtos/user.dto.js +20 -5
  56. package/fesm/entities/index.js +7 -1
  57. package/fesm/entities/pending-registration.entity.js +115 -0
  58. package/fesm/entities/user-company-permission.entity.js +0 -6
  59. package/fesm/entities/user-token.entity.js +113 -0
  60. package/fesm/guards/auth-throttler.guard.js +43 -0
  61. package/fesm/interceptors/clear-token.interceptor.js +2 -5
  62. package/fesm/interceptors/set-token.interceptor.js +37 -30
  63. package/fesm/interfaces/auth-email-provider.interface.js +38 -0
  64. package/fesm/interfaces/authentication.interface.js +1 -1
  65. package/fesm/interfaces/index.js +2 -0
  66. package/fesm/interfaces/user-enricher.interface.js +26 -0
  67. package/fesm/modules/auth.module.js +10 -22
  68. package/fesm/services/auth-config.service.js +24 -3
  69. package/fesm/services/auth-datasource.provider.js +6 -4
  70. package/fesm/services/auth-email.service.js +420 -0
  71. package/fesm/services/authentication.service.js +169 -77
  72. package/fesm/services/branch.service.js +6 -5
  73. package/fesm/services/company-selection-session.service.js +1 -1
  74. package/fesm/services/index.js +1 -0
  75. package/fesm/services/user-permission.service.js +1 -3
  76. package/fesm/services/user.service.js +215 -36
  77. package/fesm/validators/password.validator.js +48 -0
  78. package/guards/auth-throttler.guard.d.ts +7 -0
  79. package/interceptors/set-token.interceptor.d.ts +1 -0
  80. package/interfaces/auth-email-provider.interface.d.ts +6 -0
  81. package/interfaces/auth-module-options.interface.d.ts +4 -1
  82. package/interfaces/authentication.interface.d.ts +14 -0
  83. package/interfaces/index.d.ts +2 -0
  84. package/interfaces/user-enricher.interface.d.ts +64 -0
  85. package/interfaces/user.interface.d.ts +1 -0
  86. package/modules/auth.module.d.ts +0 -1
  87. package/package.json +4 -4
  88. package/services/auth-config.service.d.ts +5 -1
  89. package/services/auth-email.service.d.ts +51 -0
  90. package/services/authentication.service.d.ts +16 -11
  91. package/services/company-selection-session.service.d.ts +1 -1
  92. package/services/index.d.ts +1 -0
  93. package/services/user-permission.service.d.ts +0 -1
  94. package/services/user.service.d.ts +19 -3
  95. package/validators/password.validator.d.ts +10 -0
@@ -5,10 +5,9 @@ function _ts_decorate(decorators, target, key, desc) {
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  }
7
7
  import { CacheModule, UtilsModule } from '@flusys/nestjs-shared/modules';
8
- import { Module, Scope } from '@nestjs/common';
8
+ import { Module } from '@nestjs/common';
9
9
  import { JwtModule } from '@nestjs/jwt';
10
10
  import { PassportModule } from '@nestjs/passport';
11
- import { getRepositoryToken } from '@nestjs/typeorm';
12
11
  import { AuthConfigService } from '../services/auth-config.service';
13
12
  import { AuthDataSourceProvider } from '../services/auth-datasource.provider';
14
13
  import { AUTH_MODULE_OPTIONS } from '../config/auth.constants';
@@ -17,14 +16,14 @@ import { Company, CompanyBranch, User, UserCompanyPermission } from '../entities
17
16
  import { JwtAuthGuard } from '@flusys/nestjs-shared/guards';
18
17
  import { ClearToken } from '../interceptors/clear-token.interceptor';
19
18
  import { SetToken } from '../interceptors/set-token.interceptor';
20
- import { AuthenticationService, BranchService, CompanySelectionSessionService, CompanyService, UserPermissionService, UserService } from '../services';
19
+ import { AuthEmailService, AuthenticationService, BranchService, CompanySelectionSessionService, CompanyService, UserPermissionService, UserService } from '../services';
21
20
  import { JwtStrategy } from '../strategies/jwt.strategy';
22
21
  export class AuthModule {
23
22
  static forRoot(options) {
24
23
  return this.buildDynamicModule(options);
25
24
  }
26
25
  static forRootAsync(asyncOptions) {
27
- const { global = false, includeController = true, bootstrapAppConfig: { enableCompanyFeature } = {}, imports: externalImports = [] } = asyncOptions;
26
+ const { global = false, includeController = true, bootstrapAppConfig: { enableCompanyFeature } = {}, imports: externalImports = [], providers: additionalProviders = [] } = asyncOptions;
28
27
  const asyncProviders = this.createAsyncProviders(asyncOptions);
29
28
  // Build imports
30
29
  const imports = [
@@ -51,6 +50,7 @@ export class AuthModule {
51
50
  // Build providers
52
51
  const providers = [
53
52
  ...asyncProviders,
53
+ ...additionalProviders,
54
54
  // Config & Infrastructure
55
55
  AuthConfigService,
56
56
  AuthDataSourceProvider,
@@ -58,6 +58,7 @@ export class AuthModule {
58
58
  JwtStrategy,
59
59
  JwtAuthGuard,
60
60
  AuthenticationService,
61
+ AuthEmailService,
61
62
  // Interceptors
62
63
  SetToken,
63
64
  ClearToken,
@@ -77,6 +78,7 @@ export class AuthModule {
77
78
  JwtStrategy,
78
79
  JwtAuthGuard,
79
80
  AuthenticationService,
81
+ AuthEmailService,
80
82
  UserService
81
83
  ];
82
84
  if (enableCompanyFeature) {
@@ -92,7 +94,7 @@ export class AuthModule {
92
94
  };
93
95
  }
94
96
  static buildDynamicModule(options) {
95
- const { bootstrapAppConfig: { enableCompanyFeature } = {}, includeController = true, global = false } = options;
97
+ const { bootstrapAppConfig: { enableCompanyFeature } = {}, includeController = true, global = false, providers: additionalProviders = [] } = options;
96
98
  const imports = [
97
99
  PassportModule.register({
98
100
  defaultStrategy: 'jwt'
@@ -118,6 +120,7 @@ export class AuthModule {
118
120
  provide: AUTH_MODULE_OPTIONS,
119
121
  useValue: options
120
122
  },
123
+ ...additionalProviders,
121
124
  // Config & Infrastructure
122
125
  AuthConfigService,
123
126
  AuthDataSourceProvider,
@@ -125,6 +128,7 @@ export class AuthModule {
125
128
  JwtStrategy,
126
129
  JwtAuthGuard,
127
130
  AuthenticationService,
131
+ AuthEmailService,
128
132
  // Interceptors
129
133
  SetToken,
130
134
  ClearToken,
@@ -143,6 +147,7 @@ export class AuthModule {
143
147
  JwtStrategy,
144
148
  JwtAuthGuard,
145
149
  AuthenticationService,
150
+ AuthEmailService,
146
151
  UserService
147
152
  ];
148
153
  if (enableCompanyFeature) {
@@ -223,23 +228,6 @@ export class AuthModule {
223
228
  }
224
229
  ];
225
230
  }
226
- /**
227
- * Create repository providers that use AuthDataSourceProvider
228
- * This replaces TypeOrmModule.forFeature() functionality
229
- * Note: Must be REQUEST-scoped since AuthDataSourceProvider is REQUEST-scoped
230
- */ static getRepositoryProviders(enableCompanyFeature) {
231
- const entities = this.getEntities(enableCompanyFeature);
232
- return entities.map((entity)=>({
233
- provide: getRepositoryToken(entity),
234
- scope: Scope.REQUEST,
235
- useFactory: async (dataSourceProvider)=>{
236
- return await dataSourceProvider.getRepository(entity);
237
- },
238
- inject: [
239
- AuthDataSourceProvider
240
- ]
241
- }));
242
- }
243
231
  static getEntities(enableCompanyFeature = false) {
244
232
  const coreEntities = [
245
233
  User
@@ -25,7 +25,7 @@ function _ts_param(paramIndex, decorator) {
25
25
  decorator(target, key, paramIndex);
26
26
  };
27
27
  }
28
- import { Inject, Injectable, Optional } from '@nestjs/common';
28
+ import { Inject, Injectable, InternalServerErrorException, Logger, Optional } from '@nestjs/common';
29
29
  import { AuthModuleOptions } from '../interfaces/auth-module-options.interface';
30
30
  import { AUTH_MODULE_OPTIONS } from '../config/auth.constants';
31
31
  export class AuthConfigService {
@@ -42,13 +42,28 @@ export class AuthConfigService {
42
42
  }
43
43
  // JWT Configuration
44
44
  /** Get JWT secret key */ getJwtSecret() {
45
- return this.config.jwtSecret ?? 'default-secret-change-in-production';
45
+ if (!this.config.jwtSecret) {
46
+ throw new InternalServerErrorException('[AuthModule] JWT_SECRET is required - set via environment or module config');
47
+ }
48
+ return this.config.jwtSecret;
46
49
  }
47
50
  /** Get JWT expiration time */ getJwtExpiration() {
48
51
  return this.config.jwtExpiration ?? '1h';
49
52
  }
50
53
  /** Get refresh token secret key */ getRefreshTokenSecret() {
51
- return this.config.refreshTokenSecret ?? this.getJwtSecret();
54
+ if (this.config.refreshTokenSecret) {
55
+ return this.config.refreshTokenSecret;
56
+ }
57
+ // Production: require separate refresh token secret for security
58
+ if (process.env.NODE_ENV === 'production') {
59
+ throw new InternalServerErrorException('[AuthModule] REFRESH_TOKEN_SECRET is required in production - ' + 'using the same secret for access and refresh tokens is a security risk');
60
+ }
61
+ // Development: warn once about fallback to JWT secret
62
+ if (!this.refreshTokenSecretWarned) {
63
+ this.refreshTokenSecretWarned = true;
64
+ this.logger.warn('REFRESH_TOKEN_SECRET not configured - using JWT_SECRET as fallback. ' + 'For better security, configure a separate refresh token secret.');
65
+ }
66
+ return this.config.jwtSecret ?? this.getJwtSecret();
52
67
  }
53
68
  /** Get refresh token expiration time */ getRefreshTokenExpiration() {
54
69
  return this.config.refreshTokenExpiration ?? '7d';
@@ -56,6 +71,10 @@ export class AuthConfigService {
56
71
  /** Get refresh token cookie name */ getRefreshTokenCookieName() {
57
72
  return this.config.refreshTokenCookieName ?? 'fsn_refresh_token';
58
73
  }
74
+ // Frontend Configuration
75
+ /** Get frontend URL for email links */ getFrontendUrl() {
76
+ return this.config.frontendUrl;
77
+ }
59
78
  // Database Configuration
60
79
  /** Get default database config */ getDefaultDatabaseConfig() {
61
80
  return this.config.defaultDatabaseConfig ?? this.config.tenantDefaultDatabaseConfig;
@@ -78,8 +97,10 @@ export class AuthConfigService {
78
97
  };
79
98
  }
80
99
  constructor(injectedOptions){
100
+ _define_property(this, "logger", new Logger(AuthConfigService.name));
81
101
  _define_property(this, "options", void 0);
82
102
  _define_property(this, "config", void 0);
103
+ _define_property(this, "refreshTokenSecretWarned", false);
83
104
  this.options = injectedOptions ?? {
84
105
  global: false,
85
106
  includeController: true
@@ -26,7 +26,7 @@ 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';
@@ -41,7 +41,7 @@ export class AuthDataSourceProvider extends MultiTenantDataSourceService {
41
41
  const lockPromise = (async ()=>{
42
42
  const config = this.getDefaultDatabaseConfig();
43
43
  if (!config) {
44
- throw new Error('Default database config is not available');
44
+ throw new InternalServerErrorException('Default database config is not available');
45
45
  }
46
46
  const ds = await this.createDataSourceFromConfig(config);
47
47
  AuthDataSourceProvider.singleDataSource = ds;
@@ -102,9 +102,11 @@ export class AuthDataSourceProvider extends MultiTenantDataSourceService {
102
102
  // Entity Management
103
103
  /** Get auth entities based on company feature flag */ async getAuthEntities(enableCompanyFeature) {
104
104
  const enable = enableCompanyFeature ?? this.getEnableCompanyFeature();
105
- const { Company, CompanyBranch, User, UserCompanyPermission } = await import('../entities');
105
+ const { Company, CompanyBranch, User, UserCompanyPermission, UserToken, PendingRegistration } = await import('../entities');
106
106
  const coreEntities = [
107
- User
107
+ User,
108
+ UserToken,
109
+ PendingRegistration
108
110
  ];
109
111
  const companyEntities = enable ? [
110
112
  Company,
@@ -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);