Home > Software design >  checking user input password is equal to hash password in express-validator
checking user input password is equal to hash password in express-validator

Time:07-31

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?

CodePudding user response:

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');
        }
    });
})

  • Related