135 lines
3.7 KiB
TypeScript
135 lines
3.7 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';
|
|
import { OtpPurpose } from '../enums/otp-purpose.enum';
|
|
|
|
@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,
|
|
purpose: OtpPurpose = OtpPurpose.SIGNUP,
|
|
): Promise<{ code: string; expiresAt: Date }> {
|
|
return this.otpRepository.manager.transaction(async (manager) => {
|
|
// Serialize requests even when the phone has no OTP rows yet.
|
|
await manager.query('SELECT pg_advisory_xact_lock($1::bigint)', [phone]);
|
|
const repository = manager.getRepository(OTP);
|
|
const lastOTP = await repository.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 = repository.create({
|
|
phone,
|
|
code: hashedCode,
|
|
purpose,
|
|
createdAt: new Date(),
|
|
});
|
|
await repository.save(otp);
|
|
|
|
return { code, expiresAt: otp.expiresAt };
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Verify OTP
|
|
*/
|
|
public async verifyOTP(
|
|
phone: string,
|
|
code: string,
|
|
purpose: OtpPurpose = OtpPurpose.SIGNUP,
|
|
): 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, purpose },
|
|
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()),
|
|
});
|
|
}
|
|
}
|