OdieO
OdieO

Reputation: 6994

How to pass token from middleware to route

Here's my Passport middleware. I'm authing Instagram as you can see:

// Use the InstagramStrategy within Passport.
//   Strategies in Passport require a `verify` function, which accept
//   credentials (in this case, an accessToken, refreshToken, and Instagram
//   profile), and invoke a callback with a user object.
passport.use(new InstagramStrategy({

    clientID: INSTAGRAM_CLIENT_ID,
    clientSecret: INSTAGRAM_CLIENT_SECRET,
    callbackURL: INSTAGRAM_CALLBACK_URL
  },

  function(accessToken, refreshToken, profile, done) {

    // asynchronous verification, for effect...
    process.nextTick(function () {

      var oauth = {'accessToken' : accessToken,
                 'refreshToken' : refreshToken,
                      'profile' : profile
                  };


      return done(null, oauth);
    });
  }
));

And then my callback route:

  app.get('/auth/instagram/callback', 
    passport.authenticate('instagram', { failureRedirect: '/home/language' }),
    function(req, res) {

      var oauth = req.get({oauth : oauth}); // Tried this first
      var oauth = req.oauth; // And this second
  });

I'm just having trouble getting the variable oauth from req in this callback so I can get the access token and set it on req.sessions here.

*I didn't have both of those var oauth = ... statements in at the same time, of course. Just showing them together for brevity.

Upvotes: 1

Views: 399

Answers (1)

OdieO
OdieO

Reputation: 6994

So I saw this feature in a Google Group thread and then the docs:

passReqToCallback: true

Since for now all I wanted to do was save the token to the session, I can do this:

  passport.use(new InstagramStrategy({

    clientID: INSTAGRAM_CLIENT_ID,
    clientSecret: INSTAGRAM_CLIENT_SECRET,
    callbackURL: INSTAGRAM_CALLBACK_URL,
    passReqToCallback: true // ADD THIS!
  },

  function(req, accessToken, refreshToken, profile, done) { // `req` is first parameter

      req.session.IGAccessToken = accessToken; // Set tokens on session
      req.session.IGRefreshToken = refreshToken;

      return done(null, profile);
  }
));

And now I can access the tokens in any route.

Upvotes: 1

Related Questions