简体   繁体   中英

Unable to verify hashed password

Hi All ,

I am authenticating my user using bcrypt module .
I am able to do perform the Registration process, but facing problem during Login process.
User Model :

var userSchema = new Schema({
    email: {type: String, required: true},
    password: {type: String,
});


Hashing methods :

userSchema.methods.encryptPassword = function (password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(5), null)
};
userSchema.methods.validPassword = function (password) {
    return bcrypt.compareSync(password, this.password);
};


Sign in :

module.exports.login = function (user, callback) {
    User.findOne({'email': user.email, 'password': user.validPassword(this.password)}, callback);
};


Login Route

router.post('/login', function (req, res) {
    var user = req.body;
    User.login(user, function (err, user) {
        if (err) {
            throw err;
        }
        if (!user) {
            res.sendStatus(404);
            return;
        }
        res.json(user.id);
    });
});


While executing am getting this error: TypeError:user.validPassword is not a function

Please Help.

In Login Route , you need to instantiate the Schema:

router.post('/login', function (req, res) {
    var user = new User(req.body);
    User.login(user, function (err, user) {
        if (err) {
            throw err;
        }
        if (!user) {
            res.sendStatus(404);
            return;
        }
        res.json(user.id);
    });
});

Your mistake is that the user being provided to your login method is not a Mongoose DB object. Instead, your login function should look something like this:

module.exports.login = function (request, callback) {
    User.findOne({'email': request.email }, function(err, user) {
        if (err) return callback(err);
        if(!user || !user.validPassword(request.password)) return callback();
        return callback(null, user);
    });
};

This will ensure that user is a valid Mongoose object before you attempt to verify the password.

One other possible solution, if you'd prefer to avoid checking that the password is valid in your data layer, is to simply fetch the user document based on its email and then check the password in the login route.

router.post('/login', function (req, res) {
    var user = req.body;
    User.findOne(user, function (err, user) {
        if (err) {
            throw err;
        }
        if (!user) {
            res.sendStatus(404);
            return;
        }
        if (!user.validPassword(req.body.password)) {
            res.sendStatus(401);
            return;
        }
        res.json(user.id);
    });
});

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