Home > other >  bcrypt fails even when passwords match...>
bcrypt fails even when passwords match...>

Time:02-27

Having problem with comparing passwords using bcryptjs.

Env:

Node: v16.8.0

bcryptjs: 2.4.3

https: 1.0.0 - (the site / pages are all https in case that makes any difference).

This is what the code looks like:

// Login Function
router.post('/login', async (req, res) => {
    const { password, email } = req.body;

    let user = users.find((user) => {
        return user.email === email
    });
    // Checks that the user is already registered
    if (!user) {
        return res.status(400).json({
            "errors": [
                {
                    "msg": "Invalid Credentials"
                }
            ]
        })
    };

    // Compare Passwords
    console.log('Checking if passwords match\n')
    let isMatch = await bcrypt.compare(password, user.password);

    console.log('Displaying Password variables:')
    console.log(`Just password Variable: ${password}`)
    console.log(`User.Password variable: ${user.password}`)

    console.log('\nDisplaying Value of isMatch:')
    console.log(`${isMatch}\n`)

    if (!isMatch) {
        console.log(`The Passwords dont match! Closing Connection`)
        return res.status(400).json({
            "errors": [
                {
                    "msg": "The Passwords do not match!"
                }
            ]
        });
    } else {
        console.log(`Moving on to the JWT thingy`)
        const token = await jwt.sign({
            email
        }, process.env.JWT_SECRET, {
            expiresIn: 360000
        })
        return res.json({ token })
    };
});

This is the output of all the console.logs:


Server is runing on Port: 3443

Checking if passwords match (This is the part where is does the bcrypt.compare)

Displaying Password variables:

Just password Variable: $2a$10$mXTzEmSqPoaEsPbvM3P/o.cl7VyMhVq7S37u8Lpo8gGr6i0tS8OxS User.Password variable: $2a$10$mXTzEmSqPoaEsPbvM3P/o.cl7VyMhVq7S37u8Lpo8gGr6i0tS8OxS

Displaying Value of isMatch: false

The Passwords dont match! Closing Connection


I just cant understand why isMatch returns to false, the output of the console.logs is exactly the same but the value of isMatch returns to false, and therefore follows the !isMatch route instead of going into the JWT section.

Ive tried using bcryptjs.hashSync() and bcryptjs.compareSync but it makes no difference.

Any ideas anyone? Cheers, M.

CodePudding user response:

bcrypt.compare takes a plain text password and a password hash. Your code is passing two password hashes. So the strings are equal, but the hash of the first string is not equal to the second string.

CodePudding user response:

// Login Function

    router.post('/login', async (req, res) => {
        const { password, email } = req.body;
    
        let user = users.find((user) => {
            return user.email === email
        });
        // Checks that the user is already registered
        if (!user) {
            return res.status(400).json({
                "errors": [
                    {
                        "msg": "Invalid Credentials"
                    }
                ]
            })
        };
    
        // Compare Passwords
        console.log('Checking if passwords match\n')
        
    if (password === user.password) {
    
        console.log('Displaying Password variables:')
        console.log(`Just password Variable: ${password}`)
        console.log(`User.Password variable: ${user.password}`)
    
        console.log('\nDisplaying Value of isMatch:')
        console.log(`${isMatch}\n`)
    
        if (!isMatch) {
            console.log(`The Passwords dont match! Closing Connection`)
            return res.status(400).json({
                "errors": [
                    {
                        "msg": "The Passwords do not match!"
                    }
                ]
            });
}
        } else {
            console.log(`Moving on to the JWT thingy`)
            const token = await jwt.sign({
                email
            }, process.env.JWT_SECRET, {
                expiresIn: 360000
            })
            return res.json({ token })
        };
    });

i've edited your code to not to a bcrypt.compare, because as stated in the above answer, compare takes a plain text string and compares it to the bcrypt hashed version. So since both are hashed, a regular if statement will suffice. Please forgive me if I put the closing if bracket in the wrong place

  • Related