Link Twitter Account with Passportjs after local user auth is completed with passportjs
In the passportjs docs
Association in Verify Callback
One downside to the approach described above is that it requires two instances of the same strategy and supporting routes.
To avoid this, set the strategy's
passReqToCallback
option totrue
. With this option enabled, req will be passed as the first argument to the verify callback.
passport.use(new TwitterStrategy({ consumerKey: TWITTER_CONSUMER_KEY, consumerSecret: TWITTER_CONSUMER_SECRET, callbackURL: "http://www.example.com/auth/twitter/callback", passReqToCallback: true }, function(req, token, tokenSecret, profile, done) { if (!req.user) { // Not logged-in. Authenticate based on Twitter account. } else { // Logged in. Associate Twitter account with user. Preserve the login // state by supplying the existing user after association. // return done(null, req.user); } }));
With
req
passed as an argument, the verify callback can use the state of the request to tailor the authentication process, handling both authentication and authorization using a single strategy instance and set of routes. For example, if a user is already logged in, the newly "connected" account can be associated. Any additional application-specific properties set onreq
, includingreq.session
, can be used as well.
By the way, you can handle with the current user and its data to link any social strategy including Twitter.
You can do that in 2 ways:
Instead of trying to get
req.user
inside Twitter Strategy, you can get user email fetched from twitter response and match it with user with same email inside database. Normally, you cannot get email directly from Twitter API, you need to fill request form here to get elevated access. After request accepted, you will be able to get email from Twitter API.After twitter login, you can save user twitter profile information inside a temp table and redirect a page like
/user/do_login?twitter_profile_id=<user_twitter_profile_id_fetched_from_twitter_response>
. When you redirect to/user/do_login
you will be able to accessreq.user
and also you will have user profile id. In this action, you can grab user profile info from temp table and merge it withreq.user
. By the way, I assume that, you are using stored session.