Bcrypt.compare returns false. I checked about 10 questions in here, but still couldn’t figure it out. My user model doesn’t trim passwords. Mongodb used to store hashed password. Implemented step by step checks. Hashed password is returned correctly. Ensured that the correct password is used as an input. Consulted with genAI with no success. Please help.
userLogin: async (parent, { email, password }, context) => {
try {
// Check if the rate limit has been exceeded
if (context.req.rateLimit && context.req.rateLimit.remaining <= 0) {
// Log rate limit exceeded
logWarn(`Rate limit exceeded for email: ${email}`);
// Throw an error if the rate limit has been exceeded
throw new Error('Too many login attempts, please try again later.');
}
// Find the user by email
const user = await User.findOne({ email });
// Log the user object
logInfo(`User found: ${JSON.stringify(user)}`);
// Check if the user exists
if (!user) {
// Log failed login attempt
logError(`Failed login attempt for email: ${email}`);
// Throw an error if the user does not exist
throw new Error('User not found');
}
// Log the hashed password stored in the database
logInfo(`Hashed password from database: ${user.password}`);
// Log the provided password
logInfo(`Provided password: ${password}`);
// Check if the provided password matches the hashed password stored in the database
const isMatch = await bcrypt.compare(password, user.password);
// Log the password comparison result
logInfo(`Password match: ${isMatch}`);
if (!isMatch) {
// Log failed login attempt
logError(`Failed login attempt for email: ${email}`);
// Throw an error if the password is incorrect
throw new Error('Invalid email or password');
}
// Generate a JWT token
const token = jwt.sign({ userId: user._id }, 'your_jwt_secret_here', {
expiresIn: '1h',
});
// Log successful login
logInfo(`User logged in: ${user.email}`);
// Return the token and the user ID
return {
token,
userId: user._id,
};
} catch (error) {
// Log the error
logError(`Error during login: ${error.message}`);
throw error;
}
},