(queston about news section) How to Build a Full-Stack Authentication App

Hi,
in order to consolidate my acquired knowledge in node, express and mongo, I started to build an app. So I took part of the authentication method of this news post:

I am using this code from the post:

const jwt = require("jsonwebtoken");

module.exports = async (request, response, next) => {
  try {
    //   get the token from the authorization header
    const token = await request.headers.authorization.split(" ")[1];

    //check if the token matches the supposed origin
    const decodedToken = await jwt.verify(token, "RANDOM-TOKEN");

    // retrieve the user details of the logged in user
    const user = await decodedToken;

    // pass the user down to the endpoints here
    request.user = user;

    // pass down functionality to the endpoint
    next();
    
  } catch (error) {
    response.status(401).json({
      error: new Error("Invalid request!"),
    });
  }
};

I am having some problems with the app when I try to access the rutes they need to have the authentication, so testing with console.logs I got stack when I want to log what is on “decodedToken” constant, in the auth.js file (which is the code I copied above). It seems the code is stacked there. What can it be?
Thank you in advance!

jwt.verify does not return a promise. It is synchronous, apparently, even if you give it a callback function it just defers using the event loop.

https://github.com/auth0/node-jsonwebtoken/issues/111

But I don’t think using await should cause it to hang or error out. So it is probably unrelated, but I just wanted to mention it.

There is a bit too much code to easily test it and we do not have all your code either. Maybe create a repo with your own code.

thank you for the reply!

Yes, exactly that’s what I read too, and I tried to do it without the await, and it was still stacked

I have it on github in case anyone would like to spend some time helping me look for what might be

But anyways, when I console.log(token), it returns the correct token, and I am doing the jwt.sign in this way, so “RANDOM-TOKEN” should not be a problem either if I am right:

const token = jwt.sign(
            {
              userId: user._id,
              userEmail: user.email,
            },
            "RANDOM-TOKEN",
            { expiresIn: "24h" }
          );
          console.log(token)
           //   return success response
            res.status(200).send({
              message: "Login Successful",
              email: user.email,
              token,
            });
        })

I assume you are testing it using Postman or something similar? Are you adding the bearer token correctly and do you get the token back from this code?

const token = await request.headers.authorization.split(" ")[1];

Yes, exactly when I try it with Postman, and I console log the “request.headers.authorization” I get the bearer + the token. So when I console log the token I get only the token after spliting it

Try moving the custom CORS middleware to the top of the file as the very first thing after the dependencies (starter repo code). Or remove it a use the cors package instead, still keeping it at the top of the file.


Did you use the starter repo?

Why is your DB code commented out and why did you add other packages?

I just tried both things, not success…

No I didn’t I used another project I was working on it based in another tutorial

Before using JWT.js I was trying to use password.js. So I forgot to delete that part, also the dependecies I used at that moment are still installed.