简体   繁体   中英

node.js/express/passport hanging after google-oath login

i am trying to learn node.js and having a bit of a headache doing the express login storing cookies with google oauth. I am using mongodb, user gets saved without a problem.

I can log in just fine, but when i set the cookies baaaam. But there is no error on console.

If i try to set cookies using cookies-session and express, the app hangs and i can't access any route '/' even the '/logout'. I only able to access them again if i clear the cookies on browser. I am stuck at this point.

this is my app.js

app.use(
    cookieSession({
        maxAge: 30 * 24 * 60 * 60 * 1000,
        keys: [keys.cookieSession]
    })
);

app.use(passport.initialize());
app.use(passport.session());

my routes

app.get('/auth/google',
  passport.authenticate('google', { 
    scope: ['profile', 'email'] 
  })
);

app.get('/auth/google/callback', passport.authenticate('google'));
app.get('/api/logout', (req, res) => {
    req.logout();
    res.send(req.user);
 });

and my passport.js

passport.serializeUser((user, done) => { 
    done(null, user.id);
});

passport.deserializeUser((id, done) => {
    User.findById(id).then(user => {
        done(err, user);
    });

});

passport.use( new GoogleStrategy({
    clientID: keys.googleClientID,
    clientSecret: keys.googleClientSecret,
    callbackURL: '/auth/google/callback'
    },
    (accessToken, refreshToken, profile, done) => {
        User.findOne({ googleId: profile.id }).then((existingUser) => {
                if (existingUser) {
                // don't create a new user
                done(null, existingUser);

                } else {
                // create a new user    
                new User ({ googleId: profile.id }).save()
                .then(user => (null, user));

                }
            })

    }   

));

So i was able to get this working, but I want to know what was did wrong.

I changed this and it worked, anyone has a clue?

passport.deserializeUser((id, done) => {
    User.findById(id).then(user => {
        done(err, user);
    });

});

to

passport.deserializeUser((id, done) => {
    User.findById(id, (err, user) => {
        done(err, user);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM