feat(auth): password hashing service
This commit is contained in:
19
packages/backend/src/services/auth/passwords.test.ts
Normal file
19
packages/backend/src/services/auth/passwords.test.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { hashPassword, verifyPassword } from './passwords.js';
|
||||
|
||||
describe('passwords', () => {
|
||||
it('hashes a password and verifies it', async () => {
|
||||
const hash = await hashPassword('correcthorse');
|
||||
expect(hash).toMatch(/^\$2[aby]\$/);
|
||||
expect(await verifyPassword('correcthorse', hash)).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a wrong password', async () => {
|
||||
const hash = await hashPassword('correcthorse');
|
||||
expect(await verifyPassword('wrong', hash)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false on malformed hash', async () => {
|
||||
expect(await verifyPassword('x', 'not-a-bcrypt-hash')).toBe(false);
|
||||
});
|
||||
});
|
||||
15
packages/backend/src/services/auth/passwords.ts
Normal file
15
packages/backend/src/services/auth/passwords.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import bcrypt from 'bcryptjs';
|
||||
|
||||
const COST = 12;
|
||||
|
||||
export async function hashPassword(plain: string): Promise<string> {
|
||||
return bcrypt.hash(plain, COST);
|
||||
}
|
||||
|
||||
export async function verifyPassword(plain: string, hash: string): Promise<boolean> {
|
||||
try {
|
||||
return await bcrypt.compare(plain, hash);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user