@flusys/nestjs-auth 1.0.0-beta → 1.1.0-beta

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 (55) hide show
  1. package/cjs/config/auth.constants.js +4 -0
  2. package/cjs/controllers/authentication.controller.js +167 -5
  3. package/cjs/controllers/user.controller.js +151 -0
  4. package/cjs/dtos/authentication.dto.js +106 -3
  5. package/cjs/entities/index.js +5 -1
  6. package/cjs/entities/pending-registration.entity.js +125 -0
  7. package/cjs/entities/user-token.entity.js +129 -0
  8. package/cjs/interfaces/auth-email-provider.interface.js +45 -0
  9. package/cjs/interfaces/index.js +2 -0
  10. package/cjs/interfaces/user-enricher.interface.js +4 -0
  11. package/cjs/modules/auth.module.js +8 -2
  12. package/cjs/services/auth-config.service.js +4 -0
  13. package/cjs/services/auth-datasource.provider.js +4 -2
  14. package/cjs/services/auth-email.service.js +452 -0
  15. package/cjs/services/authentication.service.js +156 -37
  16. package/cjs/services/index.js +1 -0
  17. package/cjs/services/user.service.js +147 -11
  18. package/config/auth.constants.d.ts +1 -0
  19. package/controllers/authentication.controller.d.ts +13 -9
  20. package/controllers/user.controller.d.ts +27 -0
  21. package/dtos/authentication.dto.d.ts +21 -3
  22. package/dtos/user.dto.d.ts +1 -0
  23. package/entities/index.d.ts +7 -3
  24. package/entities/pending-registration.entity.d.ts +17 -0
  25. package/entities/user-token.entity.d.ts +15 -0
  26. package/fesm/config/auth.constants.js +11 -0
  27. package/fesm/controllers/authentication.controller.js +168 -6
  28. package/fesm/controllers/user.controller.js +151 -0
  29. package/fesm/dtos/authentication.dto.js +92 -3
  30. package/fesm/entities/index.js +7 -1
  31. package/fesm/entities/pending-registration.entity.js +115 -0
  32. package/fesm/entities/user-token.entity.js +113 -0
  33. package/fesm/interfaces/auth-email-provider.interface.js +38 -0
  34. package/fesm/interfaces/authentication.interface.js +1 -1
  35. package/fesm/interfaces/index.js +2 -0
  36. package/fesm/interfaces/user-enricher.interface.js +26 -0
  37. package/fesm/modules/auth.module.js +9 -3
  38. package/fesm/services/auth-config.service.js +4 -0
  39. package/fesm/services/auth-datasource.provider.js +4 -2
  40. package/fesm/services/auth-email.service.js +401 -0
  41. package/fesm/services/authentication.service.js +156 -37
  42. package/fesm/services/index.js +1 -0
  43. package/fesm/services/user.service.js +149 -13
  44. package/interfaces/auth-email-provider.interface.d.ts +6 -0
  45. package/interfaces/auth-module-options.interface.d.ts +4 -1
  46. package/interfaces/authentication.interface.d.ts +14 -0
  47. package/interfaces/index.d.ts +2 -0
  48. package/interfaces/user-enricher.interface.d.ts +67 -0
  49. package/interfaces/user.interface.d.ts +1 -0
  50. package/package.json +3 -3
  51. package/services/auth-config.service.d.ts +1 -0
  52. package/services/auth-email.service.d.ts +50 -0
  53. package/services/authentication.service.d.ts +16 -4
  54. package/services/index.d.ts +1 -0
  55. package/services/user.service.d.ts +16 -3
@@ -0,0 +1,452 @@
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 _authdatasourceprovider = require("./auth-datasource.provider");
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 _config = require("../config");
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
+ async getUserRepository() {
91
+ if (this.dataSourceProvider) {
92
+ return this.dataSourceProvider.getRepository(_userentity.User);
93
+ }
94
+ throw new Error('User repository not available');
95
+ }
96
+ async getUserTokenRepository() {
97
+ if (this.dataSourceProvider) {
98
+ return this.dataSourceProvider.getRepository(_usertokenentity.UserToken);
99
+ }
100
+ throw new Error('UserToken repository not available');
101
+ }
102
+ async getPendingRegistrationRepository() {
103
+ if (this.dataSourceProvider) {
104
+ return this.dataSourceProvider.getRepository(_pendingregistrationentity.PendingRegistration);
105
+ }
106
+ throw new Error('PendingRegistration repository not available');
107
+ }
108
+ isEmailEnabled() {
109
+ return !!this.emailProvider;
110
+ }
111
+ generateToken() {
112
+ return _crypto.randomBytes(32).toString('hex');
113
+ }
114
+ // ============================================
115
+ // Pending Registration (New Users)
116
+ // ============================================
117
+ /**
118
+ * Create pending registration - stores data until email verified
119
+ */ async createPendingRegistration(data) {
120
+ if (!this.emailProvider) {
121
+ throw new _common.BadRequestException('Email service is not configured');
122
+ }
123
+ const userRepository = await this.getUserRepository();
124
+ const pendingRepository = await this.getPendingRegistrationRepository();
125
+ // Check if user already exists
126
+ const existingUser = await userRepository.findOne({
127
+ where: {
128
+ email: data.email
129
+ }
130
+ });
131
+ if (existingUser) {
132
+ throw new _common.BadRequestException('Registration failed. Please try again or contact support.');
133
+ }
134
+ // Delete any existing pending registration for this email
135
+ await pendingRepository.delete({
136
+ email: data.email
137
+ });
138
+ // Create pending registration
139
+ const token = this.generateToken();
140
+ const passwordHash = await _bcrypt.hash(data.password, _config.BCRYPT_SALT_ROUNDS);
141
+ const expiresAt = new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY);
142
+ const pending = pendingRepository.create({
143
+ email: data.email,
144
+ name: data.name ?? null,
145
+ phone: data.phone ?? null,
146
+ passwordHash,
147
+ token,
148
+ expiresAt,
149
+ companyData: data.companyData ?? null
150
+ });
151
+ await pendingRepository.save(pending);
152
+ // Send verification email
153
+ const verifyUrl = `${data.verifyUrlBase}?token=${token}`;
154
+ try {
155
+ await this.emailProvider.sendVerificationEmail(data.email, token, verifyUrl);
156
+ this.logger.log(`Registration verification email sent to: ${data.email}`);
157
+ } catch (error) {
158
+ this.logger.error(`Failed to send verification email: ${error.message}`);
159
+ throw new _common.BadRequestException('Failed to send verification email. Please try again.');
160
+ }
161
+ return {
162
+ success: true,
163
+ message: 'Please check your email to verify your registration.'
164
+ };
165
+ }
166
+ // ============================================
167
+ // Password Reset (Existing Users)
168
+ // ============================================
169
+ /**
170
+ * Request password reset - sends reset email
171
+ */ async forgotPassword(email, resetUrlBase) {
172
+ if (!this.emailProvider) {
173
+ throw new _common.BadRequestException('Email service is not configured');
174
+ }
175
+ const userRepository = await this.getUserRepository();
176
+ const tokenRepository = await this.getUserTokenRepository();
177
+ const user = await userRepository.findOne({
178
+ where: {
179
+ email
180
+ }
181
+ });
182
+ // Always return success to prevent email enumeration
183
+ if (!user || !user.isActive) {
184
+ this.logger.warn(`Password reset requested for non-existent/inactive email: ${email}`);
185
+ return {
186
+ success: true,
187
+ message: 'If the email exists, a password reset link has been sent.'
188
+ };
189
+ }
190
+ // Invalidate existing password reset tokens for this user
191
+ await tokenRepository.delete({
192
+ userId: user.id,
193
+ type: _usertokenentity.TokenType.PASSWORD_RESET
194
+ });
195
+ // Create new token
196
+ const token = this.generateToken();
197
+ const userToken = tokenRepository.create({
198
+ userId: user.id,
199
+ type: _usertokenentity.TokenType.PASSWORD_RESET,
200
+ token,
201
+ expiresAt: new Date(Date.now() + this.PASSWORD_RESET_EXPIRY)
202
+ });
203
+ await tokenRepository.save(userToken);
204
+ // Send email
205
+ const resetUrl = `${resetUrlBase}?token=${token}`;
206
+ try {
207
+ await this.emailProvider.sendPasswordResetEmail(email, token, resetUrl);
208
+ this.logger.log(`Password reset email sent to: ${email}`);
209
+ } catch (error) {
210
+ this.logger.error(`Failed to send password reset email: ${error.message}`);
211
+ }
212
+ return {
213
+ success: true,
214
+ message: 'If the email exists, a password reset link has been sent.'
215
+ };
216
+ }
217
+ /**
218
+ * Reset password using token
219
+ */ async resetPassword(token, newPassword) {
220
+ const userRepository = await this.getUserRepository();
221
+ const tokenRepository = await this.getUserTokenRepository();
222
+ const userToken = await tokenRepository.findOne({
223
+ where: {
224
+ token,
225
+ type: _usertokenentity.TokenType.PASSWORD_RESET
226
+ }
227
+ });
228
+ if (!userToken) {
229
+ throw new _common.BadRequestException('Invalid or expired reset token');
230
+ }
231
+ if (userToken.expiresAt < new Date()) {
232
+ await tokenRepository.delete({
233
+ id: userToken.id
234
+ });
235
+ throw new _common.BadRequestException('Reset token has expired. Please request a new one.');
236
+ }
237
+ if (userToken.usedAt) {
238
+ throw new _common.BadRequestException('This reset token has already been used.');
239
+ }
240
+ const user = await userRepository.findOne({
241
+ where: {
242
+ id: userToken.userId
243
+ }
244
+ });
245
+ if (!user) {
246
+ throw new _common.BadRequestException('User not found');
247
+ }
248
+ // Update password
249
+ user.password = await _bcrypt.hash(newPassword, _config.BCRYPT_SALT_ROUNDS);
250
+ await userRepository.save(user);
251
+ // Mark token as used
252
+ userToken.usedAt = new Date();
253
+ await tokenRepository.save(userToken);
254
+ this.logger.log(`Password reset successful for user: ${user.email}`);
255
+ return {
256
+ success: true,
257
+ message: 'Password has been reset successfully.'
258
+ };
259
+ }
260
+ // ============================================
261
+ // Email Verification
262
+ // ============================================
263
+ /**
264
+ * Verify email using token
265
+ * Handles both pending registration and existing user verification
266
+ */ async verifyEmail(token) {
267
+ const pendingRepository = await this.getPendingRegistrationRepository();
268
+ const userRepository = await this.getUserRepository();
269
+ const tokenRepository = await this.getUserTokenRepository();
270
+ // Check for pending registration first
271
+ const pending = await pendingRepository.findOne({
272
+ where: {
273
+ token
274
+ }
275
+ });
276
+ if (pending) {
277
+ if (pending.expiresAt < new Date()) {
278
+ await pendingRepository.delete({
279
+ id: pending.id
280
+ });
281
+ throw new _common.BadRequestException('Verification token has expired. Please register again.');
282
+ }
283
+ // Delete pending registration (will be consumed by caller to create user)
284
+ await pendingRepository.delete({
285
+ id: pending.id
286
+ });
287
+ return {
288
+ type: 'pending',
289
+ pending
290
+ };
291
+ }
292
+ // Check for existing user email verification token
293
+ const userToken = await tokenRepository.findOne({
294
+ where: {
295
+ token,
296
+ type: _usertokenentity.TokenType.EMAIL_VERIFICATION
297
+ }
298
+ });
299
+ if (!userToken) {
300
+ throw new _common.BadRequestException('Invalid or expired verification token');
301
+ }
302
+ if (userToken.expiresAt < new Date()) {
303
+ await tokenRepository.delete({
304
+ id: userToken.id
305
+ });
306
+ throw new _common.BadRequestException('Verification token has expired. Please request a new one.');
307
+ }
308
+ if (userToken.usedAt) {
309
+ return {
310
+ type: 'verified',
311
+ message: 'Email has already been verified.'
312
+ };
313
+ }
314
+ const user = await userRepository.findOne({
315
+ where: {
316
+ id: userToken.userId
317
+ }
318
+ });
319
+ if (!user) {
320
+ throw new _common.BadRequestException('User not found');
321
+ }
322
+ // Mark email as verified
323
+ user.emailVerified = true;
324
+ await userRepository.save(user);
325
+ // Mark token as used
326
+ userToken.usedAt = new Date();
327
+ await tokenRepository.save(userToken);
328
+ this.logger.log(`Email verified for user: ${user.email}`);
329
+ return {
330
+ type: 'verified',
331
+ message: 'Email has been verified successfully.'
332
+ };
333
+ }
334
+ /**
335
+ * Resend verification email - handles both pending registrations and existing users
336
+ */ async resendVerificationEmail(email, verifyUrlBase) {
337
+ if (!this.emailProvider) {
338
+ throw new _common.BadRequestException('Email service is not configured');
339
+ }
340
+ const pendingRepository = await this.getPendingRegistrationRepository();
341
+ const userRepository = await this.getUserRepository();
342
+ const tokenRepository = await this.getUserTokenRepository();
343
+ // Check pending registration first
344
+ const pending = await pendingRepository.findOne({
345
+ where: {
346
+ email
347
+ }
348
+ });
349
+ if (pending) {
350
+ const token = this.generateToken();
351
+ pending.token = token;
352
+ pending.expiresAt = new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY);
353
+ await pendingRepository.save(pending);
354
+ const verifyUrl = `${verifyUrlBase}?token=${token}`;
355
+ try {
356
+ await this.emailProvider.sendVerificationEmail(email, token, verifyUrl);
357
+ this.logger.log(`Re-sent registration verification email to: ${email}`);
358
+ } catch (error) {
359
+ this.logger.error(`Failed to resend verification email: ${error.message}`);
360
+ }
361
+ return {
362
+ success: true,
363
+ message: 'If the email requires verification, a link has been sent.'
364
+ };
365
+ }
366
+ // Check existing user
367
+ const user = await userRepository.findOne({
368
+ where: {
369
+ email
370
+ }
371
+ });
372
+ if (!user || user.emailVerified) {
373
+ return {
374
+ success: true,
375
+ message: 'If the email requires verification, a link has been sent.'
376
+ };
377
+ }
378
+ // Invalidate existing tokens and create new one
379
+ await tokenRepository.delete({
380
+ userId: user.id,
381
+ type: _usertokenentity.TokenType.EMAIL_VERIFICATION
382
+ });
383
+ const token = this.generateToken();
384
+ const userToken = tokenRepository.create({
385
+ userId: user.id,
386
+ type: _usertokenentity.TokenType.EMAIL_VERIFICATION,
387
+ token,
388
+ expiresAt: new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY)
389
+ });
390
+ await tokenRepository.save(userToken);
391
+ const verifyUrl = `${verifyUrlBase}?token=${token}`;
392
+ try {
393
+ await this.emailProvider.sendVerificationEmail(user.email, token, verifyUrl);
394
+ this.logger.log(`Verification email sent to: ${user.email}`);
395
+ } catch (error) {
396
+ this.logger.error(`Failed to send verification email: ${error.message}`);
397
+ }
398
+ return {
399
+ success: true,
400
+ message: 'If the email requires verification, a link has been sent.'
401
+ };
402
+ }
403
+ // ============================================
404
+ // Cleanup
405
+ // ============================================
406
+ /**
407
+ * Clean up expired tokens and pending registrations
408
+ */ async cleanupExpired() {
409
+ const tokenRepository = await this.getUserTokenRepository();
410
+ const pendingRepository = await this.getPendingRegistrationRepository();
411
+ const now = new Date();
412
+ const tokenResult = await tokenRepository.delete({
413
+ expiresAt: (0, _typeorm.LessThan)(now)
414
+ });
415
+ const pendingResult = await pendingRepository.delete({
416
+ expiresAt: (0, _typeorm.LessThan)(now)
417
+ });
418
+ const deletedTokens = tokenResult.affected ?? 0;
419
+ const deletedPending = pendingResult.affected ?? 0;
420
+ this.logger.log(`Cleaned up ${deletedTokens} expired tokens and ${deletedPending} expired pending registrations`);
421
+ return {
422
+ deletedTokens,
423
+ deletedPending
424
+ };
425
+ }
426
+ constructor(dataSourceProvider, emailProvider){
427
+ _define_property(this, "dataSourceProvider", void 0);
428
+ _define_property(this, "emailProvider", void 0);
429
+ _define_property(this, "logger", void 0);
430
+ _define_property(this, "PASSWORD_RESET_EXPIRY", void 0); // 1 hour
431
+ _define_property(this, "EMAIL_VERIFICATION_EXPIRY", void 0); // 24 hours
432
+ this.dataSourceProvider = dataSourceProvider;
433
+ this.emailProvider = emailProvider;
434
+ this.logger = new _common.Logger(AuthEmailService.name);
435
+ this.PASSWORD_RESET_EXPIRY = 60 * 60 * 1000;
436
+ this.EMAIL_VERIFICATION_EXPIRY = 24 * 60 * 60 * 1000;
437
+ }
438
+ };
439
+ AuthEmailService = _ts_decorate([
440
+ (0, _common.Injectable)({
441
+ scope: _common.Scope.REQUEST
442
+ }),
443
+ _ts_param(0, (0, _common.Optional)()),
444
+ _ts_param(0, (0, _common.Inject)(_authdatasourceprovider.AuthDataSourceProvider)),
445
+ _ts_param(1, (0, _common.Optional)()),
446
+ _ts_param(1, (0, _common.Inject)(_interfaces.AUTH_EMAIL_PROVIDER)),
447
+ _ts_metadata("design:type", Function),
448
+ _ts_metadata("design:paramtypes", [
449
+ typeof _authdatasourceprovider.AuthDataSourceProvider === "undefined" ? Object : _authdatasourceprovider.AuthDataSourceProvider,
450
+ typeof _interfaces.IAuthEmailProvider === "undefined" ? Object : _interfaces.IAuthEmailProvider
451
+ ])
452
+ ], AuthEmailService);