otp cooldown

This commit is contained in:
yousef-alkhrissat
2024-08-09 18:44:28 +03:00
parent 3a5c518d11
commit 842e64a4d1
2 changed files with 38 additions and 1 deletions

View File

@ -0,0 +1,4 @@
export function differenceInSeconds(date1: Date, date2: Date): number {
const diffInMilliseconds = date1.getTime() - date2.getTime(); // Difference in milliseconds
return Math.floor(diffInMilliseconds / 1000); // Convert to seconds and round down
}

View File

@ -18,6 +18,8 @@ import { EmailService } from '../../../libs/common/src/util/email.service';
import { OtpType } from '../../../libs/common/src/constants/otp-type.enum';
import { UserEntity } from '../../../libs/common/src/modules/user/entities/user.entity';
import * as argon2 from 'argon2';
import { differenceInSeconds } from '@app/common/helper/differenceInSeconds';
import { LessThan, MoreThan } from 'typeorm';
@Injectable()
export class UserAuthService {
@ -124,7 +126,38 @@ export class UserAuthService {
}
async generateOTP(data: UserOtpDto): Promise<string> {
await this.otpRepository.delete({ email: data.email, type: data.type });
const threeDaysAgo = new Date();
threeDaysAgo.setDate(threeDaysAgo.getDate() - 3);
await this.otpRepository.softDelete({ email: data.email, type: data.type });
await this.otpRepository.delete({
email: data.email,
type: data.type,
createdAt: LessThan(threeDaysAgo),
});
const countOfOtp = await this.otpRepository.count({
withDeleted: true,
where: {
email: data.email,
type: data.type,
createdAt: MoreThan(threeDaysAgo),
},
});
const lastOtp = await this.otpRepository.findOne({
where: { email: data.email, type: data.type },
order: { createdAt: 'DESC' },
withDeleted: true,
});
const cooldown = 30 * Math.pow(2, countOfOtp - 1);
if (lastOtp) {
const now = new Date();
const timeSinceLastOtp = differenceInSeconds(now, lastOtp.createdAt);
if (timeSinceLastOtp < cooldown) {
throw new Error(
`Please wait ${cooldown - timeSinceLastOtp} more seconds before requesting a new OTP.`,
);
}
}
const otpCode = Math.floor(100000 + Math.random() * 900000).toString();
const expiryTime = new Date();
expiryTime.setMinutes(expiryTime.getMinutes() + 1);