I’m having issues with bcryptjs
while handling passwords in my application. Registering users works fine, but logging in using the same password is giving me errors. I have made sure that the password is correct, yet it still doesn’t match. It seems that bcryptjs
is not working for me as intended.
Here is my code for the login endpoint in Node.js:
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const UserModel = require('../models/user_model');
const router = express.Router();
const SECRET_KEY = 'secretKey';
router.post('/login', async (req, res) => {
const { email, password } = req.body;
console.log('Login attempt with email:', email);
try {
const user = await UserModel.findOne({ email });
if (!user) {
console.log('User not found');
return res.status(400).json({ message: 'Invalid email or password' });
}
console.log('Stored user record:', user);
const isMatch = await bcrypt.compare(password, user.password);
console.log('Password comparison result:', isMatch);
if (!isMatch) {
console.log('Password does not match');
return res.status(400).json({ message: 'Invalid email or password' });
}
const token = jwt.sign({ userId: user._id }, SECRET_KEY);
res.json({ token });
} catch (error) {
console.error('Error logging in:', error);
res.status(500).json({ error: 'Error logging in' });
}
});
module.exports = router;
And here is the React code for handling the login form submission:
import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
const Login = () => {
const [form, setForm] = useState({ email: '', password: '' });
const navigate = useNavigate();
const handleSubmit = async (event) => {
event.preventDefault();
try {
const response = await axios.post('http://localhost:5500/users/login', form, {
headers: { 'Content-Type': 'application/json' }
});
localStorage.setItem('token', response.data.token);
loadCart(); // Assuming you have a function to load the cart
navigate('/profile');
} catch (error) {
console.error('Error logging in:', error);
alert('Invalid email or password');
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
name="email"
value={form.email}
onChange={(e) => setForm({ ...form, email: e.target.value })}
required
/>
<input
type="password"
name="password"
value={form.password}
onChange={(e) => setForm({ ...form, password: e.target.value })}
required
/>
<button type="submit">Login</button>
</form>
);
};
export default Login;
Here is the console output:
Login attempt with email: [email protected]
Password comparison result: false
Stored user record: {
_id: new ObjectId('666bc37b7280ededaca09d72'),
fullName: 'Alex Gray',
email: '[email protected]',
password: '$2a$10$YJoBVSDWBeJ4o6e47dAR5u0wFSPv.FkLN0qshs0oYDBXQn3aYYK7e',
cart: [],
__v: 0
}
Password comparison result: false
Password does not match
I am certain that the email and password are correct. The stored password in the database is hashed, and it appears to be correct as well. I’ve logged the stored user record and the result of the password comparison, and it consistently returns false
.
Has anyone encountered this issue before, or does anyone have suggestions on what might be going wrong? Thanks!