bcrypt.compare JWT with nodeJS, Mongoose always throwing Error

Viewed 58

i am facing this kinda silly issues while i try to implement JWT in NodeJS, Mongoose as my auth mechanism.

let say i tried to implement login feature with this code (NodeJS)

const post_login = async (req, res, next) => {
    const userData = req.body;

    try {
        const user = await User.login(userData);
        res.status(200).json({user: user._id});
    } catch (error) {
        res.status(400).json({});
    }
    // res.json(userData)
};

then i attach this function in my Model data

UserSchema.statics.login = async function(userData){
    const {email, password} = userData;
    const user = await this.findOne({email});
    
    if (user) {
        const auth = await bcrypt.compare(password, user.password)
        if (auth) {
            return user;
        }
        throw Error('Password do not match');
    } 
    throw Error('Email is not registered');
};

i was successfully implement bcrypt.hash while storing my data in mongoDB. but, when i try these code, it always throwing an error (status 4000). after i do some debug, the problem is

  1. While i debug await bcrypt.compare(password, user.password), i found that it looks like comparing between unhashed "password" with stored (hashed) password "user.password"
  2. if i skipped bcrypt.compare, it returns a related document data (even if the provided password doesn't match)
  3. An error message shown
(node:11784) UnhandledPromiseRejectionWarning: Error: data and hash arguments required
    at Object.compare (E:\practice\jwt\node_modules\bcrypt\bcrypt.js:208:17)     
    at E:\practice\jwt\node_modules\bcrypt\promises.js:29:12
    at new Promise (<anonymous>)
    at Object.module.exports.promise (E:\practice\jwt\node_modules\bcrypt\promises.js:20:12)
    at Object.compare (E:\practice\jwt\node_modules\bcrypt\bcrypt.js:204:25)     
    at E:\practice\jwt\models\user-model.js:67:20
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11784) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This 
error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:11784) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the 
Node.js process with a non-zero exit code.
  1. I run on nodeV14

mind anyone know how to fix it, thanks in advance

0 Answers
Related