this is my hash functions
userSchema.pre('save', async function(next) {
try {
if (this.isModified('password')) {
const hashedPassword = await bcrypt.hash(this.password, 10);
this.password = hashedPassword;
}
next();
} catch (error) {
next(error);
}
});
userSchema.methods.comparePassword = async function(trimmedCandidatePassword, storedHashedPassword) {
try {
const isMatch = await bcrypt.compare(trimmedCandidatePassword, storedHashedPassword);
console.log("bcrypt.compare result:", isMatch); // View the direct bcrypt result
return isMatch;
} catch (error) {
throw new Error(error);
}
};
and this is the login route which handles the route of login logic
router.post('/login', async (req, res) => {
try {
const { username, password,role } = req.body;
const user = await User.findOne({ username });
// Checking is the username exists
if (!user) {
return res.status(401).json({ message: "User doesnt exist" });
}
console.log("Entered Password:", password);
console.log("Stored Hashed Password:", user.password);
const storedHashedPassword = user.password.trim();
const enteredPassword = password.trim();
// Checking password
const isPassWordValid = await user.comparePassword(enteredPassword,storedHashedPassword);
console.log(isPassWordValid)
if (!isPassWordValid) {
return res.status(401).json({ message: "Incorrect Password" });
}
if(role!==user.role){
return res.status(401).json({ message: "you are not assigned for this role" });
}
const token = jwt.sign({
userId: user._id,
role: user.role // Add the user's role to the token
}, process.env.SECRET_KEY);
res.status(200).json({ token });
} catch (error) {
res.status(500).json({ message: "Authentication Failed x2", error: error.message })
}
});
i have { "username":"sarthak@123", "password":"sarthak123", "role":"Doctor" } in my body of route i checked the hash stored in database and still getting always false