kasvith / express-mongo-jwt-boilerplate

Express Mongo JsonWebToken boilerplate
103 stars 43 forks source link

Return user data with token #11

Closed ghost closed 5 years ago

ghost commented 5 years ago

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. 😄

ghost commented 5 years ago

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)
  }
}
kasvith commented 5 years ago

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 commented 5 years ago

https://github.com/kasvith/express-mongo-jwt-boilerplate/blob/master/src/middlewares/authorization.js would be a good start. It does all the handling via passport

d0peCode commented 5 years ago

@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?