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
+1
View File
@@ -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": {
+1
View File
@@ -10,6 +10,7 @@
"unauthorized": "دسترسی غیر مجاز",
"tokenReuse": "توکن قبلا استفاده شده.",
"invalidOTP": "کد تایید اشتباه است یا منقضی شده.",
"accountNotFound": "حساب کاربری یافت نشد.",
"accessDenied": "دسترسی غیرمجاز. شما مجوزهای لازم برای انجام این عملیات را ندارید."
},
"messages": {
@@ -0,0 +1,13 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class OtpPurpose1795305600000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "otp" ADD "purpose" varchar NOT NULL DEFAULT 'signup'`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "otp" DROP COLUMN "purpose"`);
}
}
+40 -1
View File
@@ -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)
+2
View File
@@ -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,
+3 -1
View File
@@ -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;
}
@@ -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;
}
@@ -0,0 +1,9 @@
import { ApiProperty } from '@nestjs/swagger';
export class ResetPasswordOtpResponseDTO {
@ApiProperty({ example: '12345' })
code!: string;
@ApiProperty({ type: Date })
otpExpiresAt!: Date;
}
@@ -0,0 +1,6 @@
POST {{baseUrl}}/auth/reset-password/
Content-Type: application/json
{
"phone": "09333026363"
}
@@ -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,
@@ -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 });
}
}
+4
View File
@@ -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;
@@ -0,0 +1,4 @@
export enum OtpPurpose {
PASSWORD_RESET = 'password-reset',
SIGNUP = 'signup',
}
+15 -1
View File
@@ -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);
+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' },
});