@flusys/nestjs-auth 1.0.0-beta → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +590 -473
  2. package/cjs/config/auth.constants.js +12 -0
  3. package/cjs/controllers/authentication.controller.js +365 -24
  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 +82 -154
  8. package/cjs/controllers/user.controller.js +211 -7
  9. package/cjs/docs/auth-swagger.config.js +14 -7
  10. package/cjs/dtos/authentication.dto.js +114 -38
  11. package/cjs/dtos/index.js +0 -1
  12. package/cjs/dtos/user-permission.dto.js +28 -0
  13. package/cjs/dtos/user.dto.js +19 -4
  14. package/cjs/entities/index.js +5 -1
  15. package/cjs/entities/pending-registration.entity.js +125 -0
  16. package/cjs/entities/user-company-permission.entity.js +3 -9
  17. package/cjs/entities/user-token.entity.js +129 -0
  18. package/cjs/interceptors/clear-token.interceptor.js +10 -23
  19. package/cjs/interceptors/set-token.interceptor.js +15 -55
  20. package/cjs/interfaces/auth-email-provider.interface.js +45 -0
  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 +65 -143
  24. package/cjs/services/auth-config.service.js +25 -27
  25. package/cjs/services/auth-datasource.provider.js +13 -23
  26. package/cjs/services/auth-email.service.js +456 -0
  27. package/cjs/services/authentication.service.js +297 -349
  28. package/cjs/services/branch.service.js +9 -4
  29. package/cjs/services/company-selection-session.service.js +1 -1
  30. package/cjs/services/index.js +1 -0
  31. package/cjs/services/user-permission.service.js +43 -73
  32. package/cjs/services/user.service.js +184 -34
  33. package/cjs/strategies/jwt.strategy.js +44 -44
  34. package/cjs/validators/password.validator.js +45 -0
  35. package/config/auth.constants.d.ts +3 -0
  36. package/controllers/authentication.controller.d.ts +16 -10
  37. package/controllers/company-selection.controller.d.ts +6 -2
  38. package/controllers/user-permission.controller.d.ts +5 -4
  39. package/controllers/user.controller.d.ts +33 -0
  40. package/dtos/authentication.dto.d.ts +20 -6
  41. package/dtos/company-branch.dto.d.ts +0 -1
  42. package/dtos/company.dto.d.ts +0 -1
  43. package/dtos/index.d.ts +0 -1
  44. package/dtos/user-permission.dto.d.ts +4 -0
  45. package/dtos/user.dto.d.ts +1 -2
  46. package/entities/index.d.ts +7 -3
  47. package/entities/pending-registration.entity.d.ts +17 -0
  48. package/entities/user-company-permission.entity.d.ts +1 -3
  49. package/entities/user-token.entity.d.ts +15 -0
  50. package/fesm/config/auth.constants.js +6 -2
  51. package/fesm/controllers/authentication.controller.js +368 -27
  52. package/fesm/controllers/branch.controller.js +45 -2
  53. package/fesm/controllers/company-selection.controller.js +28 -21
  54. package/fesm/controllers/company.controller.js +45 -2
  55. package/fesm/controllers/user-permission.controller.js +84 -156
  56. package/fesm/controllers/user.controller.js +214 -10
  57. package/fesm/docs/auth-swagger.config.js +14 -7
  58. package/fesm/dtos/authentication.dto.js +101 -39
  59. package/fesm/dtos/index.js +0 -1
  60. package/fesm/dtos/user-permission.dto.js +28 -0
  61. package/fesm/dtos/user.dto.js +20 -5
  62. package/fesm/entities/index.js +7 -1
  63. package/fesm/entities/pending-registration.entity.js +115 -0
  64. package/fesm/entities/user-company-permission.entity.js +3 -9
  65. package/fesm/entities/user-token.entity.js +113 -0
  66. package/fesm/interceptors/clear-token.interceptor.js +9 -22
  67. package/fesm/interceptors/set-token.interceptor.js +14 -54
  68. package/fesm/interfaces/auth-email-provider.interface.js +38 -0
  69. package/fesm/interfaces/authentication.interface.js +1 -1
  70. package/fesm/interfaces/index.js +2 -0
  71. package/fesm/interfaces/user-enricher.interface.js +26 -0
  72. package/fesm/modules/auth.module.js +67 -145
  73. package/fesm/services/auth-config.service.js +26 -28
  74. package/fesm/services/auth-datasource.provider.js +14 -24
  75. package/fesm/services/auth-email.service.js +405 -0
  76. package/fesm/services/authentication.service.js +297 -349
  77. package/fesm/services/branch.service.js +9 -4
  78. package/fesm/services/company-selection-session.service.js +1 -1
  79. package/fesm/services/index.js +1 -0
  80. package/fesm/services/user-permission.service.js +44 -74
  81. package/fesm/services/user.service.js +186 -36
  82. package/fesm/strategies/jwt.strategy.js +44 -44
  83. package/fesm/validators/password.validator.js +48 -0
  84. package/interceptors/clear-token.interceptor.d.ts +0 -1
  85. package/interceptors/set-token.interceptor.d.ts +1 -1
  86. package/interfaces/auth-email-provider.interface.d.ts +6 -0
  87. package/interfaces/auth-module-options.interface.d.ts +4 -1
  88. package/interfaces/authentication.interface.d.ts +13 -3
  89. package/interfaces/index.d.ts +2 -0
  90. package/interfaces/user-enricher.interface.d.ts +64 -0
  91. package/interfaces/user.interface.d.ts +1 -0
  92. package/modules/auth.module.d.ts +6 -3
  93. package/package.json +4 -4
  94. package/services/auth-config.service.d.ts +7 -8
  95. package/services/auth-datasource.provider.d.ts +2 -4
  96. package/services/auth-email.service.d.ts +54 -0
  97. package/services/authentication.service.d.ts +27 -16
  98. package/services/company-selection-session.service.d.ts +1 -1
  99. package/services/index.d.ts +1 -0
  100. package/services/user-permission.service.d.ts +6 -9
  101. package/services/user.service.d.ts +19 -3
  102. package/strategies/jwt.strategy.d.ts +4 -1
  103. package/validators/password.validator.d.ts +10 -0
  104. package/cjs/dtos/user-company-permission.dto.js +0 -110
  105. package/dtos/user-company-permission.dto.d.ts +0 -10
  106. package/fesm/dtos/user-company-permission.dto.js +0 -98
@@ -9,8 +9,8 @@ Object.defineProperty(exports, "AuthConfigService", {
9
9
  }
10
10
  });
11
11
  const _common = require("@nestjs/common");
12
- const _authmoduleoptionsinterface = require("../interfaces/auth-module-options.interface");
13
12
  const _authconstants = require("../config/auth.constants");
13
+ const _authmoduleoptionsinterface = require("../interfaces/auth-module-options.interface");
14
14
  function _define_property(obj, key, value) {
15
15
  if (key in obj) {
16
16
  Object.defineProperty(obj, key, {
@@ -39,26 +39,39 @@ function _ts_param(paramIndex, decorator) {
39
39
  };
40
40
  }
41
41
  let AuthConfigService = class AuthConfigService {
42
- // Database Mode
43
- /** Get database mode (single or multi-tenant) */ getDatabaseMode() {
42
+ // Database Mode (required by IModuleConfigService)
43
+ getDatabaseMode() {
44
44
  return this.options.bootstrapAppConfig?.databaseMode ?? 'single';
45
45
  }
46
- /** Check if running in multi-tenant mode */ isMultiTenant() {
46
+ isMultiTenant() {
47
47
  return this.getDatabaseMode() === 'multi-tenant';
48
48
  }
49
49
  // Feature Flags
50
- /** Check if company feature is enabled */ isCompanyFeatureEnabled() {
50
+ isCompanyFeatureEnabled() {
51
51
  return this.options.bootstrapAppConfig?.enableCompanyFeature ?? false;
52
52
  }
53
53
  // JWT Configuration
54
54
  /** Get JWT secret key */ getJwtSecret() {
55
- return this.config.jwtSecret ?? 'default-secret-change-in-production';
55
+ if (!this.config.jwtSecret) {
56
+ throw new _common.InternalServerErrorException('[AuthModule] JWT_SECRET is required - set via environment or module config');
57
+ }
58
+ return this.config.jwtSecret;
56
59
  }
57
60
  /** Get JWT expiration time */ getJwtExpiration() {
58
61
  return this.config.jwtExpiration ?? '1h';
59
62
  }
60
63
  /** Get refresh token secret key */ getRefreshTokenSecret() {
61
- return this.config.refreshTokenSecret ?? this.getJwtSecret();
64
+ if (this.config.refreshTokenSecret) {
65
+ return this.config.refreshTokenSecret;
66
+ }
67
+ if (process.env.NODE_ENV === 'production') {
68
+ throw new _common.InternalServerErrorException('[AuthModule] REFRESH_TOKEN_SECRET is required in production - ' + 'using the same secret for access and refresh tokens is a security risk');
69
+ }
70
+ if (!this.refreshTokenSecretWarned) {
71
+ this.refreshTokenSecretWarned = true;
72
+ this.logger.warn('REFRESH_TOKEN_SECRET not configured - using JWT_SECRET as fallback. ' + 'For better security, configure a separate refresh token secret.');
73
+ }
74
+ return this.getJwtSecret();
62
75
  }
63
76
  /** Get refresh token expiration time */ getRefreshTokenExpiration() {
64
77
  return this.config.refreshTokenExpiration ?? '7d';
@@ -66,30 +79,15 @@ let AuthConfigService = class AuthConfigService {
66
79
  /** Get refresh token cookie name */ getRefreshTokenCookieName() {
67
80
  return this.config.refreshTokenCookieName ?? 'fsn_refresh_token';
68
81
  }
69
- // Database Configuration
70
- /** Get default database config */ getDefaultDatabaseConfig() {
71
- return this.config.defaultDatabaseConfig ?? this.config.tenantDefaultDatabaseConfig;
72
- }
73
- /** Get tenant default database config (for multi-tenant) */ getTenantDefaultDatabaseConfig() {
74
- return this.config.tenantDefaultDatabaseConfig;
75
- }
76
- /** Get registered tenants */ getTenants() {
77
- return this.config.tenants ?? [];
78
- }
79
- // Raw Options
80
- /** Get full module options */ getOptions() {
81
- return {
82
- ...this.options
83
- };
84
- }
85
- /** Get runtime config */ getConfig() {
86
- return {
87
- ...this.config
88
- };
82
+ // Frontend Configuration
83
+ /** Get frontend URL for email links */ getFrontendUrl() {
84
+ return this.config.frontendUrl;
89
85
  }
90
86
  constructor(injectedOptions){
87
+ _define_property(this, "logger", new _common.Logger(AuthConfigService.name));
91
88
  _define_property(this, "options", void 0);
92
89
  _define_property(this, "config", void 0);
90
+ _define_property(this, "refreshTokenSecretWarned", false);
93
91
  this.options = injectedOptions ?? {
94
92
  global: false,
95
93
  includeController: true
@@ -92,7 +92,7 @@ let AuthDataSourceProvider = class AuthDataSourceProvider extends _modules.Multi
92
92
  const lockPromise = (async ()=>{
93
93
  const config = this.getDefaultDatabaseConfig();
94
94
  if (!config) {
95
- throw new Error('Default database config is not available');
95
+ throw new _common.InternalServerErrorException('Default database config is not available');
96
96
  }
97
97
  const ds = await this.createDataSourceFromConfig(config);
98
98
  AuthDataSourceProvider.singleDataSource = ds;
@@ -141,38 +141,28 @@ let AuthDataSourceProvider = class AuthDataSourceProvider extends _modules.Multi
141
141
  };
142
142
  }
143
143
  // Feature Flags
144
- /** Get global enable company feature flag */ getEnableCompanyFeature() {
145
- return this.authOptions.bootstrapAppConfig?.enableCompanyFeature ?? false;
146
- }
147
- /** Get enable company feature for specific tenant. Falls back to global setting. */ getEnableCompanyFeatureForTenant(tenant) {
148
- return tenant?.enableCompanyFeature ?? this.getEnableCompanyFeature();
149
- }
150
- /** Get enable company feature for current request context */ getEnableCompanyFeatureForCurrentTenant() {
151
- return this.getEnableCompanyFeatureForTenant(this.getCurrentTenant() ?? undefined);
144
+ /** Check if company feature is enabled (tenant-specific or global fallback) */ isCompanyFeatureEnabled(tenant) {
145
+ const effectiveTenant = tenant ?? this.getCurrentTenant();
146
+ return effectiveTenant?.enableCompanyFeature ?? this.authOptions.bootstrapAppConfig?.enableCompanyFeature ?? false;
152
147
  }
153
148
  // Entity Management
154
- /** Get auth entities based on company feature flag */ async getAuthEntities(enableCompanyFeature) {
155
- const enable = enableCompanyFeature ?? this.getEnableCompanyFeature();
156
- const { Company, CompanyBranch, User, UserCompanyPermission } = await Promise.resolve().then(()=>/*#__PURE__*/ _interop_require_wildcard(require("../entities")));
149
+ /** Get auth entities based on company feature flag */ async getAuthEntities() {
150
+ const { Company, CompanyBranch, User, UserCompanyPermission, UserToken, PendingRegistration } = await Promise.resolve().then(()=>/*#__PURE__*/ _interop_require_wildcard(require("../entities")));
157
151
  const coreEntities = [
158
- User
152
+ User,
153
+ UserToken,
154
+ PendingRegistration
159
155
  ];
160
- const companyEntities = enable ? [
156
+ return this.isCompanyFeatureEnabled() ? [
157
+ ...coreEntities,
161
158
  Company,
162
159
  CompanyBranch,
163
160
  UserCompanyPermission
164
- ] : [];
165
- return [
166
- ...coreEntities,
167
- ...companyEntities
168
- ];
161
+ ] : coreEntities;
169
162
  }
170
163
  // Overrides
171
164
  /** Override to dynamically set entities based on tenant config */ async createDataSourceFromConfig(config) {
172
- const currentTenant = this.getCurrentTenant();
173
- const enableCompanyFeature = this.getEnableCompanyFeatureForTenant(currentTenant ?? undefined);
174
- const entities = await this.getAuthEntities(enableCompanyFeature);
175
- return super.createDataSourceFromConfig(config, entities);
165
+ return super.createDataSourceFromConfig(config, await this.getAuthEntities());
176
166
  }
177
167
  constructor(authOptions, request){
178
168
  super(AuthDataSourceProvider.buildParentOptions(authOptions), request), _define_property(this, "authOptions", void 0), _define_property(this, "logger", void 0), this.authOptions = authOptions, this.logger = new _common.Logger(AuthDataSourceProvider.name);
@@ -0,0 +1,456 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "AuthEmailService", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return AuthEmailService;
9
+ }
10
+ });
11
+ const _common = require("@nestjs/common");
12
+ const _bcrypt = /*#__PURE__*/ _interop_require_wildcard(require("bcrypt"));
13
+ const _crypto = /*#__PURE__*/ _interop_require_wildcard(require("crypto"));
14
+ const _typeorm = require("typeorm");
15
+ const _config = require("../config");
16
+ const _pendingregistrationentity = require("../entities/pending-registration.entity");
17
+ const _usertokenentity = require("../entities/user-token.entity");
18
+ const _userentity = require("../entities/user.entity");
19
+ const _interfaces = require("../interfaces");
20
+ const _authdatasourceprovider = require("./auth-datasource.provider");
21
+ function _define_property(obj, key, value) {
22
+ if (key in obj) {
23
+ Object.defineProperty(obj, key, {
24
+ value: value,
25
+ enumerable: true,
26
+ configurable: true,
27
+ writable: true
28
+ });
29
+ } else {
30
+ obj[key] = value;
31
+ }
32
+ return obj;
33
+ }
34
+ function _getRequireWildcardCache(nodeInterop) {
35
+ if (typeof WeakMap !== "function") return null;
36
+ var cacheBabelInterop = new WeakMap();
37
+ var cacheNodeInterop = new WeakMap();
38
+ return (_getRequireWildcardCache = function(nodeInterop) {
39
+ return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
40
+ })(nodeInterop);
41
+ }
42
+ function _interop_require_wildcard(obj, nodeInterop) {
43
+ if (!nodeInterop && obj && obj.__esModule) {
44
+ return obj;
45
+ }
46
+ if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
47
+ return {
48
+ default: obj
49
+ };
50
+ }
51
+ var cache = _getRequireWildcardCache(nodeInterop);
52
+ if (cache && cache.has(obj)) {
53
+ return cache.get(obj);
54
+ }
55
+ var newObj = {
56
+ __proto__: null
57
+ };
58
+ var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
59
+ for(var key in obj){
60
+ if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
61
+ var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
62
+ if (desc && (desc.get || desc.set)) {
63
+ Object.defineProperty(newObj, key, desc);
64
+ } else {
65
+ newObj[key] = obj[key];
66
+ }
67
+ }
68
+ }
69
+ newObj.default = obj;
70
+ if (cache) {
71
+ cache.set(obj, newObj);
72
+ }
73
+ return newObj;
74
+ }
75
+ function _ts_decorate(decorators, target, key, desc) {
76
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
77
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
78
+ 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;
79
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
80
+ }
81
+ function _ts_metadata(k, v) {
82
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
83
+ }
84
+ function _ts_param(paramIndex, decorator) {
85
+ return function(target, key) {
86
+ decorator(target, key, paramIndex);
87
+ };
88
+ }
89
+ let AuthEmailService = class AuthEmailService {
90
+ isEmailEnabled() {
91
+ return !!this.emailProvider;
92
+ }
93
+ // ============================================
94
+ // Private Helpers
95
+ // ============================================
96
+ async getRepository(entity) {
97
+ if (!this.dataSourceProvider) {
98
+ throw new _common.InternalServerErrorException(`${String(entity)} repository not available`);
99
+ }
100
+ return this.dataSourceProvider.getRepository(entity);
101
+ }
102
+ generateToken() {
103
+ return _crypto.randomBytes(32).toString('hex');
104
+ }
105
+ /** Hash token for secure storage - prevents token theft if database is compromised */ hashToken(token) {
106
+ return _crypto.createHash('sha256').update(token).digest('hex');
107
+ }
108
+ getErrorMessage(error) {
109
+ return error instanceof Error ? error.message : 'Unknown error';
110
+ }
111
+ assertEmailEnabled() {
112
+ if (!this.emailProvider) {
113
+ throw new _common.BadRequestException('Email service is not configured');
114
+ }
115
+ }
116
+ async sendVerificationEmailSafe(email, token, verifyUrl, logContext) {
117
+ try {
118
+ await this.emailProvider.sendVerificationEmail(email, token, verifyUrl);
119
+ this.logger.log(`${logContext} verification email sent to: ${email}`);
120
+ } catch (error) {
121
+ this.logger.error(`Failed to send verification email: ${this.getErrorMessage(error)}`);
122
+ throw new _common.BadRequestException('Failed to send verification email. Please try again.');
123
+ }
124
+ }
125
+ validateTokenNotExpiredOrUsed(token, expiredMessage, usedMessage) {
126
+ if (token.expiresAt < new Date()) {
127
+ throw new _common.BadRequestException(expiredMessage);
128
+ }
129
+ if (usedMessage && token.usedAt) {
130
+ throw new _common.BadRequestException(usedMessage);
131
+ }
132
+ }
133
+ // ============================================
134
+ // Pending Registration (New Users)
135
+ // ============================================
136
+ async hasPendingRegistration(email) {
137
+ if (!this.isEmailEnabled()) return false;
138
+ const pendingRepository = await this.getRepository(_pendingregistrationentity.PendingRegistration);
139
+ const pending = await pendingRepository.findOne({
140
+ where: {
141
+ email
142
+ }
143
+ });
144
+ return !!pending && pending.expiresAt > new Date();
145
+ }
146
+ async createPendingRegistration(data) {
147
+ this.assertEmailEnabled();
148
+ const userRepository = await this.getRepository(_userentity.User);
149
+ const pendingRepository = await this.getRepository(_pendingregistrationentity.PendingRegistration);
150
+ // Check if user already exists
151
+ const existingUser = await userRepository.findOne({
152
+ where: {
153
+ email: data.email
154
+ }
155
+ });
156
+ if (existingUser) {
157
+ throw new _common.BadRequestException('Registration failed. Please try again or contact support.');
158
+ }
159
+ // Delete any existing pending registration for this email
160
+ await pendingRepository.delete({
161
+ email: data.email
162
+ });
163
+ // Create pending registration with hashed token for secure storage
164
+ const token = this.generateToken();
165
+ const tokenHash = this.hashToken(token);
166
+ const passwordHash = await _bcrypt.hash(data.password, _config.BCRYPT_SALT_ROUNDS);
167
+ const expiresAt = new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY);
168
+ const pending = pendingRepository.create({
169
+ email: data.email,
170
+ name: data.name ?? null,
171
+ phone: data.phone ?? null,
172
+ passwordHash,
173
+ token: tokenHash,
174
+ expiresAt,
175
+ companyData: data.companyData ?? null
176
+ });
177
+ await pendingRepository.save(pending);
178
+ // Send verification email with raw token (user receives this)
179
+ const verifyUrl = `${data.verifyUrlBase}?token=${token}`;
180
+ await this.sendVerificationEmailSafe(data.email, token, verifyUrl, 'Registration');
181
+ return {
182
+ success: true,
183
+ message: 'Please check your email to verify your registration.'
184
+ };
185
+ }
186
+ // ============================================
187
+ // Password Reset (Existing Users)
188
+ // ============================================
189
+ /**
190
+ * Request password reset - sends reset email
191
+ */ async forgotPassword(email, resetUrlBase) {
192
+ this.assertEmailEnabled();
193
+ const userRepository = await this.getRepository(_userentity.User);
194
+ const tokenRepository = await this.getRepository(_usertokenentity.UserToken);
195
+ const user = await userRepository.findOne({
196
+ where: {
197
+ email
198
+ }
199
+ });
200
+ // Always return success to prevent email enumeration
201
+ if (!user || !user.isActive) {
202
+ this.logger.warn(`Password reset requested for non-existent/inactive email: ${email}`);
203
+ return {
204
+ success: true,
205
+ message: 'If the email exists, a password reset link has been sent.'
206
+ };
207
+ }
208
+ // Invalidate existing password reset tokens for this user
209
+ await tokenRepository.delete({
210
+ userId: user.id,
211
+ type: _usertokenentity.TokenType.PASSWORD_RESET
212
+ });
213
+ // Create new token with hashed storage
214
+ const token = this.generateToken();
215
+ const tokenHash = this.hashToken(token);
216
+ const userToken = tokenRepository.create({
217
+ userId: user.id,
218
+ type: _usertokenentity.TokenType.PASSWORD_RESET,
219
+ token: tokenHash,
220
+ expiresAt: new Date(Date.now() + this.PASSWORD_RESET_EXPIRY)
221
+ });
222
+ await tokenRepository.save(userToken);
223
+ // Send email with raw token
224
+ const resetUrl = `${resetUrlBase}?token=${token}`;
225
+ try {
226
+ await this.emailProvider.sendPasswordResetEmail(email, token, resetUrl);
227
+ this.logger.log(`Password reset email sent to: ${email}`);
228
+ } catch (error) {
229
+ this.logger.error(`Failed to send password reset email: ${this.getErrorMessage(error)}`);
230
+ throw new _common.BadRequestException('Failed to process request. Please try again later.');
231
+ }
232
+ return {
233
+ success: true,
234
+ message: 'If the email exists, a password reset link has been sent.'
235
+ };
236
+ }
237
+ /**
238
+ * Reset password using token
239
+ */ async resetPassword(token, newPassword) {
240
+ const userRepository = await this.getRepository(_userentity.User);
241
+ const tokenRepository = await this.getRepository(_usertokenentity.UserToken);
242
+ // Hash the incoming token to compare with stored hash
243
+ const tokenHash = this.hashToken(token);
244
+ const userToken = await tokenRepository.findOne({
245
+ where: {
246
+ token: tokenHash,
247
+ type: _usertokenentity.TokenType.PASSWORD_RESET
248
+ }
249
+ });
250
+ if (!userToken) {
251
+ throw new _common.BadRequestException('Invalid or expired reset token');
252
+ }
253
+ this.validateTokenNotExpiredOrUsed(userToken, 'Reset token has expired. Please request a new one.', 'This reset token has already been used.');
254
+ const user = await userRepository.findOne({
255
+ where: {
256
+ id: userToken.userId
257
+ }
258
+ });
259
+ if (!user) {
260
+ throw new _common.BadRequestException('User not found');
261
+ }
262
+ // Update password
263
+ user.password = await _bcrypt.hash(newPassword, _config.BCRYPT_SALT_ROUNDS);
264
+ await userRepository.save(user);
265
+ // Mark token as used
266
+ userToken.usedAt = new Date();
267
+ await tokenRepository.save(userToken);
268
+ this.logger.log(`Password reset successful for user: ${user.email}`);
269
+ return {
270
+ success: true,
271
+ message: 'Password has been reset successfully.'
272
+ };
273
+ }
274
+ // ============================================
275
+ // Email Verification
276
+ // ============================================
277
+ /**
278
+ * Verify email using token
279
+ * Handles both pending registration and existing user verification
280
+ */ async verifyEmail(token) {
281
+ const pendingRepository = await this.getRepository(_pendingregistrationentity.PendingRegistration);
282
+ const userRepository = await this.getRepository(_userentity.User);
283
+ const tokenRepository = await this.getRepository(_usertokenentity.UserToken);
284
+ // Hash the incoming token to compare with stored hash
285
+ const tokenHash = this.hashToken(token);
286
+ // Check for pending registration first
287
+ const pending = await pendingRepository.findOne({
288
+ where: {
289
+ token: tokenHash
290
+ }
291
+ });
292
+ if (pending) {
293
+ if (pending.expiresAt < new Date()) {
294
+ await pendingRepository.delete({
295
+ id: pending.id
296
+ });
297
+ throw new _common.BadRequestException('Verification token has expired. Please register again.');
298
+ }
299
+ // Delete pending registration (will be consumed by caller to create user)
300
+ await pendingRepository.delete({
301
+ id: pending.id
302
+ });
303
+ return {
304
+ type: 'pending',
305
+ pending
306
+ };
307
+ }
308
+ // Check for existing user email verification token
309
+ const userToken = await tokenRepository.findOne({
310
+ where: {
311
+ token: tokenHash,
312
+ type: _usertokenentity.TokenType.EMAIL_VERIFICATION
313
+ }
314
+ });
315
+ if (!userToken) {
316
+ throw new _common.BadRequestException('Invalid or expired verification token');
317
+ }
318
+ if (userToken.expiresAt < new Date()) {
319
+ await tokenRepository.delete({
320
+ id: userToken.id
321
+ });
322
+ throw new _common.BadRequestException('Verification token has expired. Please request a new one.');
323
+ }
324
+ if (userToken.usedAt) {
325
+ return {
326
+ type: 'verified',
327
+ message: 'Email has already been verified.'
328
+ };
329
+ }
330
+ const user = await userRepository.findOne({
331
+ where: {
332
+ id: userToken.userId
333
+ }
334
+ });
335
+ if (!user) {
336
+ throw new _common.BadRequestException('User not found');
337
+ }
338
+ // Mark email as verified
339
+ user.emailVerified = true;
340
+ await userRepository.save(user);
341
+ // Mark token as used
342
+ userToken.usedAt = new Date();
343
+ await tokenRepository.save(userToken);
344
+ this.logger.log(`Email verified for user: ${user.email}`);
345
+ return {
346
+ type: 'verified',
347
+ message: 'Email has been verified successfully.'
348
+ };
349
+ }
350
+ /**
351
+ * Resend verification email - handles both pending registrations and existing users
352
+ */ async resendVerificationEmail(email, verifyUrlBase) {
353
+ this.assertEmailEnabled();
354
+ const pendingRepository = await this.getRepository(_pendingregistrationentity.PendingRegistration);
355
+ const userRepository = await this.getRepository(_userentity.User);
356
+ const tokenRepository = await this.getRepository(_usertokenentity.UserToken);
357
+ // Check pending registration first
358
+ const pending = await pendingRepository.findOne({
359
+ where: {
360
+ email
361
+ }
362
+ });
363
+ if (pending) {
364
+ const token = this.generateToken();
365
+ pending.token = this.hashToken(token);
366
+ pending.expiresAt = new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY);
367
+ await pendingRepository.save(pending);
368
+ const verifyUrl = `${verifyUrlBase}?token=${token}`;
369
+ await this.sendVerificationEmailSafe(email, token, verifyUrl, 'Re-sent registration');
370
+ return {
371
+ success: true,
372
+ message: 'If the email requires verification, a link has been sent.'
373
+ };
374
+ }
375
+ // Check existing user
376
+ const user = await userRepository.findOne({
377
+ where: {
378
+ email
379
+ }
380
+ });
381
+ if (!user || user.emailVerified) {
382
+ return {
383
+ success: true,
384
+ message: 'If the email requires verification, a link has been sent.'
385
+ };
386
+ }
387
+ // Invalidate existing tokens and create new one
388
+ await tokenRepository.delete({
389
+ userId: user.id,
390
+ type: _usertokenentity.TokenType.EMAIL_VERIFICATION
391
+ });
392
+ const token = this.generateToken();
393
+ const userToken = tokenRepository.create({
394
+ userId: user.id,
395
+ type: _usertokenentity.TokenType.EMAIL_VERIFICATION,
396
+ token: this.hashToken(token),
397
+ expiresAt: new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY)
398
+ });
399
+ await tokenRepository.save(userToken);
400
+ const verifyUrl = `${verifyUrlBase}?token=${token}`;
401
+ await this.sendVerificationEmailSafe(user.email, token, verifyUrl, 'Verification');
402
+ return {
403
+ success: true,
404
+ message: 'If the email requires verification, a link has been sent.'
405
+ };
406
+ }
407
+ // ============================================
408
+ // Cleanup
409
+ // ============================================
410
+ /**
411
+ * Clean up expired tokens and pending registrations
412
+ */ async cleanupExpired() {
413
+ const tokenRepository = await this.getRepository(_usertokenentity.UserToken);
414
+ const pendingRepository = await this.getRepository(_pendingregistrationentity.PendingRegistration);
415
+ const now = new Date();
416
+ const tokenResult = await tokenRepository.delete({
417
+ expiresAt: (0, _typeorm.LessThan)(now)
418
+ });
419
+ const pendingResult = await pendingRepository.delete({
420
+ expiresAt: (0, _typeorm.LessThan)(now)
421
+ });
422
+ const deletedTokens = tokenResult.affected ?? 0;
423
+ const deletedPending = pendingResult.affected ?? 0;
424
+ this.logger.log(`Cleaned up ${deletedTokens} expired tokens and ${deletedPending} expired pending registrations`);
425
+ return {
426
+ deletedTokens,
427
+ deletedPending
428
+ };
429
+ }
430
+ constructor(dataSourceProvider, emailProvider){
431
+ _define_property(this, "dataSourceProvider", void 0);
432
+ _define_property(this, "emailProvider", void 0);
433
+ _define_property(this, "logger", void 0);
434
+ _define_property(this, "PASSWORD_RESET_EXPIRY", void 0); // 1 hour
435
+ _define_property(this, "EMAIL_VERIFICATION_EXPIRY", void 0); // 24 hours
436
+ this.dataSourceProvider = dataSourceProvider;
437
+ this.emailProvider = emailProvider;
438
+ this.logger = new _common.Logger(AuthEmailService.name);
439
+ this.PASSWORD_RESET_EXPIRY = 60 * 60 * 1000;
440
+ this.EMAIL_VERIFICATION_EXPIRY = 24 * 60 * 60 * 1000;
441
+ }
442
+ };
443
+ AuthEmailService = _ts_decorate([
444
+ (0, _common.Injectable)({
445
+ scope: _common.Scope.REQUEST
446
+ }),
447
+ _ts_param(0, (0, _common.Optional)()),
448
+ _ts_param(0, (0, _common.Inject)(_authdatasourceprovider.AuthDataSourceProvider)),
449
+ _ts_param(1, (0, _common.Optional)()),
450
+ _ts_param(1, (0, _common.Inject)(_interfaces.AUTH_EMAIL_PROVIDER)),
451
+ _ts_metadata("design:type", Function),
452
+ _ts_metadata("design:paramtypes", [
453
+ typeof _authdatasourceprovider.AuthDataSourceProvider === "undefined" ? Object : _authdatasourceprovider.AuthDataSourceProvider,
454
+ typeof _interfaces.IAuthEmailProvider === "undefined" ? Object : _interfaces.IAuthEmailProvider
455
+ ])
456
+ ], AuthEmailService);