@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,401 @@
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, 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 Error('User repository not available');
44
+ }
45
+ async getUserTokenRepository() {
46
+ if (this.dataSourceProvider) {
47
+ return this.dataSourceProvider.getRepository(UserToken);
48
+ }
49
+ throw new Error('UserToken repository not available');
50
+ }
51
+ async getPendingRegistrationRepository() {
52
+ if (this.dataSourceProvider) {
53
+ return this.dataSourceProvider.getRepository(PendingRegistration);
54
+ }
55
+ throw new Error('PendingRegistration repository not available');
56
+ }
57
+ isEmailEnabled() {
58
+ return !!this.emailProvider;
59
+ }
60
+ generateToken() {
61
+ return crypto.randomBytes(32).toString('hex');
62
+ }
63
+ // ============================================
64
+ // Pending Registration (New Users)
65
+ // ============================================
66
+ /**
67
+ * Create pending registration - stores data until email verified
68
+ */ async createPendingRegistration(data) {
69
+ if (!this.emailProvider) {
70
+ throw new BadRequestException('Email service is not configured');
71
+ }
72
+ const userRepository = await this.getUserRepository();
73
+ const pendingRepository = await this.getPendingRegistrationRepository();
74
+ // Check if user already exists
75
+ const existingUser = await userRepository.findOne({
76
+ where: {
77
+ email: data.email
78
+ }
79
+ });
80
+ if (existingUser) {
81
+ throw new BadRequestException('Registration failed. Please try again or contact support.');
82
+ }
83
+ // Delete any existing pending registration for this email
84
+ await pendingRepository.delete({
85
+ email: data.email
86
+ });
87
+ // Create pending registration
88
+ const token = this.generateToken();
89
+ const passwordHash = await bcrypt.hash(data.password, BCRYPT_SALT_ROUNDS);
90
+ const expiresAt = new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY);
91
+ const pending = pendingRepository.create({
92
+ email: data.email,
93
+ name: data.name ?? null,
94
+ phone: data.phone ?? null,
95
+ passwordHash,
96
+ token,
97
+ expiresAt,
98
+ companyData: data.companyData ?? null
99
+ });
100
+ await pendingRepository.save(pending);
101
+ // Send verification email
102
+ const verifyUrl = `${data.verifyUrlBase}?token=${token}`;
103
+ try {
104
+ await this.emailProvider.sendVerificationEmail(data.email, token, verifyUrl);
105
+ this.logger.log(`Registration verification email sent to: ${data.email}`);
106
+ } catch (error) {
107
+ this.logger.error(`Failed to send verification email: ${error.message}`);
108
+ throw new BadRequestException('Failed to send verification email. Please try again.');
109
+ }
110
+ return {
111
+ success: true,
112
+ message: 'Please check your email to verify your registration.'
113
+ };
114
+ }
115
+ // ============================================
116
+ // Password Reset (Existing Users)
117
+ // ============================================
118
+ /**
119
+ * Request password reset - sends reset email
120
+ */ async forgotPassword(email, resetUrlBase) {
121
+ if (!this.emailProvider) {
122
+ throw new BadRequestException('Email service is not configured');
123
+ }
124
+ const userRepository = await this.getUserRepository();
125
+ const tokenRepository = await this.getUserTokenRepository();
126
+ const user = await userRepository.findOne({
127
+ where: {
128
+ email
129
+ }
130
+ });
131
+ // Always return success to prevent email enumeration
132
+ if (!user || !user.isActive) {
133
+ this.logger.warn(`Password reset requested for non-existent/inactive email: ${email}`);
134
+ return {
135
+ success: true,
136
+ message: 'If the email exists, a password reset link has been sent.'
137
+ };
138
+ }
139
+ // Invalidate existing password reset tokens for this user
140
+ await tokenRepository.delete({
141
+ userId: user.id,
142
+ type: TokenType.PASSWORD_RESET
143
+ });
144
+ // Create new token
145
+ const token = this.generateToken();
146
+ const userToken = tokenRepository.create({
147
+ userId: user.id,
148
+ type: TokenType.PASSWORD_RESET,
149
+ token,
150
+ expiresAt: new Date(Date.now() + this.PASSWORD_RESET_EXPIRY)
151
+ });
152
+ await tokenRepository.save(userToken);
153
+ // Send email
154
+ const resetUrl = `${resetUrlBase}?token=${token}`;
155
+ try {
156
+ await this.emailProvider.sendPasswordResetEmail(email, token, resetUrl);
157
+ this.logger.log(`Password reset email sent to: ${email}`);
158
+ } catch (error) {
159
+ this.logger.error(`Failed to send password reset email: ${error.message}`);
160
+ }
161
+ return {
162
+ success: true,
163
+ message: 'If the email exists, a password reset link has been sent.'
164
+ };
165
+ }
166
+ /**
167
+ * Reset password using token
168
+ */ async resetPassword(token, newPassword) {
169
+ const userRepository = await this.getUserRepository();
170
+ const tokenRepository = await this.getUserTokenRepository();
171
+ const userToken = await tokenRepository.findOne({
172
+ where: {
173
+ token,
174
+ type: TokenType.PASSWORD_RESET
175
+ }
176
+ });
177
+ if (!userToken) {
178
+ throw new BadRequestException('Invalid or expired reset token');
179
+ }
180
+ if (userToken.expiresAt < new Date()) {
181
+ await tokenRepository.delete({
182
+ id: userToken.id
183
+ });
184
+ throw new BadRequestException('Reset token has expired. Please request a new one.');
185
+ }
186
+ if (userToken.usedAt) {
187
+ throw new BadRequestException('This reset token has already been used.');
188
+ }
189
+ const user = await userRepository.findOne({
190
+ where: {
191
+ id: userToken.userId
192
+ }
193
+ });
194
+ if (!user) {
195
+ throw new BadRequestException('User not found');
196
+ }
197
+ // Update password
198
+ user.password = await bcrypt.hash(newPassword, BCRYPT_SALT_ROUNDS);
199
+ await userRepository.save(user);
200
+ // Mark token as used
201
+ userToken.usedAt = new Date();
202
+ await tokenRepository.save(userToken);
203
+ this.logger.log(`Password reset successful for user: ${user.email}`);
204
+ return {
205
+ success: true,
206
+ message: 'Password has been reset successfully.'
207
+ };
208
+ }
209
+ // ============================================
210
+ // Email Verification
211
+ // ============================================
212
+ /**
213
+ * Verify email using token
214
+ * Handles both pending registration and existing user verification
215
+ */ async verifyEmail(token) {
216
+ const pendingRepository = await this.getPendingRegistrationRepository();
217
+ const userRepository = await this.getUserRepository();
218
+ const tokenRepository = await this.getUserTokenRepository();
219
+ // Check for pending registration first
220
+ const pending = await pendingRepository.findOne({
221
+ where: {
222
+ token
223
+ }
224
+ });
225
+ if (pending) {
226
+ if (pending.expiresAt < new Date()) {
227
+ await pendingRepository.delete({
228
+ id: pending.id
229
+ });
230
+ throw new BadRequestException('Verification token has expired. Please register again.');
231
+ }
232
+ // Delete pending registration (will be consumed by caller to create user)
233
+ await pendingRepository.delete({
234
+ id: pending.id
235
+ });
236
+ return {
237
+ type: 'pending',
238
+ pending
239
+ };
240
+ }
241
+ // Check for existing user email verification token
242
+ const userToken = await tokenRepository.findOne({
243
+ where: {
244
+ token,
245
+ type: TokenType.EMAIL_VERIFICATION
246
+ }
247
+ });
248
+ if (!userToken) {
249
+ throw new BadRequestException('Invalid or expired verification token');
250
+ }
251
+ if (userToken.expiresAt < new Date()) {
252
+ await tokenRepository.delete({
253
+ id: userToken.id
254
+ });
255
+ throw new BadRequestException('Verification token has expired. Please request a new one.');
256
+ }
257
+ if (userToken.usedAt) {
258
+ return {
259
+ type: 'verified',
260
+ message: 'Email has already been verified.'
261
+ };
262
+ }
263
+ const user = await userRepository.findOne({
264
+ where: {
265
+ id: userToken.userId
266
+ }
267
+ });
268
+ if (!user) {
269
+ throw new BadRequestException('User not found');
270
+ }
271
+ // Mark email as verified
272
+ user.emailVerified = true;
273
+ await userRepository.save(user);
274
+ // Mark token as used
275
+ userToken.usedAt = new Date();
276
+ await tokenRepository.save(userToken);
277
+ this.logger.log(`Email verified for user: ${user.email}`);
278
+ return {
279
+ type: 'verified',
280
+ message: 'Email has been verified successfully.'
281
+ };
282
+ }
283
+ /**
284
+ * Resend verification email - handles both pending registrations and existing users
285
+ */ async resendVerificationEmail(email, verifyUrlBase) {
286
+ if (!this.emailProvider) {
287
+ throw new BadRequestException('Email service is not configured');
288
+ }
289
+ const pendingRepository = await this.getPendingRegistrationRepository();
290
+ const userRepository = await this.getUserRepository();
291
+ const tokenRepository = await this.getUserTokenRepository();
292
+ // Check pending registration first
293
+ const pending = await pendingRepository.findOne({
294
+ where: {
295
+ email
296
+ }
297
+ });
298
+ if (pending) {
299
+ const token = this.generateToken();
300
+ pending.token = token;
301
+ pending.expiresAt = new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY);
302
+ await pendingRepository.save(pending);
303
+ const verifyUrl = `${verifyUrlBase}?token=${token}`;
304
+ try {
305
+ await this.emailProvider.sendVerificationEmail(email, token, verifyUrl);
306
+ this.logger.log(`Re-sent registration verification email to: ${email}`);
307
+ } catch (error) {
308
+ this.logger.error(`Failed to resend verification email: ${error.message}`);
309
+ }
310
+ return {
311
+ success: true,
312
+ message: 'If the email requires verification, a link has been sent.'
313
+ };
314
+ }
315
+ // Check existing user
316
+ const user = await userRepository.findOne({
317
+ where: {
318
+ email
319
+ }
320
+ });
321
+ if (!user || user.emailVerified) {
322
+ return {
323
+ success: true,
324
+ message: 'If the email requires verification, a link has been sent.'
325
+ };
326
+ }
327
+ // Invalidate existing tokens and create new one
328
+ await tokenRepository.delete({
329
+ userId: user.id,
330
+ type: TokenType.EMAIL_VERIFICATION
331
+ });
332
+ const token = this.generateToken();
333
+ const userToken = tokenRepository.create({
334
+ userId: user.id,
335
+ type: TokenType.EMAIL_VERIFICATION,
336
+ token,
337
+ expiresAt: new Date(Date.now() + this.EMAIL_VERIFICATION_EXPIRY)
338
+ });
339
+ await tokenRepository.save(userToken);
340
+ const verifyUrl = `${verifyUrlBase}?token=${token}`;
341
+ try {
342
+ await this.emailProvider.sendVerificationEmail(user.email, token, verifyUrl);
343
+ this.logger.log(`Verification email sent to: ${user.email}`);
344
+ } catch (error) {
345
+ this.logger.error(`Failed to send verification email: ${error.message}`);
346
+ }
347
+ return {
348
+ success: true,
349
+ message: 'If the email requires verification, a link has been sent.'
350
+ };
351
+ }
352
+ // ============================================
353
+ // Cleanup
354
+ // ============================================
355
+ /**
356
+ * Clean up expired tokens and pending registrations
357
+ */ async cleanupExpired() {
358
+ const tokenRepository = await this.getUserTokenRepository();
359
+ const pendingRepository = await this.getPendingRegistrationRepository();
360
+ const now = new Date();
361
+ const tokenResult = await tokenRepository.delete({
362
+ expiresAt: LessThan(now)
363
+ });
364
+ const pendingResult = await pendingRepository.delete({
365
+ expiresAt: LessThan(now)
366
+ });
367
+ const deletedTokens = tokenResult.affected ?? 0;
368
+ const deletedPending = pendingResult.affected ?? 0;
369
+ this.logger.log(`Cleaned up ${deletedTokens} expired tokens and ${deletedPending} expired pending registrations`);
370
+ return {
371
+ deletedTokens,
372
+ deletedPending
373
+ };
374
+ }
375
+ constructor(dataSourceProvider, emailProvider){
376
+ _define_property(this, "dataSourceProvider", void 0);
377
+ _define_property(this, "emailProvider", void 0);
378
+ _define_property(this, "logger", void 0);
379
+ _define_property(this, "PASSWORD_RESET_EXPIRY", void 0); // 1 hour
380
+ _define_property(this, "EMAIL_VERIFICATION_EXPIRY", void 0); // 24 hours
381
+ this.dataSourceProvider = dataSourceProvider;
382
+ this.emailProvider = emailProvider;
383
+ this.logger = new Logger(AuthEmailService.name);
384
+ this.PASSWORD_RESET_EXPIRY = 60 * 60 * 1000;
385
+ this.EMAIL_VERIFICATION_EXPIRY = 24 * 60 * 60 * 1000;
386
+ }
387
+ }
388
+ AuthEmailService = _ts_decorate([
389
+ Injectable({
390
+ scope: Scope.REQUEST
391
+ }),
392
+ _ts_param(0, Optional()),
393
+ _ts_param(0, Inject(AuthDataSourceProvider)),
394
+ _ts_param(1, Optional()),
395
+ _ts_param(1, Inject(AUTH_EMAIL_PROVIDER)),
396
+ _ts_metadata("design:type", Function),
397
+ _ts_metadata("design:paramtypes", [
398
+ typeof AuthDataSourceProvider === "undefined" ? Object : AuthDataSourceProvider,
399
+ typeof IAuthEmailProvider === "undefined" ? Object : IAuthEmailProvider
400
+ ])
401
+ ], AuthEmailService);