checking user input password is equal to hash password in express-validator

Issue

Here is my code, I’m trying to get the user password and check if its equal to the hash password saved in the database inside custom validator and I am getting error Illegal arguments: string, undefined.

exports.validateLogin = [
        check('email')
            .trim()
            .notEmpty()
            .withMessage('Email cannot be blank')
            .isEmail()
            .withMessage('Email is not valid')
            .custom((value) => {
                const findUser = User.findOne({ email: value });
                return findUser.then((user) => {
                    if (!user) {
                        return Promise.reject('E-mail is not registered');
                    }
                });
            }),
        check('password')
            .trim()
        .notEmpty()
        .withMessage('Password cannot be blank')
        .custom((value, { req, next }) => {
            const findUser = User.findOne({ email: req.body.email });
            const check = bcrypt.compare(value, findUser.password);
            if (!check) {
            throw new Error('Not same as your Password');
            }
        }),
];

Is there something I’m missing?

Solution

User.findOne(...) does not return the User directly, but instead returns a Promise that resolves with the User. Therefore findUser.password is not defined and bcrypt.compare throws an Error.

Something like this should work:

.custom((value, { req, next }) => {
    User.findOne({ email: req.body.email }).then(user => {
        const check = bcrypt.compare(value, user.password);
        if (!check) {
            throw new Error('Not same as your Password');
        }
    });
})

Answered By – PiFanatic

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published