Roby Cigar
Roby Cigar

Reputation: 948

How done function works in passport js?

I have auth function, I want it to authenticate my user route.

// auth.js

function auth(request, response, next) {
    passport.authenticate('jwt', { session: false }, async (error, token) => {
        if (error || !token) {
            response.status(401).json({ message: 'Unauthorized' });
        } 
        next(token);
    })(request, response, next);
    next()
}

module.exports = auth;

And heres my jwt strategy

// passport.js

passport.use(
  new JwtStrategy(opts, (payload, done) => {
    console.log('payload', payload)  // this works
    User.findById(payload.id)
      .then(user => {
        if (user) {
          console.log('here user', user) // this also works
          return done(null, user);
        }

        return done(null, false);
      })
  })
);

But why when I console log my request It doesn't show me the user that I already declare in done(null, user)

const auth = require('../auth.js')

router.get('/', auth, async (req, res) => {
   console.log(req.user) // return undefined
   // other code
});

Upvotes: 0

Views: 691

Answers (1)

IAmDranged
IAmDranged

Reputation: 3020

There are a couple issues that I can see:

  • From your auth() middleware function, your are calling next() before passport has had a chance to authenticate the incoming request - which happens asynchronously. You should remove the synchronous call to next() there, and defer to passport.authenticate() callback to handle this.
  • In passport.authenticate() callback, you're calling next() with an argument - express will take this as an error occurring and jump to the next error middleware in line.

Edit: I also checked the signature of the passport.authenticate() callback and it seems to be (error, user, info) - not (error, token).

Edit 2: It also seems like when passing passport.authenticate() a custom callback, it becomes your responsability to expose user on the req object by calling passport req.login() function. Please take a look here:

Upvotes: 3

Related Questions