Reputation: 537
I'm having a problem with Passport.js and express-session. When I try to log in the request just hangs. I started off with cookie-session instead of express-session and had no problem authenticating, both with Google and Facebook strategies. For some reason, the serializeUser and deserializeUser functions are not being called, and as a result no user is stored on the req object.
My code is below.
index.js
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({
secret: sessionSecret,
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
routes
router.get('/google', passport.authenticate('google', {
scope: ['profile', 'email']
}));
router.get('/google/callback', passport.authenticate('google', {
successRedirect: '/',
failureRedirect: '/login'
}));
passport set up
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (e, user) => {
done(e, user);
});
});
passport.use(new GoogleStrategy({
clientID: googleClientID,
clientSecret: googleClientSecret,
callbackURL: '/auth/google/callback',
proxy: true
}, async (accessToken, refreshToken, profile, done) => {
try {
//Does email exist in DB?
const existingUser = await User.findOne({
email: profile.emails[0].value,
});
if(existingUser) {
//If email exists, is the profile id same as one in db?
if(existingUser.googleId === profile.id) return done(null,
existingUser);
//If email exists but no google id, set one
if(!existingUser.googleId) {
const user = await User.findOneAndUpdate({
email: profile.emails[0].value
}, {
$set: {
googleId: profile.id
}
}, {
new: true
});
return done(null, user);
}
}
const newUser = await new User({
email: profile.emails[0].value,
googleId: profile.id
}).save();
done(null, newUser);
} catch (e) {
console.log(e);
}
}));
Upvotes: 0
Views: 324
Reputation: 537
Solved the problem now. I was requiring in a seed file which disconnected from my MongoDB database. This was obviously messing up the user lookup.
Upvotes: 0