Files
flyer-crawler.projectium.com/src/routes/auth.routes.test.ts
Torben Sorensen 9757f9dd9f
Some checks failed
Deploy to Test Environment / deploy-to-test (push) Has been cancelled
Refactor MainLayout to use new hooks for flyers and master items; consolidate error handling
Update error handling tests to ensure proper status assignment for errors
2025-12-14 11:05:04 -08:00

521 lines
20 KiB
TypeScript

// --- FIX REGISTRY ---
//
// 2024-08-01: Corrected `auth.routes.test.ts` by separating the mock's implementation into a `vi.hoisted` block and then applying it in the `vi.mock` call at the top level of the module.
// 2024-08-01: Corrected `vi.mock` for `passport.routes` by separating the mock's implementation into a `vi.hoisted` block and then applying it in the `vi.mock` call at the top level of the module. This resolves a variable initialization error.
// 2024-08-01: Moved `vi.hoisted` declaration for `passportMocks` before the `vi.mock` call that uses it. This fixes a "Cannot access before initialization" reference error during test setup by ensuring the hoisted variable is declared before it's referenced.
//
// --- END FIX REGISTRY ---
// src/routes/auth.routes.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';
import supertest from 'supertest';
import express, { Request, Response, NextFunction } from 'express';
import cookieParser from 'cookie-parser';
import * as bcrypt from 'bcrypt';
import passport from 'passport';
import { errorHandler } from '../middleware/errorHandler';
import { UserProfile } from '../types';
// --- FIX: Hoist passport mocks to be available for vi.mock ---
const passportMocks = vi.hoisted(() => {
type PassportCallback = (error: Error | null, user?: Express.User | false, info?: { message: string }) => void;
const authenticateMock = (strategy: string, options: Record<string, unknown>, callback: PassportCallback) => (req: Request, res: any, next: any) => {
// Simulate LocalStrategy logic based on request body
if (req.body.password === 'wrong_password') {
return callback(null, false, { message: 'Incorrect email or password.' });
}
if (req.body.email === 'locked@test.com') {
return callback(null, false, { message: 'Account is temporarily locked. Please try again in 15 minutes.' });
}
if (req.body.email === 'notfound@test.com') {
return callback(null, false, { message: 'Login failed' });
}
// Specific case for strategy error
if (req.body.email === 'dberror@test.com') {
return callback(new Error('Database connection failed'), false);
}
// Default success case
const user = { user_id: 'user-123', email: req.body.email };
// If a callback is provided (custom callback signature), call it
if (callback) {
return callback(null, user);
}
// Standard middleware signature: attach user and call next
req.user = user;
next();
};
return { authenticateMock };
});
// --- 2. Module Mocks ---
// Mock the local passport.routes module to control its behavior.
vi.mock('./passport.routes', () => ({
default: {
authenticate: vi.fn().mockImplementation(passportMocks.authenticateMock),
use: vi.fn(),
initialize: () => (req: any, res: any, next: any) => next(),
session: () => (req: any, res: any, next: any) => next(),
},
// Also mock named exports if they were used in auth.routes.ts, though they are not currently.
isAdmin: vi.fn((req: Request, res: Response, next: NextFunction) => next()),
optionalAuth: vi.fn((req: Request, res: Response, next: NextFunction) => next()),
}));
// Mock the DB connection pool to control transactional behavior
const { mockPool, mockClient } = vi.hoisted(() => {
const client = {
query: vi.fn(),
release: vi.fn(),
};
return {
mockPool: {
connect: vi.fn(() => Promise.resolve(client)),
},
mockClient: client,
};
});
// Mock the Service Layer directly.
// We use async import inside the factory to properly hoist the UniqueConstraintError class usage.
vi.mock('../services/db/index.db', async () => {
const { UniqueConstraintError } = await import('../services/db/errors.db');
return {
userRepo: {
findUserByEmail: vi.fn(),
createUser: vi.fn(),
saveRefreshToken: vi.fn(),
createPasswordResetToken: vi.fn(),
getValidResetTokens: vi.fn(),
updateUserPassword: vi.fn(),
deleteResetToken: vi.fn(),
findUserByRefreshToken: vi.fn(),
deleteRefreshToken: vi.fn(),
},
adminRepo: {
logActivity: vi.fn(),
},
UniqueConstraintError: UniqueConstraintError,
};
});
vi.mock('../services/db/connection.db', () => ({
getPool: () => mockPool,
}));
// Mock the logger
vi.mock('../services/logger.server', () => ({
logger: {
info: vi.fn(),
debug: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
},
}));
// Mock the email service
vi.mock('../services/emailService.server', () => ({
sendPasswordResetEmail: vi.fn(),
}));
// Mock bcrypt
vi.mock('bcrypt', async (importOriginal) => {
const actual = await importOriginal<typeof bcrypt>();
return { ...actual, compare: vi.fn() };
});
// Import the router AFTER mocks are established
import authRouter from './auth.routes';
import * as db from '../services/db/index.db'; // This was a duplicate, fixed.
// Import the actual class so we can spy on its prototype
import { UserRepository } from '../services/db/user.db';
import { UniqueConstraintError } from '../services/db/errors.db'; // Import actual class for instanceof checks
// --- 4. App Setup ---
const app = express();
app.use(express.json({ strict: false }));
app.use(cookieParser());
// Mock req.logIn for passport session handling stubs
app.use((req: Request, res: Response, next: NextFunction) => {
req.logIn = (user: any, cb: any) => {
if (typeof cb === 'function') cb(null);
};
next();
});
app.use('/api/auth', authRouter);
app.use(errorHandler);
// --- 5. Tests ---
describe('Auth Routes (/api/auth)', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.restoreAllMocks(); // Restore spies on prototypes
});
describe('POST /register', () => {
const newUserEmail = 'newuser@test.com';
const strongPassword = 'a-Very-Strong-Password-123!';
it('should successfully register a new user with a strong password', async () => {
// Arrange:
const mockNewUser: UserProfile = {
user_id: 'new-user-id',
user: { user_id: 'new-user-id', email: newUserEmail },
role: 'user',
points: 0,
full_name: 'Test User',
avatar_url: null,
preferences: {}
};
// FIX: Mock the method on the imported singleton instance `userRepo` directly,
// as this is what the route handler uses. Spying on the prototype does not
// affect this already-created instance.
vi.mocked(db.userRepo.createUser).mockResolvedValue(mockNewUser);
vi.mocked(db.userRepo.saveRefreshToken).mockResolvedValue(undefined);
vi.mocked(db.adminRepo.logActivity).mockResolvedValue(undefined);
// Act
const response = await supertest(app)
.post('/api/auth/register')
.send({
email: newUserEmail,
password: strongPassword,
full_name: 'Test User',
});
// Assert
expect(response.status).toBe(201);
expect(response.body.message).toBe('User registered successfully!');
expect(response.body.user.email).toBe(newUserEmail);
expect(response.body.token).toBeTypeOf('string');
expect(db.userRepo.createUser).toHaveBeenCalled();
});
it('should reject registration with a weak password', async () => {
const weakPassword = 'password';
const response = await supertest(app)
.post('/api/auth/register')
.send({
email: 'anotheruser@test.com',
password: weakPassword,
});
expect(response.status).toBe(400);
expect(response.body.message).toContain('Password is too weak');
});
it('should reject registration if the email already exists', async () => {
const dbError = new UniqueConstraintError('User with that email already exists.');
(dbError as any).code = '23505'; // Simulate PG error code
vi.mocked(db.userRepo.createUser).mockRejectedValue(dbError);
const response = await supertest(app)
.post('/api/auth/register')
.send({ email: newUserEmail, password: strongPassword });
expect(response.status).toBe(409); // 409 Conflict
expect(response.body.message).toBe('User with that email already exists.');
expect(db.userRepo.createUser).toHaveBeenCalled();
});
it('should return 500 if a generic database error occurs during registration', async () => {
const dbError = new Error('DB connection lost');
vi.mocked(db.userRepo.createUser).mockRejectedValue(dbError);
const response = await supertest(app)
.post('/api/auth/register')
.send({ email: 'fail@test.com', password: strongPassword });
expect(response.status).toBe(500);
expect(response.body.message).toBe('DB connection lost'); // The errorHandler will forward the message
});
});
describe('POST /login', () => {
it('should successfully log in a user and return a token and cookie', async () => {
// Arrange:
const loginCredentials = { email: 'test@test.com', password: 'password123' };
vi.mocked(db.userRepo.saveRefreshToken).mockResolvedValue(undefined);
// Act
const response = await supertest(app)
.post('/api/auth/login')
.send(loginCredentials);
// Assert
expect(response.status).toBe(200);
expect(response.body.user).toEqual({ user_id: 'user-123', email: loginCredentials.email });
expect(response.body.token).toBeTypeOf('string');
expect(response.headers['set-cookie']).toBeDefined();
});
it('should reject login for incorrect credentials', async () => {
const response = await supertest(app)
.post('/api/auth/login')
.send({ email: 'test@test.com', password: 'wrong_password' });
expect(response.status).toBe(401);
expect(response.body.message).toBe('Incorrect email or password.');
});
it('should reject login for a locked account', async () => {
const response = await supertest(app)
.post('/api/auth/login')
.send({ email: 'locked@test.com', password: 'password123' });
expect(response.status).toBe(401);
expect(response.body.message).toBe('Account is temporarily locked. Please try again in 15 minutes.');
});
it('should return 401 if user is not found', async () => {
const response = await supertest(app)
.post('/api/auth/login') // This was a duplicate, fixed.
.send({ email: 'notfound@test.com', password: 'password123' });
expect(response.status).toBe(401);
});
it('should return 500 if saving the refresh token fails', async () => {
// Arrange:
const loginCredentials = { email: 'test@test.com', password: 'password123' };
vi.mocked(db.userRepo.saveRefreshToken).mockRejectedValue(new Error('DB write failed'));
// Act
const response = await supertest(app).post('/api/auth/login').send(loginCredentials);
// Assert
expect(response.status).toBe(500);
});
it('should return 500 if passport strategy returns an error', async () => {
// This test covers the `if (err)` block in the passport.authenticate callback.
// The mock implementation for passport.authenticate is configured to return an error
// when the email is 'dberror@test.com'.
const response = await supertest(app)
.post('/api/auth/login')
.send({ email: 'dberror@test.com', password: 'any_password' });
expect(response.status).toBe(500);
expect(response.body.message).toBe('Database connection failed');
});
it('should set a long-lived cookie when rememberMe is true', async () => {
// Arrange
const loginCredentials = { email: 'test@test.com', password: 'password123', rememberMe: true };
vi.mocked(db.userRepo.saveRefreshToken).mockResolvedValue(undefined);
// Act
const response = await supertest(app)
.post('/api/auth/login')
.send(loginCredentials);
// Assert
expect(response.status).toBe(200);
const setCookieHeader = response.headers['set-cookie'];
expect(setCookieHeader[0]).toContain('Max-Age=2592000'); // 30 days in seconds
});
});
describe('POST /forgot-password', () => {
it('should send a reset link if the user exists', async () => {
// Arrange
vi.mocked(db.userRepo.findUserByEmail).mockResolvedValue({
user_id: 'user-123',
email: 'test@test.com',
password_hash: 'some_hash',
failed_login_attempts: 0,
last_failed_login: null,
});
vi.mocked(db.userRepo.createPasswordResetToken).mockResolvedValue(undefined);
// Act
const response = await supertest(app)
.post('/api/auth/forgot-password')
.send({ email: 'test@test.com' });
// Assert
expect(response.status).toBe(200);
expect(response.body.message).toContain('a password reset link has been sent');
expect(response.body.token).toBeTypeOf('string');
});
it('should return a generic success message even if the user does not exist', async () => {
vi.mocked(db.userRepo.findUserByEmail).mockResolvedValue(undefined);
const response = await supertest(app)
.post('/api/auth/forgot-password')
.send({ email: 'nouser@test.com' });
expect(response.status).toBe(200);
expect(response.body.message).toContain('a password reset link has been sent');
});
it('should return 500 if the database call fails', async () => {
vi.mocked(db.userRepo.findUserByEmail).mockRejectedValue(new Error('DB connection failed'));
const response = await supertest(app)
.post('/api/auth/forgot-password')
.send({ email: 'any@test.com' });
expect(response.status).toBe(500);
});
it('should still return 200 OK if the email service fails', async () => {
// Arrange
vi.mocked(db.userRepo.findUserByEmail).mockResolvedValue({
user_id: 'user-123',
email: 'test@test.com',
password_hash: 'some_hash',
failed_login_attempts: 0,
last_failed_login: null,
});
vi.mocked(db.userRepo.createPasswordResetToken).mockResolvedValue(undefined);
// Mock the email service to fail
const { sendPasswordResetEmail } = await import('../services/emailService.server');
vi.mocked(sendPasswordResetEmail).mockRejectedValue(new Error('SMTP server down'));
// Act
const response = await supertest(app)
.post('/api/auth/forgot-password')
.send({ email: 'test@test.com' });
// Assert: The route should not fail even if the email does.
expect(response.status).toBe(200);
});
});
describe('POST /reset-password', () => {
it('should reset the password with a valid token and strong password', async () => {
const tokenRecord = { user_id: 'user-123', token_hash: 'hashed-token', expires_at: new Date(Date.now() + 3600000) };
vi.mocked(db.userRepo.getValidResetTokens).mockResolvedValue([tokenRecord]); // This was a duplicate, fixed.
vi.mocked(bcrypt.compare).mockResolvedValue(true as never); // Token matches
vi.mocked(db.userRepo.updateUserPassword).mockResolvedValue(undefined);
vi.mocked(db.userRepo.deleteResetToken).mockResolvedValue(undefined);
vi.mocked(db.adminRepo.logActivity).mockResolvedValue(undefined);
const response = await supertest(app)
.post('/api/auth/reset-password')
.send({ token: 'valid-token', newPassword: 'a-Very-Strong-Password-789!' });
expect(response.status).toBe(200);
expect(response.body.message).toBe('Password has been reset successfully.');
});
it('should reject with an invalid or expired token', async () => {
vi.mocked(db.userRepo.getValidResetTokens).mockResolvedValue([]); // No valid tokens found
const response = await supertest(app)
.post('/api/auth/reset-password')
.send({ token: 'invalid-token', newPassword: 'password123' });
expect(response.status).toBe(400);
expect(response.body.message).toBe('Invalid or expired password reset token.');
});
it('should return 400 for a weak new password', async () => {
const tokenRecord = { user_id: 'user-123', token_hash: 'hashed-token', expires_at: new Date(Date.now() + 3600000) };
vi.mocked(db.userRepo.getValidResetTokens).mockResolvedValue([tokenRecord]);
vi.mocked(bcrypt.compare).mockResolvedValue(true as never);
const response = await supertest(app).post('/api/auth/reset-password').send({ token: 'valid-token', newPassword: 'weak' });
expect(response.status).toBe(400);
});
});
describe('POST /refresh-token', () => {
it('should issue a new access token with a valid refresh token cookie', async () => {
const mockUser = {
user_id: 'user-123',
email: 'test@test.com',
password_hash: 'some_hash',
failed_login_attempts: 0,
last_failed_login: null,
};
vi.mocked(db.userRepo.findUserByRefreshToken).mockResolvedValue(mockUser);
const response = await supertest(app)
.post('/api/auth/refresh-token')
.set('Cookie', 'refreshToken=valid-refresh-token');
expect(response.status).toBe(200);
expect(response.body.token).toBeTypeOf('string');
});
it('should return 401 if no refresh token cookie is provided', async () => {
const response = await supertest(app).post('/api/auth/refresh-token');
expect(response.status).toBe(401);
expect(response.body.message).toBe('Refresh token not found.');
});
it('should return 403 if refresh token is invalid', async () => {
vi.mocked(db.userRepo.findUserByRefreshToken).mockRejectedValue(new Error('Invalid or expired refresh token.'));
const response = await supertest(app)
.post('/api/auth/refresh-token')
.set('Cookie', 'refreshToken=invalid-token'); // This was a duplicate, fixed.
expect(response.status).toBe(403);
});
it('should return 500 if the database call fails', async () => {
// Arrange
vi.mocked(db.userRepo.findUserByRefreshToken).mockRejectedValue(new Error('DB Error'));
// Act
const response = await supertest(app)
.post('/api/auth/refresh-token')
.set('Cookie', 'refreshToken=any-token');
expect(response.status).toBe(500);
expect(response.body.message).toBe('DB Error');
});
});
describe('POST /logout', () => {
it('should clear the refresh token cookie and return a success message', async () => {
// Arrange
vi.mocked(db.userRepo.deleteRefreshToken).mockResolvedValue(undefined);
// Act
const response = await supertest(app)
.post('/api/auth/logout')
.set('Cookie', 'refreshToken=some-valid-token');
// Assert
expect(response.status).toBe(200);
expect(response.body.message).toBe('Logged out successfully.');
// Check that the 'set-cookie' header is trying to expire the cookie
const setCookieHeader = response.headers['set-cookie'];
expect(setCookieHeader).toBeDefined();
expect(setCookieHeader[0]).toContain('refreshToken=;');
expect(setCookieHeader[0]).toContain('Expires=Thu, 01 Jan 1970');
});
it('should still return 200 OK even if deleting the refresh token from DB fails', async () => {
// Arrange
const dbError = new Error('DB connection lost');
vi.mocked(db.userRepo.deleteRefreshToken).mockRejectedValue(dbError);
const { logger } = await import('../services/logger.server');
// Act
const response = await supertest(app)
.post('/api/auth/logout')
.set('Cookie', 'refreshToken=some-token');
// Assert
expect(response.status).toBe(200);
expect(logger.error).toHaveBeenCalledWith('Failed to delete refresh token from DB during logout.', { error: dbError });
});
});
});