Files
heala-backend/src/modules/otp/providers/otp.service.ts
T
2026-02-24 09:22:39 +03:30

105 lines
2.5 KiB
TypeScript

import {
HttpException,
HttpStatus,
Injectable,
RequestTimeoutException,
UnauthorizedException,
} from '@nestjs/common';
import { LessThan, Repository } from 'typeorm';
import { OTP } from '../otp.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Cron } from '@nestjs/schedule';
import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider';
@Injectable()
export class OtpService {
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 Math.floor(10_000 + Math.random() * 90_000).toString();
}
/**
* Create new OTP record
*/
public async createOTP(phone: string): Promise<string> {
// OTP request Rate limit
const lastOTP = await this.otpRepository.findOne({
where: { phone },
order: { createdAt: 'DESC' },
});
if (lastOTP && Date.now() - lastOTP.createdAt.getTime() < 60_000) {
throw new HttpException(
'Too many requests! Try again after 1 min.',
HttpStatus.TOO_MANY_REQUESTS,
);
}
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;
}
/**
* Verify OTP
*/
public async verifyOTP(phone: string, code: string): Promise<OTP> {
let otp: OTP | null = null;
try {
otp = await this.otpRepository.findOne({
where: { phone, used: false },
order: { createdAt: 'DESC' },
});
} catch (err) {
throw new RequestTimeoutException(
'Unable to process your request at the moment. Please try again later.',
{ cause: err, description: 'Error connecting to the database' },
);
}
if (!otp) throw new UnauthorizedException('Invalid OTP');
if (otp.expiresAt < new Date()) {
throw new UnauthorizedException('OTP expired');
}
// TODO: Compared hashed otp
if (otp.code !== code) {
throw new UnauthorizedException('Invalid OTP');
}
otp.used = true;
await this.otpRepository.save(otp);
return otp;
}
@Cron('0 */10 * * * *')
public async cleanupExpired(): Promise<void> {
await this.otpRepository.delete({
expiresAt: LessThan(new Date()),
});
}
}