简体   繁体   中英

Checking if user is logged in JWT using cookies

I am using passport-jwt strategy, JWT in cookies to authenticate a user. The user authentication is working fine. However, at the endpoints where we need not check for authenticated user to grant access, I want to check is a user is logged in. If yes, I'll hide some options from the webpage and show others. I am trying to implement this by retrieving jwt from cookie, verifying it and finding the corresponding user and returning the user obtained.

Naturally, I want the user to be returned in User in the router before moving forward.

authenticate.js

var verifyToken = async function verifyToken(token, secretkey){ 
    // console.log('This is token: ', token);
    // console.log('This is secretkey: ', secretkey);
    try{
    var data = jwt.verify(token, secretkey);
    return data;
    } catch(err){
        return err;
    }
    
}

exports.loggedIn = async function loggedIn(req){
    try{
        var token = req.signedCookies.jwt;
        console.log(token);
        var userFound = false;
        if(token){
            data = await verifyToken(token, config.secretKey);
            user = await getUser(data);

            console.log('Data: ',data);
            console.log('User: ', user);
        }
        else
            return userFound;
    }
    catch(error){
        console.log(err);
    }
}

var getUser = function getUser(jwt_payload){
    try{
    var query = User.findOne({_id: jwt_payload._id});
    var returnUser = query.exec();
    return returnUser;
    }
    catch(err){
        console.log(err);
    }
}

However in the router, the next line ie console.log('Index router: ',User); is executed before User is obtained, printing Index router: Promise {<pending>} .

router.get('/', function(req, res, next) {
  Posts.find({})
  .populate('posted_by', 'username _id')
  .then((allPosts) => {
    return allPosts;
  })
  .then((list) => {
    console.log("list: ",list);
    if(list.length > 10)
      list = list.splice(10, list.length-10);
    res.statusCode = 200;
    res.setHeader('Content-Type','text/html');
    var User = authenticate.loggedIn(req);   //Here I want the User before moving forward
    console.log('Index router: ',User);
    res.render('index', {
      posts: list,
      user: User
    });
  })
  .catch((err) => next(err));
});

I have tried writing a different async function in which I as follows async function getuser(){ User = await authenticate.loggedIn(req); } async function getuser(){ User = await authenticate.loggedIn(req); } , but the same problem occurs even then. Please help!

You have to use await :

[...]
var User = await authenticate.loggedIn(req); 
[...]

Of course set the function as async:

router.get('/', async function(req, res, next) {
[...]

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