Skip to content
Open
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
44 changes: 44 additions & 0 deletions __tests__/auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { describe, it, expect } from 'vitest';
import { hashPassword, verifyPassword, generateToken, verifyToken } from '../lib/auth';

describe('Authentication Utilities', () => {
const testPassword = 'securePassword123!';

describe('Password Hashing', () => {
it('should hash password with salt', () => {
const hashedPassword = hashPassword(testPassword);
expect(hashedPassword).toContain(':');
expect(hashedPassword.split(':').length).toBe(2);
});

it('should verify correct password', () => {
const hashedPassword = hashPassword(testPassword);
const isValid = verifyPassword(hashedPassword, testPassword);
expect(isValid).toBeTruthy();
});

it('should not verify incorrect password', () => {
const hashedPassword = hashPassword(testPassword);
const isValid = verifyPassword(hashedPassword, 'wrongPassword');
expect(isValid).toBeFalsy();
});
});

describe('Token Generation and Verification', () => {
it('should generate and verify token', () => {
const userId = '12345';
const token = generateToken(userId);
const decoded = verifyToken(token);

expect(decoded).toBeTruthy();
expect(decoded?.userId).toBe(userId);
});

it('should return null for invalid token', () => {
const invalidToken = 'invalidToken';
const decoded = verifyToken(invalidToken);

expect(decoded).toBeNull();
});
});
});
32 changes: 32 additions & 0 deletions lib/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { createHash } from 'crypto';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';

dotenv.config();

const JWT_SECRET = process.env.JWT_SECRET || 'fallback_secret';
const SALT_ROUNDS = parseInt(process.env.AUTH_SALT_ROUNDS || '10', 10);

export const hashPassword = (password: string): string => {
const salt = createHash('sha256').update(String(Math.random())).digest('hex').slice(0, SALT_ROUNDS);
const hash = createHash('sha256').update(password + salt).digest('hex');
return `${salt}:${hash}`;
};

export const verifyPassword = (storedPassword: string, providedPassword: string): boolean => {
const [salt, originalHash] = storedPassword.split(':');
const hashedProvided = createHash('sha256').update(providedPassword + salt).digest('hex');
return hashedProvided === originalHash;
};

export const generateToken = (userId: string): string => {
return jwt.sign({ userId }, JWT_SECRET, { expiresIn: '24h' });
};

export const verifyToken = (token: string): { userId: string } | null => {
try {
return jwt.verify(token, JWT_SECRET) as { userId: string };
} catch {
return null;
}
};
26 changes: 26 additions & 0 deletions lib/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Pool } from 'pg';
import dotenv from 'dotenv';

dotenv.config();

const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false
});

export const query = async (text: string, params?: any[]) => {
try {
const result = await pool.query(text, params);
return result;
} catch (error) {
console.error('Database query error:', error);
throw error;
}
};

export const getClient = async () => {
const client = await pool.connect();
return client;
};

export default pool;
Loading