Hariawan
Hariawan

Reputation: 253

How to passing data in TwitterStrategy, PassportJS?

I have three kind of user:

  1. Viewer (link to sign in: auth/v/twitter)
  2. Creator (link to sign in: auth/c/twitter)
  3. Admin (link to sign in: auth/a/twitter)

And also I have 3 different db/collection

  1. c_viewer
  2. c_creator
  3. c_admin

Where each kind of user have a different link to sign in.

Now let's take a look at the codes

var passport = require('passport')
   ,TwitterStrategy = require('passport-twitter').Strategy;

passport.use(new TwitterStrategy({
  consumerKey: config.development.tw.consumerKey,
  consumerSecret: config.development.tw.consumerSecret,
  callbackURL: config.development.tw.callbackURL
},

function(token, tokenSecret, profile, done) {
  process.nextTick(function(req, res) {
    var query = User.findOne({ 'twId': profile.id});
    query.exec(function(err, oldUser){
      if(oldUser) {
        done(null, oldUser);
      } else {
        var newUser = new User();
        newUser.twId = profile.id;
        newUser.twUsername = profile.username;
        newUser.name = profile.displayName;
        newUser.avatar = profile.photos[0].value;
     -> newUser.age = req.body.creator.age; ???
        newUser.save(function(err) {
          if(err) throw err;
          done(null, newUser);
        });
      };
    });
  });
}));

app.get('/auth/c/twitter', passport.authenticate('twitter'),
function(req, res) {
  var userUrl = req.url;
  // codes to pass the userUrl to TwitterStrategy
});
app.get('/auth/twitter/callback', 
passportForCreator.authenticate('twitter', { successRedirect: '/dashboard', failureRedirect: '/' }));

And this is my form

<input type="text" name="creator[age]" placeholder="How old are you?">
<a id="si" class="btn" href="/auth/c/twitter">Sign in</a>

My questions:

1. Can We pass <input> data to the login process? so We can read the input data in TwitterStrategy, and save to the db
2. Can We get "c" from login url (auth/ c /twitter) and pass it to TwitterStrategy? so we can simply check in different db/collection and change the query.

Upvotes: 1

Views: 3392

Answers (1)

Feugy
Feugy

Reputation: 1918

The idea is to store your values before redirecting user on twitter for authentication, and re-use these values once the user came back.

OAuth2 includes the scope parameter, which perfectly suits that case. Unfortunately, TwitterStrategy is based on OAuth1. But we can tackle it !

The next trick is about when creating the user. You should not do it when declaring strategy (because you cannot access input data), but a little later, in the last authentication callback see here the callback arguments.

Declaring your strategy:

passport.use(new TwitterStrategy({
  consumerKey: config.development.tw.consumerKey,
  consumerSecret: config.development.tw.consumerSecret,
  callbackURL: config.development.tw.callbackURL
}, function(token, tokenSecret, profile, done) {
  // send profile for further db access
  done(null, profile);
}));

When declaring your authentication url (repeat for a/twitter and v/twitter):

// declare states where it's accessible inside the clusre functions
var states={};

app.get("/auth/c/twitter", function (req, res, next) {
  // save here your values: database and input
  var reqId = "req"+_.uniqueId();
  states[reqId] = {
    database: 'c',
    age: $('input[name="creator[age]"]').val()
  };
  // creates an unic id for this authentication and stores it.
  req.session.state = reqId;
  // in Oauth2, its more like : args.scope = reqId, and args as authenticate() second params
  passport.authenticate('twitter')(req, res, next)
}, function() {});

Then when declaring the callback:

app.get("/auth/twitter/callback", function (req, res, next) {
  var reqId = req.session.state;
  // reuse your previously saved state
  var state = states[reqId]

  passport.authenticate('twitter', function(err, token) {
    var end = function(err) {
      // remove session created during authentication
      req.session.destroy()
      // authentication failed: you should redirect to the proper error page
      if (err) {
        return res.redirect("/");
      }
      // and eventually redirect to success url
      res.redirect("/dashboard");
    }

    if (err) {
      return end(err);
    }

    // now you can write into database:
    var query = User.findOne({ 'twId': profile.id});
    query.exec(function(err, oldUser){
      if(oldUser) {
        return end()
      } 
      // here, choose the right database depending on state
      var newUser = new User();
      newUser.twId = profile.id;
      newUser.twUsername = profile.username;
      newUser.name = profile.displayName;
      newUser.avatar = profile.photos[0].value;
      // reuse the state variable
      newUser.age = state.age
      newUser.save(end);
    });
  })(req, res, next)
});

Upvotes: 3

Related Questions