feat: add reset password

This commit is contained in:
2026-11-22 09:25:21 +03:30
parent 88b4a99908
commit 302d06b44f
15 changed files with 197 additions and 26 deletions
+36 -23
View File
@@ -7,6 +7,7 @@ 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 {
@@ -36,35 +37,47 @@ export class OtpService {
*/
public async createOTP(
phone: string,
purpose: OtpPurpose = OtpPurpose.SIGNUP,
): Promise<{ code: string; expiresAt: Date }> {
// OTP request Rate limit
const lastOTP = await this.otpRepository.findOne({
where: { phone },
order: { createdAt: 'DESC', id: 'DESC' },
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 };
});
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> {
public async verifyOTP(
phone: string,
code: string,
purpose: OtpPurpose = OtpPurpose.SIGNUP,
): Promise<OTP> {
let verifiedOTP: OTP | null;
try {
@@ -72,7 +85,7 @@ export class OtpService {
async (manager) => {
const repository = manager.getRepository(OTP);
const otp = await repository.findOne({
where: { phone },
where: { phone, purpose },
order: { createdAt: 'DESC', id: 'DESC' },
lock: { mode: 'pessimistic_write' },
});