Repository navigation
feat(auth): Implement forgot password and reset password #13
base: dev
Are you sure you want to change the base?
Changes from 7 commits
f0e23d2
10180a8
0ef8157
8b6a22a
1758a01
636e268
71511b5
048f3ee
95e2161
ba3fc1f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -1,23 +1,35 @@ | ||||||||||||||||||||||||||
| import { HttpStatus, Injectable } from '@nestjs/common'; | ||||||||||||||||||||||||||
| import { HttpStatus, Injectable, Logger } from '@nestjs/common'; | ||||||||||||||||||||||||||
| import { JwtService } from '@nestjs/jwt'; | ||||||||||||||||||||||||||
| import { InjectRepository } from '@nestjs/typeorm'; | ||||||||||||||||||||||||||
| import { Repository } from 'typeorm'; | ||||||||||||||||||||||||||
| import * as bcrypt from 'bcrypt'; | ||||||||||||||||||||||||||
| import * as SYS_MSG from '@shared/constants/SystemMessages'; | ||||||||||||||||||||||||||
| import { CustomHttpException } from '@shared/helpers/custom-http-filter'; | ||||||||||||||||||||||||||
| import { User } from '@modules/user/entities/user.entity'; | ||||||||||||||||||||||||||
| import { UserSession } from './entities/user-session.entity'; | ||||||||||||||||||||||||||
| import { CreateUserDTO } from './dto/create-user.dto'; | ||||||||||||||||||||||||||
| import { LoginDto } from './dto/login.dto'; | ||||||||||||||||||||||||||
| import { RedisService } from '@modules/redis/services/redis.service'; | ||||||||||||||||||||||||||
| import { randomInt } from 'crypto'; | ||||||||||||||||||||||||||
| import { EmailService } from '@modules/email/email.service'; | ||||||||||||||||||||||||||
| import { FRONTEND_RESET_PASSWORD } from '@shared/constants/app-constants'; | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| const OTP_LENGTH = 6; | ||||||||||||||||||||||||||
| const OTP_EXPIRY_MINUTES = 10; | ||||||||||||||||||||||||||
| const RESET_OTP_TTL_SECONDS = 300; | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| @Injectable() | ||||||||||||||||||||||||||
| export default class AuthenticationService { | ||||||||||||||||||||||||||
| private readonly logger = new Logger(AuthenticationService.name); | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| constructor( | ||||||||||||||||||||||||||
| @InjectRepository(User) | ||||||||||||||||||||||||||
| private readonly userRepository: Repository<User>, | ||||||||||||||||||||||||||
| private readonly jwtService: JwtService | ||||||||||||||||||||||||||
| @InjectRepository(UserSession) | ||||||||||||||||||||||||||
| private readonly userSessionRepository: Repository<UserSession>, | ||||||||||||||||||||||||||
| private readonly jwtService: JwtService, | ||||||||||||||||||||||||||
| private readonly redisService: RedisService, | ||||||||||||||||||||||||||
| private readonly emailService: EmailService | ||||||||||||||||||||||||||
| ) {} | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| async createNewUser(createUserDto: CreateUserDTO) { | ||||||||||||||||||||||||||
|
|
@@ -26,7 +38,7 @@ export default class AuthenticationService { | |||||||||||||||||||||||||
| throw new CustomHttpException(SYS_MSG.USER_ACCOUNT_EXIST, HttpStatus.BAD_REQUEST); | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| const hashedPassword = await bcrypt.hash(createUserDto.password, 10); | ||||||||||||||||||||||||||
| const hashedPassword = await this.hashPassword(createUserDto.password); | ||||||||||||||||||||||||||
| const user = this.userRepository.create({ | ||||||||||||||||||||||||||
| email: createUserDto.email, | ||||||||||||||||||||||||||
| full_name: createUserDto.full_name, | ||||||||||||||||||||||||||
|
|
@@ -93,7 +105,7 @@ export default class AuthenticationService { | |||||||||||||||||||||||||
| throw new CustomHttpException(SYS_MSG.INVALID_PASSWORD, HttpStatus.BAD_REQUEST); | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| user.password = await bcrypt.hash(newPassword, 10); | ||||||||||||||||||||||||||
| user.password = await this.hashPassword(newPassword); | ||||||||||||||||||||||||||
| await this.userRepository.save(user); | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| return { | ||||||||||||||||||||||||||
|
|
@@ -102,10 +114,72 @@ export default class AuthenticationService { | |||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| private generateOtp(): string { | ||||||||||||||||||||||||||
| return Math.floor(Math.random() * 10 ** OTP_LENGTH) | ||||||||||||||||||||||||||
| .toString() | ||||||||||||||||||||||||||
| .padStart(OTP_LENGTH, '0'); | ||||||||||||||||||||||||||
| async forgotPassword(email: string) { | ||||||||||||||||||||||||||
| const user = await this.userRepository.findOne({ where: { email } }); | ||||||||||||||||||||||||||
| if (user) { | ||||||||||||||||||||||||||
| const otp = this.generateOtp(); | ||||||||||||||||||||||||||
| const key = `reset_otp:${email}`; | ||||||||||||||||||||||||||
| try { | ||||||||||||||||||||||||||
| await this.redisService.set(key, otp, RESET_OTP_TTL_SECONDS); | ||||||||||||||||||||||||||
| await this.emailService.sendForgotPasswordMail( | ||||||||||||||||||||||||||
| email, | ||||||||||||||||||||||||||
| user.full_name, | ||||||||||||||||||||||||||
| `${FRONTEND_RESET_PASSWORD}?email=${email}`, | ||||||||||||||||||||||||||
| otp | ||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. URL-encode the email in the reset link.
🛡️ Proposed fix await this.emailService.sendForgotPasswordMail(
email,
user.full_name,
- `${FRONTEND_RESET_PASSWORD}?email=${email}`,
+ `${FRONTEND_RESET_PASSWORD}?email=${encodeURIComponent(email)}`,
otp
);📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents🧩 Analysis chain🏁 Script executed: #!/bin/bash
# Locate EmailService implementation and inspect sendForgotPasswordMail
fd -t f 'email.service.ts$'
rg -nP -C5 '\bsendForgotPasswordMail\s*\(' --type=tsRepository: hngprojects/flowbrand-be Length of output: 1607 Fix malformed URL construction in sendForgotPasswordMail call. The method expects a base URL and appends Pass only the base URL without query parameters: 🤖 Prompt for AI Agents |
||||||||||||||||||||||||||
| } catch (err) { | ||||||||||||||||||||||||||
| this.logger.error( | ||||||||||||||||||||||||||
| `Failed to issue password reset OTP for user ${user.id}`, | ||||||||||||||||||||||||||
| (err as Error).stack ?? (err as Error).message | ||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||||||||||||||||||||||||||
| return { | ||||||||||||||||||||||||||
| status_code: HttpStatus.OK, | ||||||||||||||||||||||||||
| message: SYS_MSG.FORGOT_PASSWORD_OTP_SENT, | ||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| async resetPassword(email: string, otp: string, newPassword: string) { | ||||||||||||||||||||||||||
| const key = `reset_otp:${email}`; | ||||||||||||||||||||||||||
| const storedOtp = await this.redisService.get(key); | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| if (otp !== storedOtp) { | ||||||||||||||||||||||||||
| throw new CustomHttpException(SYS_MSG.INCORRECT_TOTP_CODE, HttpStatus.BAD_REQUEST); | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| const user = await this.userRepository.findOne({ where: { email } }); | ||||||||||||||||||||||||||
| if (!user) { | ||||||||||||||||||||||||||
| await this.redisService.del(key); | ||||||||||||||||||||||||||
| throw new CustomHttpException(SYS_MSG.INCORRECT_TOTP_CODE, HttpStatus.BAD_REQUEST); | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| user.password = await this.hashPassword(newPassword); | ||||||||||||||||||||||||||
| await this.userRepository.save(user); | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| await this.redisService.del(key); | ||||||||||||||||||||||||||
| await this.redisService.delByPattern(`active_session:${user.id}:*`); | ||||||||||||||||||||||||||
| await this.userSessionRepository.update( | ||||||||||||||||||||||||||
| { user_id: user.id, is_revoked: false }, | ||||||||||||||||||||||||||
| { is_revoked: true, revoked_at: new Date() } | ||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Password change and session revocation can fail half-way through. After Line 138 commits the new hash, any failure in 🤖 Prompt for AI Agents |
||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| return { | ||||||||||||||||||||||||||
| status_code: HttpStatus.OK, | ||||||||||||||||||||||||||
| message: SYS_MSG.PASSWORD_UPDATED, | ||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| private async hashPassword(password: string): Promise<string> { | ||||||||||||||||||||||||||
| return bcrypt.hash(password, 10); | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| private generateOtp(length: number = OTP_LENGTH): string { | ||||||||||||||||||||||||||
| if (!Number.isInteger(length) || length < 1 || length > 10) { | ||||||||||||||||||||||||||
| throw new RangeError('OTP length must be an integer between 1 and 10'); | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
| const max = 10 ** length; | ||||||||||||||||||||||||||
| return randomInt(0, max).toString().padStart(length, '0'); | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| private computeOtpExpiry(): Date { | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| import { ApiProperty } from '@nestjs/swagger'; | ||
| import { IsEmail, IsNotEmpty } from 'class-validator'; | ||
|
|
||
| export class ForgotPasswordDto { | ||
| @ApiProperty({ description: 'Email address of the account', example: 'jane@example.com' }) | ||
| @IsNotEmpty() | ||
| @IsEmail() | ||
| readonly email: string; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| import { ApiProperty } from '@nestjs/swagger'; | ||
| import { IsEmail, IsNotEmpty, IsString, IsStrongPassword, Length, MinLength } from 'class-validator'; | ||
|
|
||
| export class ResetPasswordDto { | ||
| @ApiProperty({ description: 'Email address of the account', example: 'jane@example.com' }) | ||
| @IsNotEmpty() | ||
| @IsEmail() | ||
| readonly email: string; | ||
|
|
||
| @ApiProperty({ description: 'OTP sent to the email', example: '482910' }) | ||
| @IsNotEmpty() | ||
| @IsString() | ||
| @Length(6, 6) | ||
| readonly otp: string; | ||
|
|
||
| @ApiProperty({ description: 'New password', example: 'NewP@ssword123' }) | ||
| @IsNotEmpty() | ||
| @IsString() | ||
| @MinLength(8) | ||
| @IsStrongPassword( | ||
| {}, | ||
| { | ||
| message: | ||
| 'Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character.', | ||
| } | ||
| ) | ||
| readonly newPassword: string; | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.