When i am logging in with the correct credentials it is saying they are invalid
and i can not figure out why.
auth.routes.js
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/user.model.js'); //
// User registration endpoint
router.post('/register', async (req, res) => {
const { username, email, password } = req.body;
console.log(`Registration attempt for username: ${username}, email: ${email}`); // Log the attempted registration details
try {
let user = await User.findOne({ email });
if (user) {
console.log(`User already exists with email: ${email}`); // Log if user already exists
return res.status(400).json({ msg: 'User already exists' });
}
console.log(`Creating new user with email: ${email}`);
user = new User({
username,
email,
password
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
console.log(`User created successfully: ${user.id}`);
const payload = {
user: {
id: user.id
}
};
jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: 360000 }, (err, token) => {
if (err) {
console.error(`Error generating JWT for user: ${email}`, err);
throw err; // Log and throw the error if JWT generation fails
}
console.log(`JWT generated for user: ${email}`);
res.json({ token });
});
} catch (err) {
console.error(`Server error during registration for username: ${username}, email: ${email}`, err.message);
res.status(500).send('Server error');
}
});
// Simplified User login endpoint with detailed diagnostic logging
router.post('/login', async (req, res) => {
const { email, password } = req.body;
console.log(`[Login Attempt] Email: ${email}`);
try {
// Step 1: Find the user by email
const user = await User.findOne({ email });
if (!user) {
console.log(`[Error] No user found for email: ${email}`);
return res.status(400).json({ msg: 'Invalid Credentials' });
}
console.log(`[Success] User found for email: ${email}, Username: ${user.username}`);
// Step 2: Compare the submitted password with the user's stored hashed password
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) {
console.log(`[Error] bcrypt comparison error: `, err);
return res.status(500).send('Server error during password comparison');
}
if (!isMatch) {
console.log(`[Mismatch] Password does not match for user: ${email}`);
console.log(`[Debug] Submitted password: ${password}`); // # FOR DEBUG ONLY
return res.status(400).json({ msg: 'Invalid Credentials' });
}
// Step 3: Password matches, proceed to generate JWT
console.log(`[Success] Password matches for user: ${email}`);
const payload = {
user: { id: user.id }
};
jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: 360000 }, (err, token) => {
if (err) {
console.error(`[Error] JWT generation error for user: ${email}`, err);
return res.status(500).send('Server error during JWT generation');
}
console.log(`[Success] JWT generated for user: ${email}`);
res.json({ token });
});
});
} catch (err) {
console.error(`[Server Error] During login for user: ${email}`, err.message);
res.status(500).send('Server error');
}
});
module.exports = router;
user.model.js
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
// Define the schema for our user model
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
trim: true, // Removes whitespace from both ends of a string
minlength: 3 // Minimum length of the username
},
email: {
type: String,
required: true,
unique: true,
trim: true, // Removes whitespace from both ends of a string
match: [/.+@.+..+/, 'Please fill a valid email address'] // Regex to validate email format
},
password: {
type: String,
required: true,
minlength: 6 // Minimum length of the password
}
}, {
timestamps: true // Automatically adds createdAt and updatedAt fields
});
// Pre-save hook to hash the password before saving it to the database
userSchema.pre('save', async function(next) {
// Only hash the password if it has been modified (or is new)
if (!this.isModified('password')) return next();
try {
// Generate a salt and use it to hash the password
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
next();
} catch (error) {
next(error);
}
});
// Instance method to check if the provided password matches the hashed password in the database
userSchema.methods.matchPassword = async function(enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
// Create the model from the schema and export it
const User = mongoose.model('User', userSchema, 'users');
module.exports = User;
output i am getting
"Server started on port 5000 MongoDB Connected [Login Attempt] Email: email i used [Success] User found for email: email i used, Username: username i used [Mismatch] Password does not match for user: email i used [Debug] Submitted password: password"
I have signed up succesfully with the output
_id 65c51a381f0331aa2edfb9d5 username "username i used" email "email i used" password "$2a$ hashed pass" createdAt 2024-02-08T18:15:20.965+00:00 updatedAt 2024-02-08T18:15:20.965+00:00 __v 0
in the database, but when i login it says invalid credentials.
If you have any idea what i could do here to fix this, please let me know. I have been debugging none stop and i originally thought the password wasnt being compared properly when logging in, but it is as i printed in the debug logs and it outputted as the decrypted password, thanks.