feat: fix validation generate otp

pull/148/head
Firman Ramdhani 2025-06-10 15:02:43 +07:00
parent dc1fadbe1f
commit 8497a5779d
2 changed files with 21 additions and 9 deletions

View File

@ -38,6 +38,10 @@ export class OtpService {
return Object.values(counts).some((count) => count > 2); return Object.values(counts).some((count) => count > 2);
} }
private hasMatchLength(str: string) {
return str.length !== this.otpLength;
}
public generateSecureOTP(): string { public generateSecureOTP(): string {
let otp: string; let otp: string;
@ -46,11 +50,11 @@ export class OtpService {
Math.floor(Math.random() * 10).toString(), Math.floor(Math.random() * 10).toString(),
).join(''); ).join('');
} while ( } while (
this.hasMatchLength(otp) ||
this.hasSequentialDigits(otp) || this.hasSequentialDigits(otp) ||
this.hasRepeatedDigits(otp) || this.hasRepeatedDigits(otp) ||
this.isPalindrome(otp) || this.isPalindrome(otp) ||
this.hasPartiallyRepeatedDigits(otp) || this.hasPartiallyRepeatedDigits(otp)
otp?.length < this.otpLength
); );
return otp; return otp;
} }

View File

@ -74,7 +74,9 @@ export class OtpVerificationService {
const createdAtMoment = moment(Number(activeOTP.created_at)); const createdAtMoment = moment(Number(activeOTP.created_at));
const nowMoment = moment(Number(dateNow)); const nowMoment = moment(Number(dateNow));
const diffSeconds = nowMoment.diff(createdAtMoment, 'seconds'); const diffSeconds = nowMoment.diff(createdAtMoment, 'seconds');
if (diffSeconds < 60) { const isProduction = process.env.NODE_ENV === 'true';
if (diffSeconds < 60 && isProduction) {
throw new BadRequestException( throw new BadRequestException(
'An active OTP request was made recently. Please try again later.', 'An active OTP request was made recently. Please try again later.',
); );
@ -116,10 +118,13 @@ export class OtpVerificationService {
); );
} }
let otp: any;
// Build a where condition with OR between target_id and reference // Build a where condition with OR between target_id and reference
const otp = await this.otpVerificationRepo.findOne({
where: [ if (target_id) {
{ otp = await this.otpVerificationRepo.findOne({
where: {
otp_code, otp_code,
action_type, action_type,
target_id, target_id,
@ -127,7 +132,10 @@ export class OtpVerificationService {
is_used: false, is_used: false,
is_replaced: false, is_replaced: false,
}, },
{ });
} else if (reference) {
otp = await this.otpVerificationRepo.findOne({
where: {
otp_code, otp_code,
action_type, action_type,
reference, reference,
@ -135,8 +143,8 @@ export class OtpVerificationService {
is_used: false, is_used: false,
is_replaced: false, is_replaced: false,
}, },
],
}); });
}
if (!otp) { if (!otp) {
throw new BadRequestException('Invalid or expired OTP.'); throw new BadRequestException('Invalid or expired OTP.');