本文介绍了如何在TwitterStrategy,PassportJS中传递数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三种用户:

  1. 查看器(登录链接:auth/ v /twitter)
  2. 创作者(登录链接:auth/ c /twitter)
  3. 管理员(登录链接:auth/ a /twitter)
  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)

我还有3个不同的数据库/集合

And also I have 3 different db/collection

  1. c_viewer
  2. c_creator
  3. c_admin
  1. c_viewer
  2. c_creator
  3. c_admin

每种类型的用户都有不同的登录链接.

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

现在让我们看一下代码

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: '/' }));

这是我的表格

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

我的问题:

1..我们可以将<input>数据传递到登录过程吗?因此我们可以在TwitterStrategy中读取输入数据,并将其保存到db
2.我们能否从登录URL(auth/ c /twitter)中获得"c"并将其传递给TwitterStrategy?这样我们就可以简单地检入不同的数据库/集合并更改查询.

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.

推荐答案

想法是在重定向用户到Twitter上进行身份验证之前存储您的值,并在用户回来后重新使用这些值.

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包含scope参数,它非常适合这种情况.不幸的是,TwitterStrategy基于OAuth1.但是我们可以解决!

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 callbacksee here the callback arguments.

声明您的策略:

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);
}));

在声明身份验证URL时(重复a/twitter和v/twitter):

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() {});

然后在声明回调时:

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)
});

这篇关于如何在TwitterStrategy,PassportJS中传递数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 19:37