Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link facebook data to currently logged in user with Passport.js

I'm using passport.js and I'm wounding if I can link a facebook id to a logged in user's account. Something like this:

passport.use( new FacebookStrategy({
        consumerKey: ---
        consumerSecret: ---
        callbackURL: "http://mycallback"
    },
    function(token, tokenSecret, profile, done) {
        if (user is logged in)
            user = User.addfacebookId(user, profile.id)
            done(user);
        }
    }   
));
like image 458
Pardoner Avatar asked Jun 26 '12 15:06

Pardoner


People also ask

How does Passport js authentication work?

The “Passport JS” library connects with the “expression-session” library, and forms the basic scaffolding to attach the (authenticated) user information to the req. session object. The main Passport JS library deals with already authenticated users, and does not play any part in actually authenticating the users.


1 Answers

There's a few ways to approach this, but I think one of the most straight-forward is to use the passReqToCallback option. With that enabled, req becomes the first argument to the verify callback, and from there you can check to see if req.user exists, which means the user is already logged in. At that point, you can associate the user with Facebook profile details and supply the same user instance to the done callback. If req.user does not exist, just handle it as usual.

For example:

passport.use(new FacebookStrategy({
    clientID: ---
    clientSecret: ---
    callbackURL: "http://mycallback"
    passReqToCallback: true
  },
  function(req, accessToken, refreshToken, profile, done) {
    if (req.user)
      // user is already logged in.  link facebook profile to the user
      done(req.user);
    } else {
      // not logged in.  find or create the user based on facebook profile
    }
  }   
));
like image 63
Jared Hanson Avatar answered Sep 16 '22 21:09

Jared Hanson