Search code examples
node.jsfacebookparse-platformpassport.js

Node.js Passport deserializing Users returns 20+ identical users


Everything seems to works. The request to Parse.com checks if the users exists and either creates it or retrieves it. I'm having two main problem. First, when the deserializeUser function is called it returns 20 identical users and the findUser function, as it should, returns those 20 users. Also, I can't access the req.user

    passport.serializeUser(function(user, done) {

            done(null, user.objectId);
    });

    passport.deserializeUser(function(uid, done) {

            console.log(uid)
            // This outputs the ObjectId 20 TIMES!! ??

            Parse.findUser(uid,function(error,user){

                done(null, user);
            })
    });

    // CONFIGURATION
    app.configure(function() {
            app.use(express.bodyParser()); //read
            app.use(express.cookieParser()); //read
        app.use(express.session({ secret: process.env.SESSION_SECRET || 'abcde' }));
        app.use(passport.initialize());
        app.use(passport.session());
            app.use(app.router);
            app.use(express.static(__dirname + '/static'))
    });

    passport.use(new FacebookStrategy({
            clientID: process.env.FACEBOOK_APP_ID || 'app_id',
            clientSecret: process.env.FACEBOOK_SECRET || 'fb_secret',
        callbackURL: "http://localhost:5000/auth/facebook/callback"
        },
        function(accessToken, refreshToken, profile, done) {

            process.nextTick(function() {
                    _parse.user(accessToken, profile,function(parseUser){
                        //this returns the user.....

                    return done(null, parseUser);
                    })
            })
        })
    )
    app.get('/auth/facebook',
        passport.authenticate('facebook',{scope:'email'}),
            function(req, res){
                // The request will be redirected to Facebook ....
    });

    app.get('/auth/facebook/callback',
        passport.authenticate('facebook', { failureRedirect: '/login' }),
            function(req, res) {

                    console.log(req.user)
                    // this works! ...
                res.redirect('/browse');
    });

    app.get('/browse',function(req,res){
            console.log(req.user)
            // this is works too ...

            res.render('browse.jade',{title:'Browse',classes:'browse'})
    })

    app.get('/logout', function(req, res){
        req.logout();
        res.redirect('/login');
    });

Solution

  • My suspicion is that you are loading a page with 20 different resources, and each call is for a single request to one of those resources.

    Move the app.use(express.static(__dirname + '/static')) middleware to the top of your middleware stack. Since those resources are static and public, its not necessary to parse the body, cookies or load sessions.