Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

135
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda