- 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
40 lines
1.0 KiB
TypeScript
40 lines
1.0 KiB
TypeScript
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$')
|
|
);
|
|
}
|