Can not Login with credentials of any other user than the one created at first place Mongodb and react

127
July 25, 2022, at 7:20 PM

I am facing this issue in react that when I create user other than the first one the users gets created in the mongodb but when I try to login with the credentials of any other users I get this internal node error 464 in terminal with the message of wrong password in postman and the API crashes also if the password for the first registered user is wrong the API crashes in same manner. Also the login request doesn't verify the username it only cares about the password. I have no idea what is causing this issue. I checked my code but it seems fine to me. Can someone please assist who may have faced and solved this problem? Any help will be highly appreciated. Thank you in advance.

My code for auth is:

const router = require("express").Router();
const User = require("../models/User");
const CryptoJS = require("crypto-js");
const jwt = require("jsonwebtoken");
//REGISTER
router.post("/register", async (req, res) => {
  const newUser = new User({
    username: req.body.username,
    email: req.body.email,
    password: CryptoJS.AES.encrypt(
      req.body.password,
      process.env.PASS_SEC
    ).toString(),
  });
  try {
    const savedUser = await newUser.save();
    res.status(201).json(savedUser);
  } catch (err) {
    res.status(500).json(err);
  }
});
//LOGIN
router.post('/login', async (req, res) => {
    try{
        const user = await User.findOne(
            {
                userName: req.body.user_name
            }
        );
        !user && res.status(401).json("Wrong User Name");
        const hashedPassword = CryptoJS.AES.decrypt(
            user.password,
            process.env.PASS_SEC
        );

        const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
        const inputPassword = req.body.password;
        
        originalPassword != inputPassword && 
            res.status(401).json("Wrong Password");
        const accessToken = jwt.sign(
        {
            id: user._id,
            isAdmin: user.isAdmin,
        },
        process.env.JWT_SEC,
            {expiresIn:"3d"}
        );
  
        const { password, ...others } = user._doc;  
        res.status(200).json({...others, accessToken});
    }catch(err){
        res.status(500).json(err);
    }
});
module.exports = router;

And the error that I get in the terminal is

node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (D:\Shop Api Test\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (D:\Shop Api Test\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (D:\Shop Api Test\node_modules\express\lib\response.js:267:15)
    at D:\Shop Api Test\routes\auth.js:63:25
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
Answer 1

the error

Cannot set headers after they are sent to the client

usually happens when you send response again while you already sent response back to client. so i think when user send wrong pass you send res.status(401).json("Wrong Password"); and since you're not returning, the function still runs and execute codes after that so the second res.status().json() will call and cause the error

change your code like this and always retrun if you don't wanna do anything after sending response back

router.post('/login', async (req, res) => {
  try {
    const user = await User.findOne({
      userName: req.body.user_name
    });
    if (!user) {
      return res.status(401).json("Wrong User Name");
    }
    const hashedPassword = CryptoJS.AES.decrypt(
      user.password,
      process.env.PASS_SEC
    );
    const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
    const inputPassword = req.body.password;
    if (originalPassword != inputPassword) {
        return res.status(401).json("Wrong Password");
    }
      
    const accessToken = jwt.sign({
        id: user._id,
        isAdmin: user.isAdmin,
      },
      process.env.JWT_SEC, {
        expiresIn: "3d"
      }
    );
    const { password, others } = user._doc;
    return res.status(200).json({ ...others, accessToken });
  } catch (err) {
    res.status(500).json(err);
  }
});
Rent Charter Buses Company
READ ALSO
Best practices to handle Cart

Best practices to handle Cart

I am trying to create a E-commerce project using MERN stack and was wonderingHow to go about creating a cart for a user

103
Js Node Selenium Try-Catch Js Error not working

Js Node Selenium Try-Catch Js Error not working

I'm trying to simulate clicking on an element that is rendered after a certain iteration of documentreadyState='complete'

63
How to convert s3Object into File and send it inside a FormData on nodeJS?

How to convert s3Object into File and send it inside a FormData on nodeJS?

so I need to download a file from S3 bucket and then, with either its buffer or readStream, append it to a FormData on nodeI've tried different libraries such as formdata-node, isomorphic-form-data and form-data

86
How do I stop my nodejs server for test purposes?

How do I stop my nodejs server for test purposes?

my nodejs module starts a server on a specific port, I am wondering if it is a way to stop the execution of that server in my mocha test:

61