Files
heala-backend/src/modules/otp/providers/otp.service.ts
T

122 lines
3.2 KiB
TypeScript

import { HttpStatus, Injectable, UnauthorizedException } from '@nestjs/common';
import { LessThan, Repository } from 'typeorm';
import { randomInt } from 'crypto';
import { OTP } from '../entities/otp.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Cron, CronExpression } from '@nestjs/schedule';
import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider';
import { AppException } from '@/common/exceptions/app.exception';
import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception';
@Injectable()
export class OtpService {
private readonly maxFailedAttempts = 10;
constructor(
/**
* Inject OTP Repository
*/
@InjectRepository(OTP)
private readonly otpRepository: Repository<OTP>,
/**
* Inject Hashing Provider
*/
private readonly hashingProvider: HashingProvider,
) {}
/**
* Generate OTP 5-digit code
*/
private generateOTPCode(): string {
return randomInt(10_000, 100_000).toString();
}
/**
* Create new OTP record
*/
public async createOTP(
phone: string,
): Promise<{ code: string; expiresAt: Date }> {
// OTP request Rate limit
const lastOTP = await this.otpRepository.findOne({
where: { phone },
order: { createdAt: 'DESC', id: 'DESC' },
});
if (lastOTP && Date.now() - lastOTP.createdAt.getTime() < 60_000) {
throw new AppException(
'common.errors.tooManyRequests',
HttpStatus.TOO_MANY_REQUESTS,
{ minutes: 1 },
);
}
const code = this.generateOTPCode();
const hashedCode = await this.hashingProvider.hash(code);
const otp = this.otpRepository.create({ phone, code: hashedCode });
await this.otpRepository.save(otp);
return { code, expiresAt: otp.expiresAt };
}
/**
* Verify OTP
*/
public async verifyOTP(phone: string, code: string): Promise<OTP> {
let verifiedOTP: OTP | null;
try {
verifiedOTP = await this.otpRepository.manager.transaction(
async (manager) => {
const repository = manager.getRepository(OTP);
const otp = await repository.findOne({
where: { phone },
order: { createdAt: 'DESC', id: 'DESC' },
lock: { mode: 'pessimistic_write' },
});
if (
!otp ||
otp.used ||
otp.failedAttempts >= this.maxFailedAttempts ||
otp.expiresAt.getTime() <= Date.now()
) {
return null;
}
const matches = await this.hashingProvider.compare(code, otp.code);
if (!matches) {
otp.failedAttempts += 1;
await repository.save(otp);
return null;
}
if (otp.expiresAt.getTime() <= Date.now()) return null;
otp.used = true;
await repository.save(otp);
return otp;
},
);
} catch (err) {
throw new AppTimeoutException(err);
}
if (!verifiedOTP) {
throw new UnauthorizedException('auth.errors.invalidOTP');
}
return verifiedOTP;
}
@Cron(CronExpression.EVERY_10_MINUTES)
public async cleanupExpired(): Promise<void> {
await this.otpRepository.delete({
expiresAt: LessThan(new Date()),
});
}
}