In this example, we use the bcrypt module to hash and compare passwords securely. This can be useful for password storage in databases.
Ensure you have the bcrypt
module installed:
npm install bcrypt
// Import necessary modules
import bcrypt from "bcrypt";
import { customErrorHandler } from "../middlewares/errorHandler.js";
// Hashing function
export const hashPassword = async (password, next) => {
try {
// Hash the password with a salt factor of 12
return await bcrypt.hash(password, 12);
} catch (error) {
// Handle errors during hashing
next(new customErrorHandler(400, "Encountered an error in hashing password"));
}
};
// Password comparison function
export const compareHashedPassword = async (password, hashPassword, next) => {
try {
// Compare the input password with the hashed password
return await bcrypt.compare(password, hashPassword);
} catch (error) {
// Handle errors during password comparison
next(new customErrorHandler(400, "Encountered an error in comparing hashed password"));
}
};
- Hashing a Password:
const hashedPassword = await hashPassword("user_password", next);
// 'hashedPassword' now contains the securely hashed password.
- Comparing Passwords:
const isMatch = await compareHashedPassword("user_input_password", hashedPassword, next);
// 'isMatch' will be true if the passwords match, otherwise false.