Skip to content
This repository was archived by the owner on May 12, 2026. It is now read-only.
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,6 @@ RESEND_SMTP_HOST=smtp.resend.com
RESEND_SMTP_PORT=465
RESEND_SMTP_USER=resend
RESEND_SMTP_API_KEY=
MAIL_FROM="FlowBrand <flowbrand@hng14.com>"
MAIL_FROM="FlowBrand <flowbrand@hng14.com>"

FRONTEND_URL=
2 changes: 1 addition & 1 deletion scripts/test-resend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ async function main() {
console.log(' Accepted :', info.accepted);
}

main().catch((err) => {
main().catch(err => {
console.error('SMTP error:', err.message);
process.exit(1);
});
2 changes: 1 addition & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,4 @@ import mailerConfig from '@config/mailer.config';
],
controllers: [HealthController, ProbeController],
})
export class AppModule { }
export class AppModule {}
23 changes: 23 additions & 0 deletions src/modules/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import AuthenticationService from './auth.service';
import { CreateUserDTO } from './dto/create-user.dto';
import { LoginDto } from './dto/login.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
import { ForgotPasswordDto } from './dto/forgot-password.dto';
import { ResetPasswordDto } from './dto/reset-password.dto';

@ApiTags('Authentication')
@Controller('auth')
Expand Down Expand Up @@ -45,4 +47,25 @@ export default class RegistrationController {
const user = request['user'] as { id: string };
return this.authService.changePassword(user.id, body.oldPassword, body.newPassword);
}

@skipAuth()
@Post('forgot-password')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Request a password reset OTP' })
@ApiBody({ type: ForgotPasswordDto })
@ApiResponse({ status: HttpStatus.OK, description: SYS_MSG.FORGOT_PASSWORD_OTP_SENT })
async forgotPassword(@Body() body: ForgotPasswordDto) {
return this.authService.forgotPassword(body.email);
}

@skipAuth()
@Post('reset-password')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Reset password using OTP' })
@ApiBody({ type: ResetPasswordDto })
@ApiResponse({ status: HttpStatus.OK, description: SYS_MSG.PASSWORD_UPDATED })
@ApiResponse({ status: HttpStatus.BAD_REQUEST, description: SYS_MSG.INCORRECT_TOTP_CODE })
async resetPassword(@Body() body: ResetPasswordDto) {
return this.authService.resetPassword(body.email, body.otp, body.newPassword);
}
}
3 changes: 3 additions & 0 deletions src/modules/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import AuthenticationService from './auth.service';
import { AuthMetadata } from './entities/auth-metadata.entity';
import { UserSession } from './entities/user-session.entity';
import type { StringValue } from 'ms';
import { EmailModule } from '@modules/email/email.module';
import { EmailService } from '@modules/email/email.service';

const expiry = authConfig().jwtExpiry;
@Module({
Expand All @@ -24,6 +26,7 @@ const expiry = authConfig().jwtExpiry;
expiresIn: `${expiry}` as unknown as StringValue,
},
}),
EmailModule,
],
exports: [TypeOrmModule],
})
Expand Down
90 changes: 82 additions & 8 deletions src/modules/auth/auth.service.ts
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;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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) {
Expand All @@ -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,
Expand Down Expand Up @@ -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 {
Expand All @@ -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
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

URL-encode the email in the reset link.

${FRONTEND_RESET_PASSWORD}?email=${email} interpolates the address verbatim. Addresses containing + (e.g., user+tag@example.com), &, or = will be misparsed by the frontend (+ decodes to space), producing a broken prefill or, worse, query-string injection. Use encodeURIComponent.

🛡️ Proposed fix
         await this.emailService.sendForgotPasswordMail(
           email,
           user.full_name,
-          `${FRONTEND_RESET_PASSWORD}?email=${email}`,
+          `${FRONTEND_RESET_PASSWORD}?email=${encodeURIComponent(email)}`,
           otp
         );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await this.emailService.sendForgotPasswordMail(
email,
user.full_name,
`${FRONTEND_RESET_PASSWORD}?email=${email}`,
otp
);
await this.emailService.sendForgotPasswordMail(
email,
user.full_name,
`${FRONTEND_RESET_PASSWORD}?email=${encodeURIComponent(email)}`,
otp
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/modules/auth/auth.service.ts` around lines 124 - 129, The reset URL is
built without encoding the email, causing addresses with characters like +, &, =
to be misparsed; update the call in auth.service.ts where
this.emailService.sendForgotPasswordMail(...) is invoked (the call that passes
`${FRONTEND_RESET_PASSWORD}?email=${email}`) to wrap the email with
encodeURIComponent (i.e., use
`${FRONTEND_RESET_PASSWORD}?email=${encodeURIComponent(email)}`) so the query
parameter is safely URL-encoded before being sent to the frontend.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Locate EmailService implementation and inspect sendForgotPasswordMail
fd -t f 'email.service.ts$'
rg -nP -C5 '\bsendForgotPasswordMail\s*\(' --type=ts

Repository: hngprojects/flowbrand-be

Length of output: 1607


Fix malformed URL construction in sendForgotPasswordMail call.

The method expects a base URL and appends ?token= to it (line 58 in email.service.ts), but the call passes ${FRONTEND_RESET_PASSWORD}?email=${email}, which already contains query parameters. This results in a malformed URL like {FRONTEND_RESET_PASSWORD}?email={email}?token={otp}.

Pass only the base URL without query parameters:

await this.emailService.sendForgotPasswordMail(
  email,
  user.full_name,
  FRONTEND_RESET_PASSWORD,
  otp
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/modules/auth/auth.service.ts` around lines 124 - 129, The call to
sendForgotPasswordMail in auth.service.ts is passing a URL with its own query
string (`${FRONTEND_RESET_PASSWORD}?email=${email}`) but email.service.ts
(sendForgotPasswordMail) appends `?token=` to the base URL, producing a
malformed URL; update the call to pass only the base FRONTEND_RESET_PASSWORD (no
query params) to sendForgotPasswordMail and leave token construction to
email.service.ts so the final link becomes
`${FRONTEND_RESET_PASSWORD}?token=${otp}` (ensure sendForgotPasswordMail still
receives email and user.full_name as before).

} catch (err) {
this.logger.error(
`Failed to issue password reset OTP for user ${user.id}`,
(err as Error).stack ?? (err as Error).message
);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
Comment thread
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);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
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() }
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Password change and session revocation can fail half-way through.

After Line 138 commits the new hash, any failure in del, delByPattern, or userSessionRepository.update leaves a partially-reset account. The worst case is a changed password with old sessions still valid, and Line 140 deletes the OTP before the revocation work has completed, so the user cannot safely retry. This flow needs coordinated failure handling: wrap the SQL writes in a transaction, perform revocation before consuming the OTP, and make the Redis cleanup retryable/idempotent.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/modules/auth/auth.service.ts` around lines 137 - 145, The current flow
updates the password (user.password = await this.hashPassword(...); await
this.userRepository.save(user)) then performs Redis and session revocation,
which can leave the account in an inconsistent state; instead wrap the DB
mutations (userRepository.save and userSessionRepository.update) in a single
transaction so both the new password and is_revoked updates are atomic (use your
ORM/transaction helpers around save and update in AuthService), perform session
revocation via userSessionRepository.update (and any DB-side flags) before
deleting the OTP, then only delete the OTP key (redisService.del) after the DB
transaction commits; make Redis cleanup calls (redisService.del and
redisService.delByPattern) idempotent/retryable (retry on transient errors and
ignore “not found” outcomes) so failures in Redis don’t leave the DB
half-changed, and surface/throw errors if the DB transaction fails so the caller
can retry.


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 {
Expand Down
9 changes: 9 additions & 0 deletions src/modules/auth/dto/forgot-password.dto.ts
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;
}
28 changes: 28 additions & 0 deletions src/modules/auth/dto/reset-password.dto.ts
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;
}
Loading
Loading