I am working on the backend logic for the login page, so after I successfully register a user I immediately try to login with the same details I used but I am getting a Wrong credentials message from json
{
"success": false,
"message": "wrong credentials",
"statusCode": 401
}
I tried to console log the password first and compare it to the one in my database, and it is the same but I am getting success:false message. For reference this is my login controller:
import User from "../models/User.model.js";
import catchAsyncErrors from "../utils/catchAsyncErrors.js";
import bcryptjs from 'bcryptjs';
import jwt from 'jsonwebtoken'
import { ErrorHandler} from '../utils/errorHandler.js'
const loginUser = catchAsyncErrors(async (req, res, next) => {
const { email, password } = req.body;
try {
const validUser = await User.findOne({ email }).select("+password");
if (!validUser) return next(ErrorHandler(404, 'User not found'));
const validPassword = bcryptjs.compareSync(password, validUser.password);
console.log('password:', password);
console.log('validUserPassword:', validUser.password);
console.log('validPassword:', validPassword);
if (!validPassword) return next(ErrorHandler(401, 'wrong credentials'));
const token = jwt.sign({ id: validUser._id }, process.env.JWT_SECRET);
const { password: hashedPassword, ...rest } = validUser._doc;
const expiryDate = new Date(Date.now() + 3600000); // 1 hour
res
.cookie('access_token', token, { httpOnly: true, expires: expiryDate })
.status(200).json({message : 'User is logged in Succesfully'});
} catch (error) {
next(error);
}
});
export default loginUser;
and this is the result I am getting from the console too
password: asdfghjk
validUserPassword: $2b$10$bRzLI8rpbUustsNiQP4MbeubmwFaSOgeEdJHZXE8QG3ilCTwZAYLK
validPassword: false
any idea on what might be the problem?
I have tried changing the credentials and making sure that I am doing everything correctly. And also, checking that the hashed password in the database and the userId.password are the same and the password I typed is the unhashed version of the userId.password