feat(auth): add bcrypt password hashing service
- Add password hashing and verification utilities - Implement bcrypt hash detection helper - Support configurable salt rounds from unified config - Replace plaintext password storage with secure hashing
This commit is contained in:
39
services/auth/password.service.ts
Normal file
39
services/auth/password.service.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import bcrypt from 'bcryptjs';
|
||||||
|
import { getAuthConfig } from '../../config/unified.config';
|
||||||
|
|
||||||
|
const DEFAULT_ROUNDS = 10;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hash a plaintext password using bcrypt.
|
||||||
|
* Falls back to a sane default if auth config is unavailable.
|
||||||
|
*/
|
||||||
|
export async function hashPassword(plainPassword: string): Promise<string> {
|
||||||
|
const rounds = getAuthConfig()?.bcryptRounds ?? DEFAULT_ROUNDS;
|
||||||
|
return bcrypt.hash(plainPassword, rounds);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compare a plaintext password against a stored bcrypt hash.
|
||||||
|
*/
|
||||||
|
export async function verifyPassword(
|
||||||
|
plainPassword: string,
|
||||||
|
hashedPassword?: string | null
|
||||||
|
): Promise<boolean> {
|
||||||
|
if (!hashedPassword) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return bcrypt.compare(plainPassword, hashedPassword);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convenience helper to decide whether a password needs hashing.
|
||||||
|
* Useful when dealing with legacy or seeded data.
|
||||||
|
*/
|
||||||
|
export function isBcryptHash(value?: string | null): boolean {
|
||||||
|
if (!value) return false;
|
||||||
|
return (
|
||||||
|
value.startsWith('$2a$') ||
|
||||||
|
value.startsWith('$2b$') ||
|
||||||
|
value.startsWith('$2y$')
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user