Using passport.js, I write the route this way so I have access to the MongoDb document userDoc
. But, when doing it this way... passport.serializeUser()
will never be called and the req
object will be missing user
.
auth.route('/auth/facebook/callback')
.get(function(req, res, next) {
passport.authenticate('facebook', function(err, userDoc, info) {
if (err) { return next(err); }
// I don't think !userDoc will ever happen because of mongo upsert
if (!userDoc) { return res.redirect('/login'); }
res.cookie('facebookPicUrl', userDoc.value.facebook.picture, {maxAge : 9999999,
httpOnly: false,
secure: false,
signed: false
});
res.redirect('http://localhost:9000/users')
})(req, res, next);
});
But if I write it this way, the req.user
is there as it should be:
auth.route('/auth/facebook/callback')
.get(passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('http://localhost:9000/users')
});
How can I make this to where passport.serializeUser
is called and user
exists on req
and I also have access to the mongoDb object?
Since you are using the custom authentication callback you are responsible for establishing the session.
Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling
req.login()
) and send a response.
req.login()
assigns the user
object to the request object req
as req.user
once the login operation completes.
You can see for example that in the documentation req.login()
is explicitly called in the custom callback:
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With