diff --git a/src/i18n/en/auth.json b/src/i18n/en/auth.json index 8a2614b..2294953 100644 --- a/src/i18n/en/auth.json +++ b/src/i18n/en/auth.json @@ -10,6 +10,7 @@ "unauthorized": "Unauthorized access", "tokenReuse": "Token reuse detected.", "invalidOTP": "OTP is invalid or expired.", + "accountNotFound": "Account not found.", "accessDenied": "Access denied. You do not have the required permissions to perform this action." }, "messages": { diff --git a/src/i18n/fa/auth.json b/src/i18n/fa/auth.json index f1bb0a4..dfa063f 100644 --- a/src/i18n/fa/auth.json +++ b/src/i18n/fa/auth.json @@ -10,6 +10,7 @@ "unauthorized": "دسترسی غیر مجاز", "tokenReuse": "توکن قبلا استفاده شده.", "invalidOTP": "کد تایید اشتباه است یا منقضی شده.", + "accountNotFound": "حساب کاربری یافت نشد.", "accessDenied": "دسترسی غیرمجاز. شما مجوزهای لازم برای انجام این عملیات را ندارید." }, "messages": { diff --git a/src/migrations/1795305600000-OtpPurpose.ts b/src/migrations/1795305600000-OtpPurpose.ts new file mode 100644 index 0000000..295a24e --- /dev/null +++ b/src/migrations/1795305600000-OtpPurpose.ts @@ -0,0 +1,13 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class OtpPurpose1795305600000 implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "otp" ADD "purpose" varchar NOT NULL DEFAULT 'signup'`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`ALTER TABLE "otp" DROP COLUMN "purpose"`); + } +} diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.ts index 3fcf7f9..2f9ee2b 100644 --- a/src/modules/auth/auth.controller.ts +++ b/src/modules/auth/auth.controller.ts @@ -1,4 +1,11 @@ -import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common'; +import { + Body, + Controller, + Header, + HttpCode, + HttpStatus, + Post, +} from '@nestjs/common'; import { LoginDTO } from './dtos/login.dto'; import { AuthService } from './providers/auth.service'; import { VerifyOtpDTO } from './dtos/verify-otp.dto'; @@ -13,6 +20,8 @@ import { LogoutDTO } from './dtos/logout.dto'; import { ActiveUser } from '@/common/decorators/active-user.decorator'; import { AccessToken } from './decorators/access-token.decorator'; import { User } from '@/modules/users/entities/user.entity'; +import { ResetPasswordDTO } from './dtos/reset-password.dto'; +import { ResetPasswordOtpResponseDTO } from './dtos/responses/reset-password-otp.dto'; @Controller('auth') export class AuthController { @@ -109,6 +118,36 @@ export class AuthController { return await this.authService.verifyOTP(verifyOtpDto); } + @Public() + @Post('reset-password') + @HttpCode(HttpStatus.OK) + @Header('Cache-Control', 'no-store') + @Throttle({ default: { limit: 30, ttl: 60_000 } }) + @ApiAppResponse([ + { + status: HttpStatus.OK, + variants: [ + { model: ResetPasswordOtpResponseDTO }, + { model: TokensResponseDTO }, + ], + }, + { + status: HttpStatus.UNAUTHORIZED, + variants: [{ messageExample: 'کد تایید اشتباه است یا منقضی شده.' }], + }, + { + status: HttpStatus.NOT_FOUND, + variants: [{ messageExample: 'حساب کاربری یافت نشد.' }], + }, + { + status: HttpStatus.TOO_MANY_REQUESTS, + variants: [{ messageExample: 'لطفا بعد از ۱ دقیقه دوباره امتحان کنید.' }], + }, + ]) + public async resetPassword(@Body() dto: ResetPasswordDTO) { + return this.authService.resetPassword(dto); + } + @Public() @Post('refresh') @HttpCode(HttpStatus.OK) diff --git a/src/modules/auth/auth.module.ts b/src/modules/auth/auth.module.ts index 742f92c..101fed4 100644 --- a/src/modules/auth/auth.module.ts +++ b/src/modules/auth/auth.module.ts @@ -16,6 +16,7 @@ import { RefreshTokensProvider } from './providers/refresh-tokens.provider'; import { RedisModule } from '@/common/modules/redis/redis.module'; import { AuthRedisProvider } from './providers/auth-redis.provider'; import { LogoutProvider } from './providers/logout.provider'; +import { ResetPasswordProvider } from './providers/reset-password.provider'; @Module({ imports: [ @@ -45,6 +46,7 @@ import { LogoutProvider } from './providers/logout.provider'; RefreshTokensProvider, AuthRedisProvider, LogoutProvider, + ResetPasswordProvider, { provide: APP_GUARD, useClass: GlobalAuthGuard, diff --git a/src/modules/auth/dtos/login.dto.ts b/src/modules/auth/dtos/login.dto.ts index e52d54e..27c3733 100644 --- a/src/modules/auth/dtos/login.dto.ts +++ b/src/modules/auth/dtos/login.dto.ts @@ -22,7 +22,9 @@ export class PhoneDTO { field: '$t(auth.fields.phone)', }), }) - @Transform(({ value }) => Utils.StringUtils.normalizePhone(value as string)) + @Transform(({ value }: { value: unknown }) => + typeof value === 'string' ? Utils.StringUtils.normalizePhone(value) : value, + ) phone!: string; } diff --git a/src/modules/auth/dtos/reset-password.dto.ts b/src/modules/auth/dtos/reset-password.dto.ts new file mode 100644 index 0000000..e5754e0 --- /dev/null +++ b/src/modules/auth/dtos/reset-password.dto.ts @@ -0,0 +1,14 @@ +import { ApiPropertyOptional } from '@nestjs/swagger'; +import { IsString, Matches, ValidateIf } from 'class-validator'; +import { i18nValidationMessage as t } from 'nestjs-i18n'; +import { PhoneDTO } from './login.dto'; + +export class ResetPasswordDTO extends PhoneDTO { + @ApiPropertyOptional({ description: '5-digit OTP code', example: '12345' }) + @ValidateIf((_object, value) => value !== undefined) + @IsString() + @Matches(/^[0-9]{5}$/, { + message: t('validation.wrongFieldFormat', { field: '$t(auth.fields.otp)' }), + }) + otp?: string; +} diff --git a/src/modules/auth/dtos/responses/reset-password-otp.dto.ts b/src/modules/auth/dtos/responses/reset-password-otp.dto.ts new file mode 100644 index 0000000..a95de96 --- /dev/null +++ b/src/modules/auth/dtos/responses/reset-password-otp.dto.ts @@ -0,0 +1,9 @@ +import { ApiProperty } from '@nestjs/swagger'; + +export class ResetPasswordOtpResponseDTO { + @ApiProperty({ example: '12345' }) + code!: string; + + @ApiProperty({ type: Date }) + otpExpiresAt!: Date; +} diff --git a/src/modules/auth/http/reset-password.post.endpoints.http b/src/modules/auth/http/reset-password.post.endpoints.http new file mode 100644 index 0000000..98c2d2f --- /dev/null +++ b/src/modules/auth/http/reset-password.post.endpoints.http @@ -0,0 +1,6 @@ +POST {{baseUrl}}/auth/reset-password/ +Content-Type: application/json + +{ + "phone": "09333026363" +} \ No newline at end of file diff --git a/src/modules/auth/providers/auth.service.ts b/src/modules/auth/providers/auth.service.ts index f9884a3..93820f9 100644 --- a/src/modules/auth/providers/auth.service.ts +++ b/src/modules/auth/providers/auth.service.ts @@ -7,6 +7,8 @@ import { RefreshTokenDTO } from '../dtos/refresh-token.dto'; import { RefreshTokensProvider } from './refresh-tokens.provider'; import { LogoutDTO } from '../dtos/logout.dto'; import { LogoutProvider } from './logout.provider'; +import { ResetPasswordDTO } from '../dtos/reset-password.dto'; +import { ResetPasswordProvider } from './reset-password.provider'; @Injectable() export class AuthService { @@ -30,6 +32,7 @@ export class AuthService { * Inject Logout Provider */ private readonly logoutProvider: LogoutProvider, + private readonly resetPasswordProvider: ResetPasswordProvider, ) {} public async logIn(loginDto: LoginDTO) { @@ -44,6 +47,10 @@ export class AuthService { return await this.refreshTokensProvider.refreshTokens(refreshTokenDto); } + public async resetPassword(dto: ResetPasswordDTO) { + return this.resetPasswordProvider.resetPassword(dto); + } + public async logout( userId: number, logoutDto: LogoutDTO, diff --git a/src/modules/auth/providers/reset-password.provider.ts b/src/modules/auth/providers/reset-password.provider.ts new file mode 100644 index 0000000..4ad7c45 --- /dev/null +++ b/src/modules/auth/providers/reset-password.provider.ts @@ -0,0 +1,42 @@ +import { Injectable, NotFoundException } from '@nestjs/common'; +import { randomUUID } from 'crypto'; +import { AppResponse } from '@/common/responses'; +import { OtpService } from '@/modules/otp/providers/otp.service'; +import { UsersService } from '@/modules/users/providers/users.service'; +import { ResetPasswordDTO } from '../dtos/reset-password.dto'; +import { GenerateTokenProvider } from './generate-token.provider'; +import { OtpPurpose } from '@/modules/otp/enums/otp-purpose.enum'; + +@Injectable() +export class ResetPasswordProvider { + constructor( + private readonly usersService: UsersService, + private readonly otpService: OtpService, + private readonly generateTokenProvider: GenerateTokenProvider, + ) {} + + public async resetPassword({ phone, otp }: ResetPasswordDTO) { + // if ( + // process.env.NODE_ENV !== 'development' || + // process.env.AUTH_RESET_PASSWORD_RETURN_OTP !== 'true' + // ) { + // throw new NotFoundException(); + // } + + const user = await this.usersService.findOneByPhone(phone); + if (!user) { + throw new NotFoundException('auth.errors.accountNotFound'); + } + + if (otp !== undefined) { + await this.otpService.verifyOTP(phone, otp, OtpPurpose.PASSWORD_RESET); + return this.generateTokenProvider.generateTokens(user, randomUUID()); + } + + const { code, expiresAt } = await this.otpService.createOTP( + phone, + OtpPurpose.PASSWORD_RESET, + ); + return new AppResponse({ code, otpExpiresAt: expiresAt }); + } +} diff --git a/src/modules/otp/entities/otp.entity.ts b/src/modules/otp/entities/otp.entity.ts index 17088ec..96e3b56 100644 --- a/src/modules/otp/entities/otp.entity.ts +++ b/src/modules/otp/entities/otp.entity.ts @@ -7,6 +7,7 @@ import { PrimaryGeneratedColumn, BaseEntity, } from 'typeorm'; +import { OtpPurpose } from '../enums/otp-purpose.enum'; @Entity() @Index(['phone', 'used']) @@ -28,6 +29,9 @@ export class OTP extends BaseEntity { }) code!: string; + @Column({ type: 'enum', enum: OtpPurpose, default: 'signup' }) + purpose!: OtpPurpose; + @CreateDateColumn() createdAt!: Date; diff --git a/src/modules/otp/enums/otp-purpose.enum.ts b/src/modules/otp/enums/otp-purpose.enum.ts new file mode 100644 index 0000000..ee19e70 --- /dev/null +++ b/src/modules/otp/enums/otp-purpose.enum.ts @@ -0,0 +1,4 @@ +export enum OtpPurpose { + PASSWORD_RESET = 'password-reset', + SIGNUP = 'signup', +} diff --git a/src/modules/otp/providers/otp.service.spec.ts b/src/modules/otp/providers/otp.service.spec.ts index 270a8f7..4dfdab2 100644 --- a/src/modules/otp/providers/otp.service.spec.ts +++ b/src/modules/otp/providers/otp.service.spec.ts @@ -3,6 +3,7 @@ import { OTP } from '../entities/otp.entity'; import { OtpService } from './otp.service'; import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider'; import { beforeEach, describe, expect, it, jest } from '@jest/globals'; +import { OtpPurpose } from '../enums/otp-purpose.enum'; describe('OTP verification', () => { let otp: OTP; @@ -48,7 +49,7 @@ describe('OTP verification', () => { it('consumes the latest OTP under a database write lock and rejects reuse', async () => { await expect(service.verifyOTP(otp.phone, '12345')).resolves.toBe(otp); expect(findOne).toHaveBeenCalledWith({ - where: { phone: otp.phone }, + where: { phone: otp.phone, purpose: 'signup' }, order: { createdAt: 'DESC', id: 'DESC' }, lock: { mode: 'pessimistic_write' }, }); @@ -71,6 +72,19 @@ describe('OTP verification', () => { expect(save).toHaveBeenCalledTimes(10); }); + it('looks up password reset codes by both phone and purpose', async () => { + findOne.mockResolvedValue(null); + await expect( + service.verifyOTP(otp.phone, '12345', OtpPurpose.PASSWORD_RESET), + ).rejects.toThrow(); + expect(findOne).toHaveBeenCalledWith( + expect.objectContaining({ + where: { phone: otp.phone, purpose: 'password-reset' }, + }), + ); + expect(compare).not.toHaveBeenCalled(); + }); + it('allows a correct code after nine wrong guesses', async () => { otp.failedAttempts = 9; await expect(service.verifyOTP(otp.phone, '12345')).resolves.toBe(otp); diff --git a/src/modules/otp/providers/otp.service.ts b/src/modules/otp/providers/otp.service.ts index 5c78432..8a88a2e 100644 --- a/src/modules/otp/providers/otp.service.ts +++ b/src/modules/otp/providers/otp.service.ts @@ -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 { + public async verifyOTP( + phone: string, + code: string, + purpose: OtpPurpose = OtpPurpose.SIGNUP, + ): Promise { 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' }, });