I am trying to implement authentication in my API using passport.js with passport_jwt strategy. the code is attached below
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const opts = {}
const User = require('../models/user_model')
const dotenv = require('dotenv')
module.exports = function(passport) {
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = process.env.JWT_SECRET;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findById(jwt_payload._id, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
}));
}
here I have passed the user on the done function on successful authentication. For my post routes I used passport.authenticate as a route middleware like below.
app.use('/api/v1/posts', passport.authenticate('jwt', { session : false }), postRoutes)
Now the question is how can I access the user, previously sent on the done function, while creating the post routes? Thank you so much.
CodePudding user response:
You can access user in your postRoutes method as code below:
exports.postRoutes = async (req, res) => {
console.log('req.user =====>', req.user);
res.status(200).send({ user: req.user })
};