kasvith / express-mongo-jwt-boilerplate

Express Mongo JsonWebToken boilerplate

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Return user data with token

opened this issue · comments

Hi Kasun,

thank you very much for this fantastic boilerplate! 👍
It really helps me to dive into MongoDB/Mongoose.

I have a question about what the best approach would be for a GET route like /profile to get the user data after successfully log in.

After the login the API returns an JWT token. Can I search with that for my user to get all my data back?

Normally I did that with session cookies like findById(req.session.id) but I never did something like this with a JWT token. 😄

Would be this a valid and secure approach?

exports.profile = async (req, res, next) => {
  try {
    let token = req.headers['x-access-token'] || req.headers['authorization'];

    if (token.startsWith('Bearer ')) {
      token = token.slice(7, token.length);
    }

    const userId = jwt.verify(token, config.secret)
    const user = await User.findById(userId.sub);

    return res.json({
      user: user
    })
  } catch (error) {
    next(error)
  }
}

Yah that would be no problem, keep jwt in header. Its also a good practice for having two tokens refresh and access. Store access token in your machine and use that to renew your refresh token. Head to auth0 for more info

(Boilerplate maybe pretty old, did not have time for update it, if you like you can do a pr :) )

@kasvith but isn't it easier to just add exports.user = user inside services/passport.js service (after findOne mongoose method) and then require it wherever you need user data? Is there something wrong with this solution?