Home > Blockchain >  Bcrypt compare password stays invalid even is password is correct on login
Bcrypt compare password stays invalid even is password is correct on login

Time:06-03

I'm trying to compare a password from my database with the password on login.

req.body.wachtwoord is the password send to the API to check.

results.0.wachtwoord is the hashed password in the database.

It doesn't matter if I enter the right or wrong password on login, the error still says Password is invalid

Here is my code for login to compare the 2 passwords:

bcrypt.compare(req.body.wachtwoord, results[0].wachtwoord, function(err, res) {
    if (err) {
        logger.error(err);
        res.status(err.status).json(err);
    }
    if (res) {
        // Send JWT
        logger.info("passwords matched, sending userinfo en valid token.");
        const { password, ...userinfo } = results[0];
        const payload = { docentID: userinfo.docentID, };

        logger.debug(payload);

        jwt.sign(
             payload,
             jwtSecretKey, { expiresIn: "25d" },
             function(err, token) {
                 if (token) {
                     logger.info("User logged in, sending: ", userinfo);
                     res.status(200).json({
                         status: 200,
                         result: {...userinfo, token },
                     });
                 }
             }
        );
    } else {
        logger.info("Password invalid");
            res.status(401).json({
                status: 401,
                message: "Password invalid.",
                datetime: new Date().toISOString,
            });
    }
});

Here's my full repo if you want to take a look for an error. The password is being hashed in user.controller.js and is compared to the database in auth.controller.js.

Thanks in advance.

CodePudding user response:

You're comparing against results[0].wachtwoord, but further up in the code the property seems to be called password:

const { password, ...userinfo } = results[0];
        ^^^^^^^^

CodePudding user response:

My password was being stored in the database at 50 characters. This is too short for the bycrypt hash. I changed the length to 60 and now my compare works. There was nothing wrong with my code for comparing and hashing ;)

  • Related