0

i found this: How to passing data in TwitterStrategy, PassportJS? which was very helpful but i think it's uses either an old version of passport or express, or both:

I get no errors with my below code but passport.authenticate('twitter') doesn't appear to get called. I know my TwitterStrategy works so i don't think it's that, it think maybe i need to do a res.send() somewhere so the ajax request receives success? any help would be appreciated! thanks in advance!

var states={};

router.get('/auth/twitter', function(req, res, next){

  var reqId = 'req'+req.sessionID

  states[reqId] = {
    turkeyName : req.query.turkeyName,
    charityName : req.query.charityName,
    votes : req.query.votes
  };

  req.session.state = reqId
  next();

}, function(req, res, next) {
    passport.authenticate('twitter');
});

and this is what i'm doing on the client

  var params = {
    turkeyName: $('#turkeyNameInput').val(),
    charityName: 'Stand up to Cancer',
    votes: 1
  };

  var auth = $.ajax({
    type: 'GET',
    url: '/auth/twitter',
    data: params,
    dataType: 'text',
    async: true
  });

  auth.success(function(data){
    console.log('$ajax.auth -- success');
    console.log(data);
  });

  auth.error(function(err){
    console.log('$ajax.auth -- error');
    console.log(err);
  });
Community
  • 1
  • 1
Paul
  • 151
  • 10

1 Answers1

0

Ok, so for anyone else who has this issue.

In my noob way i was using ajax to make the get request from the client to the server route... but after my server made the relavent passport call i ran into some Access-Control-Allow-Origin errors.

This is because Twitter blocks requests coming from client via ajax. If you're getting Access-Control-Allow-Origin or something similar ditch ajax and use window.location.href

Route:

var states={};

router.get('/auth/twitter', function(req, res, next){  
  var reqId = 'req'+req.sessionID

  states[reqId] = {
    turkeyName : req.query.turkeyName,
    charityName : req.query.charityName,
    votes : req.query.votes
  };

  req.session.state = reqId
  next();

}, passport.authenticate('twitter'),function(req, res) {

});

Callback:

router.get("/auth/twitter/callback",
  passport.authenticate('twitter'), function(req, res) {

    var reqId = req.session.state;
    var state = states[reqId]

    findOrCreate(userInfo.userInfoModel, {userInfo : req.user, turkeyName : state.turkeyName, charityName : state.charityName, votes : state.votes}, function(err, userDataRes){
      if(err){
        req.session.destroy();
      }else{
        res.redirect('/list');
      }
    });
});

Client:

  var url = '/auth/twitter?'

  var dataObj = {
    turkeyName: $('#turkeyNameInput').val(),
    charityName: 'name of charity',
    votes: 1
  };

  window.location.href = url + $.param(dataObj);
Paul
  • 151
  • 10