Can't seem to fix undefined await result

Viewed 55

I need to compare passwords with Bcrypt library.

here's my code:

bcrypt.js

const bcrypt = require('bcrypt');
const saltRounds = 10;

var Bcrypt = () => {

}

Bcrypt.encrypt = async function(password) {
    const hashedPassword = await bcrypt.hash(password, saltRounds)
    return hashedPassword
}

Bcrypt.compare = async function(password, hashed_password) {
    await bcrypt.compare(password, hashed_password, function(err, result) {
        return result;
    });
}

module.exports = Bcrypt;

userMethods.js

const Bcrypt = require('../../global-functions/bcrypt');

var login = async(req) => {
    var user = {
        username: req.body.username,
        password: req.body.password
    }
    if (!user.username || !user.password) {
        return ({ error: "Login details are required to continue." });
    }
    return new Promise((resolve, reject) => {
        db.query("SELECT name,username,email,password FROM users WHERE username = ?", [req.body.username], function(err, rows) {
            if (err) {
                console.log("error: ", err);
                reject(err);
            } else {
                var compared_result = Bcrypt.compare(user.password, rows[0].password); // returns **undefined**
            }

            if (compared_result) {
                resolve({ success: compared_result, username: rows[0].username });
            } else {
                resolve({ error: "wrong username or password!" });
            }
        });
    });
}

when I try to add await before Bcrypt.compare I get an "await is only valid in async function" error.

I would appreciate any help.

1 Answers

Do you want to put it before this Bcrypt.compare

   Bcrypt.compare = async function(password, hashed_password) {
        await bcrypt.compare(password, hashed_password, function(err, result) {
            return result;
        });
    }
    

Then you have to write this code into a outer function and give async there then use await inside

async function()
{
       await Bcrypt.compare = async function(password, hashed_password) {
            await bcrypt.compare(password, hashed_password, function(err, result) {
                return result;
            });
        }
}
        

I think this might solve your problem

Related