feat(auth): password hashing service
This commit is contained in:
@@ -17,6 +17,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@flashcard/shared": "*",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-sqlite3": "^11.0.0",
|
||||
"drizzle-orm": "^0.33.0",
|
||||
"express": "^4.19.0",
|
||||
@@ -25,6 +26,7 @@
|
||||
"zod": "^3.23.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/better-sqlite3": "^7.6.0",
|
||||
"@types/express": "^4.17.0",
|
||||
"@types/multer": "^1.4.0",
|
||||
|
||||
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