why bcrypt.comapre return false when jsonwebtoken store in the cookie

15 Views Asked by At
const express = require('express');
const bcrypt = require('bcryptjs');
const schema = require('../database/schema/accountSchema');
const router = express.Router();

// Endpoint to handle user login
router.post('/loginn', async (req, res) => {
    try {
        require('../database/connectmongo.js');

        const { email, password } = req.body;

        if (!email || !password) {
            return res.status(423).json({ message: 'Please provide both email and password.' });
        }

        // Find user by email
        const user = await schema.findOne({ email });

        // If user doesn't exist
        if (!user) {
            return res.status(401).json({ message: 'Invalid email or password.' });
        }


        const isPasswordValid = await bcrypt.compare(password, user.password);
        console.log(isPasswordValid);  // first time logout and return true after removing cookie always return false

        if (!isPasswordValid) {
            return res.status(401).json({ message: 'Incorrect email or password.' });
        }

        const token = await user.generateAuthentication();

        res.cookie('token', token, {
            expires: new Date(Date.now() + 1000 * 60 * 60 * 24),
            httpOnly: true
        })

        return res.status(200).json({ message: 'Login successful.' });
    } catch (error) {
        console.error(error);

        return res.status(500).json({ message: 'An error occurred while logging into the account.' });
    }
});

module.exports = router;

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

const signUpSchema = mongoose.Schema({
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true,
        minlength: 7
    },
    tokens: [
        {
            token: {
                type: String,
                required: true
            }
        }
    ]
});


// Encoded password before saving in database
signUpSchema.pre('save', async function (next) {
    try {
        this.password = await bcrypt.hash(this.password, 10);
    } catch (error) {
        console.log({ eroor: error.message });
    }

    next();
})

    
signUpSchema.methods.generateAuthentication = async function () {
    try {
        const token = await jwt.sign({ _id: this._id.toString(), password: this.password}, process.env.SECRET_KEY, {
            expiresIn: 5000
        })

        this.tokens = this.tokens.concat({ token });
        
        await this.save();
        return token;

    } catch (error) {
        console.log(error);
    }
}

const schema = new mongoose.model("login", signUpSchema);

module.exports = schema;

i am creating a login form and issue is facing when i generate authentication token and store in the cookie after store cookie in the browser again i can't login the response have invalid email or password i debug this code but i analyze after storing token in the browser bcrypt.compare function does not match with the password enter image description here

0

There are 0 best solutions below