J
J
JordanBelford2021-02-25 14:01:01
Node.js
JordanBelford, 2021-02-25 14:01:01

Why is the compare function not working correctly?

Hello! To encrypt the password, I used the bcrypt library. When comparing the password received from the client and from the database, I get an empty object. Who knows what could be the problem?

router.post('/sign_in', [
        check('email', 'Введите корректный email').normalizeEmail().isEmail(),
        check('password', 'Введите корректный password').exists()
    ],
    async (req, res) => {
    try {
        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.send({message: 'Введены не корректные данные'});
        }

        const {email, password} = req.body;

        const user = await User.findOne({email});


        if (!user) {
            return res.send({message: 'Не правильно введен логин или пароль'});
        }

        const isMatchPassword = bcrypt.compare(password, user.password);

        if (!isMatchPassword) {
            return res.send({message: 'Не правильно введен логин или пароль'});
        }

        const token = jsonWebToken.sign(
            {userId: user.id},
        config.jwtSecretKey,
            {expiresIn: '1h'}
        );

        res.send({token, userId: user.id});

    } catch (e) {
        console.error(e.message);
    }
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Developer, 2021-02-25
@JordanBelford

bcrypt doesn't encrypt anything! This is a hash function!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question