简体   繁体   中英

BCRYPTJS: returning same hash for different passwords

I didn't find anyone with similar problem on google, what happens is no matter the password user inputs it returns hash as if that is correct password, but you can input anything and it will still return same hashed password of that mail when it's found in database.

For example:

Password input: asd

bcrypt: $2a$12$EkucFAxlupmAzec1CDnBmuYugwAO4cXj.5bt/thg8l/dG0JDhMScm

Password input: astastas

bcrypt: $2a$12$EkucFAxlupmAzec1CDnBmuYugwAO4cXj.5bt/thg8l/dG0JDhMScm

code:

    exports.login = (req, res, next) => {
        const email = req.body.email;
        const password = req.body.password;

        Users.findOne({ email: email }).then(result => {
            if (!result) {
                throw new Error('No user with that email');
            }
            else if (crypt.compare(password, result.password)) {
                const token = jwebtoken.sign({ email: result.email },
                    'thisisatokenyoucantfake', { expiresIn: '1h' });

                res.status(200).json({ token: token });
                console.log(password);
                console.log(result.password);
            } else {
                throw new Error('No user');
            }
        }).catch(err => console.log(err));
    };

mongodb atlas is used for storing hashed passwords, encrypt length is 12 .

if anyone needs solution:

exports.login = (req, res, next) => {
    const email = req.body.email;
    const password = req.body.password;

    Users.findOne({ email: email }).then(result => {
        if (!result) {
            throw new Error('No user with that email');
        } else {
            return crypt.compare(password, result.password);
        }
    }).then(result => {
        if (result) {
            const token = jwebtoken.sign({ email: result.email },
                'thisisatokenyoucantfake', { expiresIn: '1h' });

            res.status(200).json({ token: token });
        } else {
            throw new Error('Wrong password');
        }
    }).catch(err => console.log(err));
};

bcrypt.compare is asynchronous - it returns a promise. Your if statement will always return true because a promise is a truthy value. You need to resolve the promise using either await or .then() to get the resulting boolean.

Also you're logging the input plaintext password and the stored hash - the stored hash should always be the same as that's the point.

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