Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access Passport 'done' function from rest of the code while authenticating using passport.js?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 })
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading