From eb7d294471d18c38b3ea59fe57f050cd0f6d49eb Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 21 Aug 2024 14:25:06 +0300 Subject: [PATCH] added cooldown with OTP --- src/auth/controllers/user-auth.controller.ts | 2 +- src/auth/services/user-auth.service.ts | 18 +++++++++++++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/auth/controllers/user-auth.controller.ts b/src/auth/controllers/user-auth.controller.ts index 86f9ce6..e650d39 100644 --- a/src/auth/controllers/user-auth.controller.ts +++ b/src/auth/controllers/user-auth.controller.ts @@ -71,7 +71,7 @@ export class UserAuthController { return { statusCode: HttpStatus.OK, data: { - otp: otpCode, + ...otpCode, }, message: 'Otp Send Successfully', }; diff --git a/src/auth/services/user-auth.service.ts b/src/auth/services/user-auth.service.ts index 9a9c670..7b539e2 100644 --- a/src/auth/services/user-auth.service.ts +++ b/src/auth/services/user-auth.service.ts @@ -140,7 +140,10 @@ export class UserAuthService { return await this.userRepository.findOne({ where: { uuid: id } }); } - async generateOTP(data: UserOtpDto): Promise { + async generateOTP(data: UserOtpDto): Promise<{ + otpCode: string; + cooldown: number; + }> { const otpLimiter = new Date(); otpLimiter.setDate( otpLimiter.getDate() - this.configService.get('OTP_LIMITER'), @@ -178,7 +181,7 @@ export class UserAuthService { order: { createdAt: 'DESC' }, withDeleted: true, }); - const cooldown = 30 * Math.pow(2, countOfOtp - 1); + let cooldown = 30 * Math.pow(2, countOfOtp - 1); if (lastOtp) { const now = new Date(); const timeSinceLastOtp = differenceInSeconds(now, lastOtp.createdAt); @@ -201,10 +204,19 @@ export class UserAuthService { expiryTime, type: data.type, }); + const countOfOtpToReturn = await this.otpRepository.count({ + withDeleted: true, + where: { + email: data.email, + type: data.type, + createdAt: MoreThan(otpLimiter), + }, + }); + cooldown = 30 * Math.pow(2, countOfOtpToReturn - 1); const subject = 'OTP send successfully'; const message = `Your OTP code is ${otpCode}`; this.emailService.sendEmail(data.email, subject, message); - return otpCode; + return { otpCode, cooldown }; } async verifyOTP(data: VerifyOtpDto): Promise {