diff --git a/src/services/identity/UsersService.ts b/src/services/identity/UsersService.ts index 7e621291b..761c3a57e 100644 --- a/src/services/identity/UsersService.ts +++ b/src/services/identity/UsersService.ts @@ -187,23 +187,16 @@ class UsersService { } async sendEmailOtp(email: string) { - const parsedEmail = email.toLowerCase() + const normalizedEmail = email.toLowerCase() const { otp, hashedOtp } = await this.otpService.generateLoginOtpWithHash() // Reset attempts to login - const otpEntry = await this.otpRepository.findOne({ - where: { email: parsedEmail }, + await this.otpRepository.upsert({ + email: normalizedEmail, + hashedOtp, + attempts: 0, + expiresAt: this.getOtpExpiry(), }) - if (!otpEntry) { - // create new entry - await this.createOtpEntry(parsedEmail, OtpType.Email, hashedOtp) - } else { - await otpEntry?.update({ - hashedOtp, - attempts: 0, - expiresAt: this.getOtpExpiry(), - }) - } const subject = "One-Time Password (OTP) for IsomerCMS" const html = `

Your OTP is ${otp}. It will expire in ${milliSecondsToMinutes( @@ -211,21 +204,19 @@ class UsersService { )} minutes. Please use this to verify your email address.

If your OTP does not work, please request for a new OTP.

IsomerCMS Support Team

` - await this.mailer.sendMail(parsedEmail, subject, html) + await this.mailer.sendMail(normalizedEmail, subject, html) } async sendSmsOtp(mobileNumber: string) { const { otp, hashedOtp } = await this.otpService.generateLoginOtpWithHash() // Reset attempts to login - const otpEntry = await this.otpRepository.findOne({ - where: { mobileNumber }, + await this.otpRepository.upsert({ + mobileNumber, + hashedOtp, + attempts: 0, + expiresAt: this.getOtpExpiry(), }) - if (!otpEntry) { - await this.createOtpEntry(mobileNumber, OtpType.Mobile, hashedOtp) - } else { - await otpEntry?.update({ hashedOtp, attempts: 0 }) - } const message = `Your OTP is ${otp}. It will expire in ${milliSecondsToMinutes( OTP_EXPIRY @@ -433,26 +424,6 @@ class UsersService { private getOtpExpiry() { return new Date(Date.now() + OTP_EXPIRY) } - - private async createOtpEntry( - key: string, - keyType: OtpType, - hashedOtp: string - ) { - if (keyType === OtpType.Email) { - await this.otpRepository.create({ - email: key.toLowerCase(), - hashedOtp, - expiresAt: this.getOtpExpiry(), - }) - } else { - await this.otpRepository.create({ - mobileNumber: key, - hashedOtp, - expiresAt: this.getOtpExpiry(), - }) - } - } } export default UsersService