Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 })
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!