Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
80 changes: 80 additions & 0 deletions apps/backend/src/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ describe('AuthController', () => {
// Create mock implementations
const mockAuthService = {
signup: jest.fn(),
confirmForgotPassword: jest.fn(),
};

const mockUsersService = {
create: jest.fn(),
find: jest.fn(),
};

beforeEach(async () => {
Expand All @@ -37,6 +39,14 @@ describe('AuthController', () => {
expect(controller).toBeDefined();
});

it('rejects forgot password for unregistered email', async () => {
mockUsersService.find.mockResolvedValue([]);

await expect(
controller.forgotPassword({ email: 'random@example.com' } as any),
).rejects.toThrow('Account is not registered.');
});

describe('me', () => {
it('returns a display name when first and last name are available', async () => {
const result = await controller.me({
Expand Down Expand Up @@ -65,4 +75,74 @@ describe('AuthController', () => {
expect(result.username).toBe('plain@example.com');
});
});

describe('confirmPassword', () => {
const confirmPasswordBody = {
email: 'user@example.com',
code: '123456',
password: 'newPassword123',
};

it('successfully confirms password reset', async () => {
mockAuthService.confirmForgotPassword.mockResolvedValue(undefined);

await expect(
controller.confirmPassword(confirmPasswordBody as any),
).resolves.toBeUndefined();

expect(mockAuthService.confirmForgotPassword).toHaveBeenCalledWith(
confirmPasswordBody,
);
});

it('throws BadRequestException for invalid verification code', async () => {
const error = new Error('Code mismatch');
(error as any).name = 'CodeMismatchException';
mockAuthService.confirmForgotPassword.mockRejectedValue(error);

await expect(
controller.confirmPassword(confirmPasswordBody as any),
).rejects.toThrow('Confirmation code is incorrect');
});

it('throws BadRequestException for invalid verification code exception', async () => {
const error = new Error('Invalid code');
(error as any).name = 'InvalidVerificationCodeException';
mockAuthService.confirmForgotPassword.mockRejectedValue(error);

await expect(
controller.confirmPassword(confirmPasswordBody as any),
).rejects.toThrow('Confirmation code is incorrect');
});

it('throws BadRequestException for user not found', async () => {
const error = new Error('User not found');
(error as any).name = 'UserNotFoundException';
mockAuthService.confirmForgotPassword.mockRejectedValue(error);

await expect(
controller.confirmPassword(confirmPasswordBody as any),
).rejects.toThrow('User not found');
});

it('throws BadRequestException for expired code', async () => {
const error = new Error('Code expired');
(error as any).name = 'ExpiredCodeException';
mockAuthService.confirmForgotPassword.mockRejectedValue(error);

await expect(
controller.confirmPassword(confirmPasswordBody as any),
).rejects.toThrow('Confirmation code has expired');
});

it('throws BadRequestException for generic error', async () => {
const error = new Error('Some other error');
(error as any).name = 'SomeOtherException';
mockAuthService.confirmForgotPassword.mockRejectedValue(error);

await expect(
controller.confirmPassword(confirmPasswordBody as any),
).rejects.toThrow('Some other error');
});
});
});
37 changes: 33 additions & 4 deletions apps/backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,13 +228,42 @@ export class AuthController {
}

@Post('/forgotPassword')
forgotPassword(@Body() body: ForgotPasswordDto): Promise<void> {
return this.authService.forgotPassword(body.email);
async forgotPassword(@Body() body: ForgotPasswordDto): Promise<void> {
const registeredUsers = await this.usersService.find(body.email);

if (!registeredUsers.length) {
throw new BadRequestException('Account is not registered.');
}

try {
await this.authService.forgotPassword(body.email);
} catch (error: unknown) {
console.error('Forgot password error:', error);
throw new BadRequestException(this.getErrorMessage(error));
}
}

@Post('/confirmPassword')
confirmPassword(@Body() body: ConfirmPasswordDto): Promise<void> {
return this.authService.confirmForgotPassword(body);
async confirmPassword(@Body() body: ConfirmPasswordDto): Promise<void> {
try {
await this.authService.confirmForgotPassword(body);
} catch (error: unknown) {
console.error('Confirm password error:', error);
// Map Cognito errors to user-friendly messages
if (error instanceof Error) {
const errName = (error as any).name || '';
switch (errName) {
case 'InvalidVerificationCodeException':
case 'CodeMismatchException':
throw new BadRequestException('Confirmation code is incorrect');
case 'UserNotFoundException':
throw new BadRequestException('User not found');
case 'ExpiredCodeException':
throw new BadRequestException('Confirmation code has expired');
}
}
throw new BadRequestException(this.getErrorMessage(error));
}
}

@Post('/delete')
Expand Down
3 changes: 2 additions & 1 deletion apps/backend/src/donations/donations.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { DonationsService } from './donations.service';
import { CreateDonationRequest } from './mappers';
import { DonationResponseDto } from './dtos/donation-response-dto';
import { DonationsRepository } from './donations.repository';
import { Goal } from './goal.entity';
// mock donations

// invalid donation: non positive donation amount
Expand Down Expand Up @@ -242,7 +243,7 @@ describe('DonationsService', () => {
providers: [
DonationsService,
{ provide: getRepositoryToken(Donation), useValue: repoMock },

{ provide: getRepositoryToken(Goal), useValue: {} },
{ provide: DonationsRepository, useValue: mockDonationsRepository },
],
}).compile();
Expand Down
21 changes: 21 additions & 0 deletions apps/frontend/src/api/apiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ export type AuthResponse = {
idToken: string;
};
export type RefreshRequest = { refreshToken: string; userSub: string };
export type ConfirmPasswordRequest = {
email: string;
confirmationCode: string;
newPassword: string;
};

type ApiError = { error?: string; message?: string };

Expand Down Expand Up @@ -107,6 +112,22 @@ export class ApiClient {
}
}

public async forgotPassword(email: string): Promise<void> {
try {
await this.axiosInstance.post('/api/auth/forgotPassword', { email });
} catch (err: unknown) {
this.handleAxiosError(err, 'Failed to send password reset email');
}
}

public async confirmPassword(body: ConfirmPasswordRequest): Promise<void> {
try {
await this.axiosInstance.post('/api/auth/confirmPassword', body);
} catch (err: unknown) {
this.handleAxiosError(err, 'Failed to reset password');
}
}

public async getActiveGoalSummary(): Promise<ActiveGoalResponse> {
try {
const res = await this.axiosInstance.get('/api/donations/goal/active');
Expand Down
6 changes: 3 additions & 3 deletions apps/frontend/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { AuthProvider } from '@components/AuthProvider';
import { ProtectedRoute } from '@components/ProtectedRoute';
import { AdminRoute } from '@components/AdminRoute';
import { LoginPage } from '@containers/auth/LoginPage';
import { ConfirmSentEmailPage } from '@containers/auth/ConfirmSentEmailPage';
import { ResetPasswordPage } from '@containers/auth/ResetPasswordPage';
import { ConfirmRegisteredPage } from '@containers/auth/ConfirmRegisteredPage';
import { DashboardPage } from '@containers/dashboard/DashboardPage';
import { DonorStatsChart } from '@components/DonorStatsChart';
Expand All @@ -30,8 +30,8 @@ const router = createBrowserRouter([
element: <LoginPage />,
},
{
path: '/confirm-sent-email',
element: <ConfirmSentEmailPage />,
path: '/reset-password',
element: <ResetPasswordPage />,
},
{
path: '/confirm-registered',
Expand Down
55 changes: 36 additions & 19 deletions apps/frontend/src/containers/auth/LoginPage.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../../components/AuthProvider';
import { Button } from '../../components/ui/button';
Expand All @@ -14,6 +14,8 @@ import {
} from '@components/ui/input-group';
import { EyeIcon, EyeOffIcon } from 'lucide-react';
import { PasswordCriterion } from './PasswordCriterion';
import { usePasswordValidation } from './usePasswordValidation';
import apiClient from '@api/apiClient';

enum AuthPage {
Login,
Expand All @@ -31,6 +33,7 @@ export const LoginPage: React.FC = () => {
const [showConfirmPassword, setShowConfirmPassword] = useState(false);

const [error, setError] = useState('');
const [success, setSuccess] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [authPage, setAuthPage] = useState<AuthPage>(AuthPage.Login);

Expand All @@ -40,30 +43,31 @@ export const LoginPage: React.FC = () => {

const locationState = location.state as {
from?: { pathname: string };
message?: string;
} | null;
const from = locationState?.from?.pathname || '/dashboard';

const hasMinLength = password.length >= 8;
const hasUppercase = /[A-Z]/.test(password);
const hasLowercase = /[a-z]/.test(password);
const hasNumber = /\d/.test(password);
const hasSpecialChar = /[^A-Za-z0-9]/.test(password);
const passwordsMatch =
password.length > 0 &&
confirmPassword.length > 0 &&
password === confirmPassword;
const allCriteriaMet =
hasMinLength &&
hasUppercase &&
hasLowercase &&
hasNumber &&
hasSpecialChar &&
passwordsMatch;
useEffect(() => {
if (locationState?.message) {
setSuccess(locationState.message);
}
}, [locationState?.message]);

const {
hasMinLength,
hasUppercase,
hasLowercase,
hasNumber,
hasSpecialChar,
passwordsMatch,
allCriteriaMet,
} = usePasswordValidation(password, confirmPassword);

const showAuthFieldError =
authPage === AuthPage.Login &&
!!error &&
error !== 'Account created successfully! Please sign in.';
error !== 'Account created successfully! Please sign in.' &&
!success;

const headerText = (() => {
switch (authPage) {
Expand Down Expand Up @@ -105,7 +109,8 @@ export const LoginPage: React.FC = () => {
navigate('/confirm-registered', { replace: true });
setError('Account created successfully! Please sign in.');
} else if (authPage === AuthPage.ForgotPassword) {
navigate('/confirm-sent-email', { replace: true });
await apiClient.forgotPassword(email);
navigate('/reset-password', { replace: true, state: { email } });
}
} catch (err: unknown) {
console.error('Auth error:', err);
Expand Down Expand Up @@ -155,6 +160,12 @@ export const LoginPage: React.FC = () => {
className="flex flex-col gap-4 mt-10"
noValidate
>
{success && (
<p className="text-sm text-[#12BA82] font-medium" role="status">
{success}
</p>
)}

{authPage === AuthPage.Signup && (
<div className="flex gap-4">
<div className="flex-1">
Expand Down Expand Up @@ -220,6 +231,12 @@ export const LoginPage: React.FC = () => {
</span>
</div>

{authPage === AuthPage.ForgotPassword && error && (
<p className="-mt-2 text-sm text-[#B4444D]" role="alert">
{error}
</p>
)}

{authPage !== AuthPage.ForgotPassword && (
<div>
<Label
Expand Down
Loading
Loading