i have simple passport-facebook & google oauth application and it works but problem it is not serializing users properly i guess because when i log req.user
it returns undefined. here is my code for facebook oauth
passport.serializeUser((user,done)=>{
done(null,user.id)
})
passport.deserializeUser((id,done)=>{
const user = User.findById(id)
done(null, user)
})
passport.use(new FacebookStrategy({
clientID: process.env.FB_CLIENT_ID,
clientSecret: process.env.FB_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/facebook/callback"
},
async (accessToken, refreshToken, profile, done) => {
const user = await User.findOne({ userId: profile.id })
if(user){
console.log('existing user '+ user)
return done(null,user)
}else{
const newuser = User.create({ username: profile.displayName,userId: profile.id });
console.log(newuser.toString())
done(null,newuser)
}
}))
and here is passport-google-oauth2
passport.serializeUser((user,done)=>{
done(null,user.id)
})
passport.deserializeUser((id,done)=>{
const user = User.findById(id)
done(null, user)
})
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/callback"
},
async (accessToken, refreshToken, profile, done) => {
const user =await User.findOne({ userId: profile.id })
if(user){
console.log('existing user '+ user )
return done(null,user)
}else{
const newuser = User.create({ username: profile.displayName,userId:
profile.id });
console.log(newuser)
done(null,newuser)
}
}))
and here is route config
router.get('/facebook', passportFacebook.authenticate('facebook'));
router.get('/facebook/callback',passportFacebook.authenticate('facebook', { failureRedirect: '/auth/login' }),
function(req, res) {
res.redirect('/');
});
router.get('/google',
passportGoogle.authenticate('google', { scope: 'profile' }));
router.get('/google/callback',passportGoogle.authenticate('google', {
failureRedirect: '/auth/login' }),
function(req, res) {
res.redirect('/');
});
so what is wrong with this code?
The problem is you don't await
for user
in deserializeUser
.
const user = User.findById(id)
You need to use then
or await
result from User.findById
. So your deserializeUser
code should be
passport.deserializeUser(async (id,done) => {
const user = await User.findById(id)
done(null, user)
})