passportjs +facebook + current User

949 views Asked by At

Have some issues figuring out how to access the current user through my facebook login. I'm using passportJS, Node, express. I think that my 'user' is not staying logged in but I have no way to check. I'll upload what I have and thank you for anyone looking over it - really appreciate it.

route.js

 app.get('/auth/facebook', passport.authenticate('facebook', { scope : ['email', 'public_profile', 'user_friends'] }));
// handle the callback after facebook has authenticated the user
app.get('/auth/facebook/callback',
    passport.authenticate('facebook', {
        successRedirect : '/profile',
        failureRedirect : '/'
    }));
// route for logging out
app.get('/logout', function(req, res) {
    req.logout();
    res.redirect('/');
});
};
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on 
if (req.isAuthenticated())
    return next();
// if they aren't redirect them to the home page
res.redirect('/');
}

passport.js

    passport.use(new FacebookStrategy({
    // pull in our app id and secret from our auth.js file
    clientID        : configAuth.facebookAuth.clientID,
    clientSecret    : configAuth.facebookAuth.clientSecret,
    callbackURL     : configAuth.facebookAuth.callbackURL,
    // profileFields: ['id', 'name','picture.type(large)', 'emails', 'username', 'displayName', 'about', 'gender']
},
// facebook will send back the token and profile
function(token, refreshToken, profile, done) {
    // asynchronous
    process.nextTick(function() {
        // find the user in the database based on their facebook id
        User.findOne({ 'facebook.id' : profile.id }, function(err, user) {
            // if there is an error, stop everything and return that
            // ie an error connecting to the database
            if (err)
                return done(err);
            // if the user is found, then log them in
            if (user) {
                return done(null, user); // user found, return that user
            } else {
                // if there is no user found with that facebook id, create them
                var newUser            = new User();
                // set all of the facebook information in our user model
                newUser.facebook.id    = profile.id; // set the users facebook id                   
                newUser.facebook.token = token; // we will save the token that facebook provides to the user                    
                newUser.facebook.name  = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned
                newUser.facebook.email = profile.emails[0].value; // facebook can return multiple emails so we'll take the first
                console.log(profile);
                console.log(user);
                console.log('it is working');
                // save our user to the database
                newUser.save(function(err) {
                    if (err)
                        throw err;
                    // if successful, return the new user
                    return done(null, newUser);
                });
            }
        });
    });
})); // end of FacebookStrategy
};

server.js

require('./config/passport')(passport); // pass passport for configuration

// // required for passport
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

This is my first stackoverflow post so apologies in advanced if I have insulted anyone with the format.

2

There are 2 answers

0
JosephScript On

Your user should be serialized some how. For example:

// set up cookie parser and session
var cookieParser = require('cookie-parser');
var session = require('express-session');

app.use(cookieParser());
app.use(session({
    secret: 'mysecret',
    resave: true,
    saveUninitialized: false
}));

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

// Lets user information be stored and retrieved from session
passport.serializeUser(function(user, done) {
    done(null, user.facebook.id);
});

passport.deserializeUser(function(id, done) {
User.findById(id, function(err,user){
     if(err) done(err);
         done(null,user);
     });
});

Then you can access the user object via req.user. For example a test route could be:

app.get('/user', function(req, res, next) {

    res.send(req.user);
});

Good luck!

0
RITESH ARORA On

You can also do it in another way :

router.get('/auth/facebook', function(req, res, next) {
    passport.authenticate('facebook', { scope : ['email', 'public_profile', 'user_friends'] } , function(err, user, info) {
        if(err)   return res.status(400).send(err); 
        if(user._id){
           req.logIn(user, function(err) {
                if (err) { return next(err); }
                //redirect where you want
                return res.redirect("");
            });
        }
     })(req, res, next);
}) 

req.logIn is a function which is required with user obj to create session and maintain . Otherwise passport will never able to maintain session of user.