feat: hash otp code

This commit is contained in:
2026-02-24 09:22:39 +03:30
parent 63b4567166
commit b9adbef7e8
4 changed files with 33 additions and 7 deletions
+2 -1
View File
@@ -2,9 +2,10 @@ import { Module } from '@nestjs/common';
import { OtpService } from './providers/otp.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { OTP } from './otp.entity';
import { HashingModule } from '@/common/modules/hashing/hashing.module';
@Module({
imports: [TypeOrmModule.forFeature([OTP])],
imports: [TypeOrmModule.forFeature([OTP]), HashingModule],
providers: [OtpService],
exports: [OtpService],
})
+22 -6
View File
@@ -2,12 +2,14 @@ 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 {
@@ -17,6 +19,11 @@ export class OtpService {
*/
@InjectRepository(OTP)
private readonly otpRepository: Repository<OTP>,
/**
* Inject Hashing Provider
*/
private readonly hashingProvider: HashingProvider,
) {}
/**
@@ -44,9 +51,9 @@ export class OtpService {
}
const code = this.generateOTPCode();
// TODO: Hash the code
const hashedCode = await this.hashingProvider.hash(code);
const otp = this.otpRepository.create({ phone, code });
const otp = this.otpRepository.create({ phone, code: hashedCode });
await this.otpRepository.save(otp);
@@ -57,10 +64,19 @@ export class OtpService {
* Verify OTP
*/
public async verifyOTP(phone: string, code: string): Promise<OTP> {
const otp = await this.otpRepository.findOne({
where: { phone, used: false },
order: { createdAt: 'DESC' },
});
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');