feat: add reset password
This commit is contained in:
@@ -10,6 +10,7 @@
|
|||||||
"unauthorized": "Unauthorized access",
|
"unauthorized": "Unauthorized access",
|
||||||
"tokenReuse": "Token reuse detected.",
|
"tokenReuse": "Token reuse detected.",
|
||||||
"invalidOTP": "OTP is invalid or expired.",
|
"invalidOTP": "OTP is invalid or expired.",
|
||||||
|
"accountNotFound": "Account not found.",
|
||||||
"accessDenied": "Access denied. You do not have the required permissions to perform this action."
|
"accessDenied": "Access denied. You do not have the required permissions to perform this action."
|
||||||
},
|
},
|
||||||
"messages": {
|
"messages": {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
"unauthorized": "دسترسی غیر مجاز",
|
"unauthorized": "دسترسی غیر مجاز",
|
||||||
"tokenReuse": "توکن قبلا استفاده شده.",
|
"tokenReuse": "توکن قبلا استفاده شده.",
|
||||||
"invalidOTP": "کد تایید اشتباه است یا منقضی شده.",
|
"invalidOTP": "کد تایید اشتباه است یا منقضی شده.",
|
||||||
|
"accountNotFound": "حساب کاربری یافت نشد.",
|
||||||
"accessDenied": "دسترسی غیرمجاز. شما مجوزهای لازم برای انجام این عملیات را ندارید."
|
"accessDenied": "دسترسی غیرمجاز. شما مجوزهای لازم برای انجام این عملیات را ندارید."
|
||||||
},
|
},
|
||||||
"messages": {
|
"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"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 { LoginDTO } from './dtos/login.dto';
|
||||||
import { AuthService } from './providers/auth.service';
|
import { AuthService } from './providers/auth.service';
|
||||||
import { VerifyOtpDTO } from './dtos/verify-otp.dto';
|
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 { ActiveUser } from '@/common/decorators/active-user.decorator';
|
||||||
import { AccessToken } from './decorators/access-token.decorator';
|
import { AccessToken } from './decorators/access-token.decorator';
|
||||||
import { User } from '@/modules/users/entities/user.entity';
|
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')
|
@Controller('auth')
|
||||||
export class AuthController {
|
export class AuthController {
|
||||||
@@ -109,6 +118,36 @@ export class AuthController {
|
|||||||
return await this.authService.verifyOTP(verifyOtpDto);
|
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()
|
@Public()
|
||||||
@Post('refresh')
|
@Post('refresh')
|
||||||
@HttpCode(HttpStatus.OK)
|
@HttpCode(HttpStatus.OK)
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import { RefreshTokensProvider } from './providers/refresh-tokens.provider';
|
|||||||
import { RedisModule } from '@/common/modules/redis/redis.module';
|
import { RedisModule } from '@/common/modules/redis/redis.module';
|
||||||
import { AuthRedisProvider } from './providers/auth-redis.provider';
|
import { AuthRedisProvider } from './providers/auth-redis.provider';
|
||||||
import { LogoutProvider } from './providers/logout.provider';
|
import { LogoutProvider } from './providers/logout.provider';
|
||||||
|
import { ResetPasswordProvider } from './providers/reset-password.provider';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -45,6 +46,7 @@ import { LogoutProvider } from './providers/logout.provider';
|
|||||||
RefreshTokensProvider,
|
RefreshTokensProvider,
|
||||||
AuthRedisProvider,
|
AuthRedisProvider,
|
||||||
LogoutProvider,
|
LogoutProvider,
|
||||||
|
ResetPasswordProvider,
|
||||||
{
|
{
|
||||||
provide: APP_GUARD,
|
provide: APP_GUARD,
|
||||||
useClass: GlobalAuthGuard,
|
useClass: GlobalAuthGuard,
|
||||||
|
|||||||
@@ -22,7 +22,9 @@ export class PhoneDTO {
|
|||||||
field: '$t(auth.fields.phone)',
|
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;
|
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 { RefreshTokensProvider } from './refresh-tokens.provider';
|
||||||
import { LogoutDTO } from '../dtos/logout.dto';
|
import { LogoutDTO } from '../dtos/logout.dto';
|
||||||
import { LogoutProvider } from './logout.provider';
|
import { LogoutProvider } from './logout.provider';
|
||||||
|
import { ResetPasswordDTO } from '../dtos/reset-password.dto';
|
||||||
|
import { ResetPasswordProvider } from './reset-password.provider';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
@@ -30,6 +32,7 @@ export class AuthService {
|
|||||||
* Inject Logout Provider
|
* Inject Logout Provider
|
||||||
*/
|
*/
|
||||||
private readonly logoutProvider: LogoutProvider,
|
private readonly logoutProvider: LogoutProvider,
|
||||||
|
private readonly resetPasswordProvider: ResetPasswordProvider,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public async logIn(loginDto: LoginDTO) {
|
public async logIn(loginDto: LoginDTO) {
|
||||||
@@ -44,6 +47,10 @@ export class AuthService {
|
|||||||
return await this.refreshTokensProvider.refreshTokens(refreshTokenDto);
|
return await this.refreshTokensProvider.refreshTokens(refreshTokenDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async resetPassword(dto: ResetPasswordDTO) {
|
||||||
|
return this.resetPasswordProvider.resetPassword(dto);
|
||||||
|
}
|
||||||
|
|
||||||
public async logout(
|
public async logout(
|
||||||
userId: number,
|
userId: number,
|
||||||
logoutDto: LogoutDTO,
|
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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
PrimaryGeneratedColumn,
|
PrimaryGeneratedColumn,
|
||||||
BaseEntity,
|
BaseEntity,
|
||||||
} from 'typeorm';
|
} from 'typeorm';
|
||||||
|
import { OtpPurpose } from '../enums/otp-purpose.enum';
|
||||||
|
|
||||||
@Entity()
|
@Entity()
|
||||||
@Index(['phone', 'used'])
|
@Index(['phone', 'used'])
|
||||||
@@ -28,6 +29,9 @@ export class OTP extends BaseEntity {
|
|||||||
})
|
})
|
||||||
code!: string;
|
code!: string;
|
||||||
|
|
||||||
|
@Column({ type: 'enum', enum: OtpPurpose, default: 'signup' })
|
||||||
|
purpose!: OtpPurpose;
|
||||||
|
|
||||||
@CreateDateColumn()
|
@CreateDateColumn()
|
||||||
createdAt!: Date;
|
createdAt!: Date;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export enum OtpPurpose {
|
||||||
|
PASSWORD_RESET = 'password-reset',
|
||||||
|
SIGNUP = 'signup',
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import { OTP } from '../entities/otp.entity';
|
|||||||
import { OtpService } from './otp.service';
|
import { OtpService } from './otp.service';
|
||||||
import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider';
|
import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider';
|
||||||
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
|
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
|
||||||
|
import { OtpPurpose } from '../enums/otp-purpose.enum';
|
||||||
|
|
||||||
describe('OTP verification', () => {
|
describe('OTP verification', () => {
|
||||||
let otp: OTP;
|
let otp: OTP;
|
||||||
@@ -48,7 +49,7 @@ describe('OTP verification', () => {
|
|||||||
it('consumes the latest OTP under a database write lock and rejects reuse', async () => {
|
it('consumes the latest OTP under a database write lock and rejects reuse', async () => {
|
||||||
await expect(service.verifyOTP(otp.phone, '12345')).resolves.toBe(otp);
|
await expect(service.verifyOTP(otp.phone, '12345')).resolves.toBe(otp);
|
||||||
expect(findOne).toHaveBeenCalledWith({
|
expect(findOne).toHaveBeenCalledWith({
|
||||||
where: { phone: otp.phone },
|
where: { phone: otp.phone, purpose: 'signup' },
|
||||||
order: { createdAt: 'DESC', id: 'DESC' },
|
order: { createdAt: 'DESC', id: 'DESC' },
|
||||||
lock: { mode: 'pessimistic_write' },
|
lock: { mode: 'pessimistic_write' },
|
||||||
});
|
});
|
||||||
@@ -71,6 +72,19 @@ describe('OTP verification', () => {
|
|||||||
expect(save).toHaveBeenCalledTimes(10);
|
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 () => {
|
it('allows a correct code after nine wrong guesses', async () => {
|
||||||
otp.failedAttempts = 9;
|
otp.failedAttempts = 9;
|
||||||
await expect(service.verifyOTP(otp.phone, '12345')).resolves.toBe(otp);
|
await expect(service.verifyOTP(otp.phone, '12345')).resolves.toBe(otp);
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { Cron, CronExpression } from '@nestjs/schedule';
|
|||||||
import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider';
|
import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider';
|
||||||
import { AppException } from '@/common/exceptions/app.exception';
|
import { AppException } from '@/common/exceptions/app.exception';
|
||||||
import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception';
|
import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception';
|
||||||
|
import { OtpPurpose } from '../enums/otp-purpose.enum';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class OtpService {
|
export class OtpService {
|
||||||
@@ -36,35 +37,47 @@ export class OtpService {
|
|||||||
*/
|
*/
|
||||||
public async createOTP(
|
public async createOTP(
|
||||||
phone: string,
|
phone: string,
|
||||||
|
purpose: OtpPurpose = OtpPurpose.SIGNUP,
|
||||||
): Promise<{ code: string; expiresAt: Date }> {
|
): Promise<{ code: string; expiresAt: Date }> {
|
||||||
// OTP request Rate limit
|
return this.otpRepository.manager.transaction(async (manager) => {
|
||||||
const lastOTP = await this.otpRepository.findOne({
|
// Serialize requests even when the phone has no OTP rows yet.
|
||||||
where: { phone },
|
await manager.query('SELECT pg_advisory_xact_lock($1::bigint)', [phone]);
|
||||||
order: { createdAt: 'DESC', id: 'DESC' },
|
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
|
* 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;
|
let verifiedOTP: OTP | null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -72,7 +85,7 @@ export class OtpService {
|
|||||||
async (manager) => {
|
async (manager) => {
|
||||||
const repository = manager.getRepository(OTP);
|
const repository = manager.getRepository(OTP);
|
||||||
const otp = await repository.findOne({
|
const otp = await repository.findOne({
|
||||||
where: { phone },
|
where: { phone, purpose },
|
||||||
order: { createdAt: 'DESC', id: 'DESC' },
|
order: { createdAt: 'DESC', id: 'DESC' },
|
||||||
lock: { mode: 'pessimistic_write' },
|
lock: { mode: 'pessimistic_write' },
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user