otp in database

This commit is contained in:
2026-01-20 20:27:01 +03:30
parent 897db44c66
commit 6ba36ca130
13 changed files with 113 additions and 124 deletions
+6 -5
View File
@@ -7,12 +7,13 @@ import { JwtModule } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { AdminModule } from '../admin/admin.module';
import { TokensService } from './services/tokens.service';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { User } from '../user/entities/user.entity';
import { AdminAuthGuard } from './guards/adminAuth.guard';
import { RefreshToken } from './entities/refresh-token.entity';
import { NotificationsModule } from '../notification/notifications.module';
import { OtpRepository } from './repository/otp.repository';
import { OtpService } from './services/otp.service';
import { Otp } from './entities/otp.entity';
@Module({
imports: [
@@ -33,13 +34,13 @@ import { NotificationsModule } from '../notification/notifications.module';
inject: [ConfigService],
}),
forwardRef(() => AdminModule),
MikroOrmModule.forFeature([User, RefreshToken]),
MikroOrmModule.forFeature([RefreshToken, Otp]),
forwardRef(() => NotificationsModule),
],
controllers: [AuthController],
providers: [AuthService, TokensService, AdminAuthGuard],
providers: [AuthService, TokensService, AdminAuthGuard, OtpRepository, OtpService],
exports: [AdminAuthGuard],
})
export class AuthModule { }
+16
View File
@@ -0,0 +1,16 @@
import { Entity, Index, OptionalProps, PrimaryKey, Property } from '@mikro-orm/core';
@Entity({ tableName: 'otps' })
@Index({ properties: ['phone'] })
export class Otp {
[OptionalProps]?: 'createdAt'
@PrimaryKey({ type: 'varchar', })
phone!: string;
@Property()
code!: string;
@Property({ columnType: 'timestamptz' })
expiresAt!: Date
}
@@ -0,0 +1,14 @@
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
import { Injectable } from '@nestjs/common';
import { Otp } from '../entities/otp.entity';
@Injectable()
export class OtpRepository extends EntityRepository<Otp> {
constructor(
readonly em: EntityManager,
) {
super(em, Otp);
}
}
+13 -27
View File
@@ -1,6 +1,5 @@
import { Injectable, BadRequestException } from '@nestjs/common';
import { RequestOtpDto } from '../dto/request-otp.dto';
import { CacheService } from '../../util/cache.service';
import { SmsService } from '../../notification/services/sms.service';
import { UserService } from '../../user/providers/user.service';
import { randomInt } from 'crypto';
@@ -9,46 +8,35 @@ import { AuthMessage } from 'src/common/enums/message.enum';
import { AdminRepository } from 'src/modules/admin/repositories/admin.repository';
import { AdminLoginTransformer } from '../transformers/admin-login.transformer';
import { UserLoginTransformer } from '../transformers/user-login.transformer';
import { ConfigService } from '@nestjs/config';
import { normalizePhone } from '../../util/phone.util';
import { OtpService } from './otp.service';
@Injectable()
export class AuthService {
readonly ADMIN_PERMISSIONS_KEY = 'admin-perms';
private OTP_EXPIRATION_TIME: number;
constructor(
private readonly cacheService: CacheService,
private readonly smsService: SmsService,
private readonly userService: UserService,
private readonly tokensService: TokensService,
private readonly adminRepository: AdminRepository,
private readonly configService: ConfigService,
private readonly otpService: OtpService,
) {
this.OTP_EXPIRATION_TIME = this.configService.get<number>('OTP_EXPIRATION_TIME') ?? 240;
}
private userOtpKey(phone: string) {
return `otp:${phone}`;
}
private adminOtpKey(phone: string) {
return `otp-admin:${phone}`;
}
async requestOtp(dto: RequestOtpDto, isAdmin: boolean) {
const { phone } = dto;
const normalizedPhone = normalizePhone(phone);
if (isAdmin) {
await this.valdateAdmin(normalizedPhone)
}
const code = this.generateOtpCode();
const key = isAdmin ? this.adminOtpKey(normalizedPhone) : this.userOtpKey(normalizedPhone);
await this.cacheService.set(key, code, this.OTP_EXPIRATION_TIME);
await this.otpService.set(normalizedPhone, code)
// await this.smsService.sendotp(normalizedPhone, code);
return { code };
@@ -56,16 +44,14 @@ export class AuthService {
async verifyOtp(phone: string, code: string) {
const normalizedPhone = normalizePhone(phone);
const key = this.userOtpKey(normalizedPhone);
const cachedCode = await this.cacheService.get(key);
const cachedCode = await this.otpService.get(normalizedPhone);
if (!cachedCode) throw new BadRequestException('OTP expired or not found');
if (cachedCode !== code) throw new BadRequestException('Invalid OTP');
await this.cacheService.del(key);
await this.otpService.delete(normalizedPhone)
const user = await this.userService.getOrCreate({
firstName: '[کاربر]',
lastName: '',
phone: normalizedPhone,
gender: true,
maxCredit: 0
@@ -81,13 +67,13 @@ export class AuthService {
async verifyOtpAdmin(phone: string, code: string) {
const normalizedPhone = normalizePhone(phone);
const key = this.adminOtpKey(normalizedPhone);
const cachedCode = await this.cacheService.get(key);
const cachedCode = await this.otpService.get(normalizedPhone);
if (!cachedCode) throw new BadRequestException('OTP expired or not found');
if (cachedCode !== code) throw new BadRequestException('Invalid OTP');
await this.cacheService.del(key);
await this.otpService.delete(normalizedPhone);
const admin = await this.adminRepository.findOne({ phone: normalizedPhone }, { populate: ['role', 'role.permissions'] });
+50
View File
@@ -0,0 +1,50 @@
import { Injectable } from "@nestjs/common";
import { OtpRepository } from "../repository/otp.repository";
import { EntityManager } from "@mikro-orm/postgresql";
import { ConfigService } from "@nestjs/config";
@Injectable()
export class OtpService {
private OTP_EXPIRATION_TIME: number;// in seconds
constructor(
private readonly otpRepository: OtpRepository,
private readonly configService: ConfigService,
private readonly em: EntityManager
) {
this.OTP_EXPIRATION_TIME = this.configService.get<number>('OTP_EXPIRATION_TIME') ?? 240;
}
async set(phone: string, code: string) {
let otpRecord = await this.otpRepository.findOne({ phone })
const expiresAt = new Date(Date.now() + this.OTP_EXPIRATION_TIME * 1000)
if (!otpRecord) {
otpRecord = this.otpRepository.create({
phone,
code,
expiresAt
})
} else {
otpRecord.code = code
otpRecord.expiresAt = expiresAt
}
await this.em.persistAndFlush(otpRecord)
return { successs: true }
}
async get(phone: string) {
let otpRecord = await this.otpRepository.findOne({ phone, expiresAt: { $gt: new Date() } })
return otpRecord?.code
}
async delete(phone: string) {
await this.otpRepository.nativeDelete({ phone })
return { successs: true }
}
}
@@ -2,7 +2,7 @@ import type { User } from '../../user/entities/user.entity';
export interface UserLoginResponse {
id: string;
firstName: string;
firstName?: string;
lastName?: string;
phone: string;
isActive?: boolean;