简体   繁体   中英

bcrypt password comparison is not working in Node.js with mongoose

Whenever I send a post request with Postman to /api/user/login . It shows user.password is not defined. I'm trying to compare the plain password with the existing hashed password stored in the MongoDB but it's showing a ReferenceError: user is not defined .

Below are the code and the error message with a screenshot. Please let me know where I messed up.

    const router = require('express').Router();
    const User = require('../model/User');
    const bcrypt = require('bcryptjs');
    const Joi = require('@hapi/joi');
    
    const registerSchema = Joi.object({
        name: Joi.string()
            .min(6)
            .required(),
        email: Joi.string()
            .min(6)
            .email()
            .required(),
        password: Joi.string()
            .min(6)
            .required()
    })
    
    const loginSchema = Joi.object({
        email:Joi.string()
            .required(),
        password:Joi.string()
            .required()
    })
    
    router.post('/register', async(req, res)=>{   
        
        const {error} = registerSchema.validate(req.body);
        if(error)
            return res.status(400).send(error.details[0].message);
    
            // Checking if the user exist in database   
            const checkExistingEmail =  await User.findOne({email: req.body.email});
            if(checkExistingEmail) return res.status(400).send('Email already exist');
    
    
        // Hash  passwords
        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(req.body.password, salt);
    
         //Create New Database for user
        const user = new User({
            name: req.body.name,
            email: req.body.email,
            password: hashedPassword    
        });
        try {
            const savedUser =  await user.save()
            res.send({user : user._id});
        } catch(err) {
            res.status(400).send(err);
            
        }
    });
    
    
    router.post('/login',  async(req, res) =>{
        const {error} = loginSchema.validate(req.body)
        if(error)
            return res.status(400).send(error.details[0].message);
    
            // Checking if the user exist in database   
            const checkExistingEmail =  await User.findOne({email: req.body.email});
            if(!checkExistingEmail) return res.status(400).send('Email does not exist');
    
            // Check Password
            const validPass = await bcrypt.compare(req.body.password, user.password);
            if(!validPass) return res.status(400).send('Password does not match');
    
            res.send('Logged In');
    
    });
    
  
    
    module.exports = router;

Error is shown here:

[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
Server running and listening at port 8081....
Connected to Database...
(node:9380) UnhandledPromiseRejectionWarning: ReferenceError: user is not defined
    at D:\tapu\PROJECT WORKS\PROJECT 1.0\Personal Blogging Web Application\Server Side\Login API\routes\auth.js:67:67
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:9380) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:9380) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate 
the Node.js process with a non-zero exit code.

Here is the screenshot with error

You should learn how to read stacktrace first.

UnhandledPromiseRejectionWarning: ReferenceError: user is not defined at D:\tapu\PROJECT WORKS\PROJECT 1.0\Personal Blogging Web Application\Server Side\Login API\routes\auth.js:67:67

There is ReferenceError in your code in file auth.js at line 67. Instead of chekcExistingEmail you are using user variable.

You can read more about stacktraces here:https://www.digitalocean.com/community/tutorials/js-stack-trace

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