简体   繁体   中英

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

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?

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

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