0

I'm trying to implement authentication with argon2, and the line that crashes the app is highlighted in the following code snippet.

const { readFileSync } = require("fs");
const { Router } = require("express");
const users = require("../users.json");
const { verify } = require("argon2");
const { sign } = require("jsonwebtoken");

const key = readFileSync("key");
const expiresIn = process.env.JWT_MAX_AGE || "1d";

const router = Router();

router.post("/", async (req, res) => {
    const { phone_number, password } = req.body;

    const user = users.find((user) => user.phone_number === phone_number);

    if (!user) {
        res.status(401).json({ message: "Invalid username/password" });
        return;
    }

    if (!await verify(user.password_hash, password)) {
        // CRASH: This line crashes the app
        res.status(401).json({ message: "Invalid username/password" });
        return;
    }

    const { id } = user;

    sign({ id }, key, { expiresIn }, (err, token) => {
        if (err) {
            res.status(500).json({ message: "Something went wrong" });
            return;
        }

        res.status(200).json({ token });
    });
});

module.exports = router;

I got the following output after POSTing credentials with an existing username and an invalid password. May I know what could possibly go wrong in this case? Thanks!

node:internal/errors:465
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:372:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (/Users/user/Repositories/backend/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/Users/user/Repositories/backend/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/Users/user/Repositories/backend/node_modules/express/lib/response.js:278:15)
    at /Users/user/Repositories/backend/routes/sign_in.js:23:25 {
  code: 'ERR_HTTP_HEADERS_SENT'
}
ckl
  • 13
  • 3
  • So if you're passing a non-existent username/phone number, you don't get an error? – robertklep Jul 13 '22 at 09:21
  • @robertklep Yup, I don't get the same error if I pass a non-existent username, meaning that the if-statement above the CRASH line does work as expected. – ckl Jul 13 '22 at 09:22
  • Are you using any middleware that might be causing it? – robertklep Jul 13 '22 at 09:25
  • @robertklep but I do get response if I pass in non-existent username/phone number, that should have passed all middlewares before reaching the /signin route, am I right? – ckl Jul 13 '22 at 09:28
  • Yes, unless you have a custom middleware that somehow could be causing it. – robertklep Jul 13 '22 at 09:33

0 Answers0