简体   繁体   中英

How to use bcrypt.compare in mongoose model?

I am trying to implement the login function in my express API. Below are my controller and the model functions related to the authentication process.

auth.controller

import User from '../models/user.model';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';

dotenv.config({path: './src/.env'});

const jwtSecret = process.env.JWT_SECRET;

function login(req, res, next) {

var username = req.body.username;
var password = req.body.password;

User.login(username, password)
    .then(user => {
        if (user) {
            const token = jwt.sign({
                userId: user._id
            }, jwtSecret);

            res.json({
                token,
                username: user.userName
            });
        }

        res.send('No such user exists!');
    })
    .catch(e => next(e));
}

export default { login };

user.model

userSchema.statics = {
list() {
    return this.find().exec();
},

login(username, password) {

    var queryPromise = this.findOne({ "userName": username }).exec();

    queryPromise.then(function(user) {
        bcrypt.compare(password, user.password, function(err, isMatch){
            if (err) throw err;
                console.log('Is password match :', isMatch);

            if (isMatch) {
                return;
            }
        });

    });
 }
}

Here's the error I'm getting

TypeError: Cannot read property 'then' of undefined

Can someone tell me what I'm doing wrong here?

The login method should return a Promise if you want to use .then

login(username, password) {
    return new Promise((resolve, reject) => {
        var queryPromise = this.findOne({ "userName": username }).exec();

        queryPromise.then(function(user) {
            bcrypt.compare(password, user.password, function(err, isMatch) {
                if (err) throw err;
                console.log('Is password match :', isMatch);

                if (isMatch) {
                    return resolve(user); // pass the user if you want to access it in the .then statement
                } else {
                    return reject(new Error('Invalid Credentials'));
                }
            });

        });
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM