why does the compare method of bcrypt returns false even when i enter the right password?

Advertisements

I am using Postman to test the login API. The register API works fine and hashes the password before saving it to the database. but when I try to log in with the same credentials, it says the password does not match.

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");

const Schema = mongoose.Schema;
const userSchema = new Schema({
    username: {
        type: String, 
        required: true, 
        unique: true,
        trim: true,
        minlength: 5
    },
    email: {
        type:String, 
        required: true, 
        unique: true, 
        trim: true
    },
    password: {
        type: String, 
        required: true,
        trim: true, 
        lowercase: true,
        minlength: 6
    }
});

This is the middleware to encrypt the password

userSchema.pre("save", async function (next) {

    try{
        const user = this;
        if (!user.isModified("password")) {
          return next();
        }
        const salt = await bcrypt.genSalt(10);
        const hash = await bcrypt.hash(user.password, salt);
        user.password = hash;
        next();
    }
    catch (error) {
        throw new Error(error);
    }

  });

This is the login functionality. whenever I enter a correct username and password, it says wrong password.

try{
        const {username, password} = req.body;
        const { error } = loginValidation.validate(req.body);
    
        if (error) {
            return res.status(400).json({ message: error.details[0].message, type: "error"});
        }
    
        const existingUser = await User.findOne({ username });
        
        if (!existingUser){
            return res.status(401).json({message:"Invalid username", type:"error"});
        }

        const passwordMatch = await bcrypt.compare(password, existingUser.password);
        if(!passwordMatch){
            return res.status(401).json({message:"Invalid password", type:"error"});
        }

        res.status(200).json({message: "Login successful", type:"success"});

    }catch(error){
        console.log(error.message + "Error from controllers/auth.js");
        res.status(500).json({message:"Error authenticating user", type:"error"});
    }
}```

>Solution :

It looks like you are converting the password to lowercase in the schema. Remove lowercase: true in the password field and try it again.

Leave a ReplyCancel reply