javascript - 使用 passportjs 完成本地用户身份验证后,将 Twitter 帐户与 Passportjs 关联起来

标签 javascript node.js express twitter passport.js

我只想在还有用户后链接twitter帐户。

首先我有一个这样的 router.js

// GET Registration Page
router.get('/signup', function(req, res){
    res.render('register',{noty: req.flash('message')});
});

// Handle Registration POST 
router.post('/signup', passport.authenticate('signup', {
    successRedirect: '/connect_twitter',
    failureRedirect: '/signup',
    failureFlash : true  
}));  

/* GET Twitter Auth*/
router.get('/login/twitter', passport.authenticate('twitter'));
router.get('/login/twitter/return', 
    passport.authenticate('twitter', { failureRedirect: '/' }),
    function(req, res) {
        res.redirect('/home');
});

如果成功,我将 "/connect_twitter" 重定向到 req.user != null ,即当前用户。在 "/connect_twitter" 中,带有按钮的重定向推特。

当推特返回用户的 token 时,我使用这个策略

passport.use(new TwitterStrategy({
    consumerKey: config.twitter.consumer_key,
    consumerSecret: config.twitter.consumer_secret,
    callbackURL: config.tw_callback 
  },
  function(token, tokenSecret, profile, cb) {
    // In this example, the user's Twitter profile is supplied as the user
    // record.  In a production-quality application, the Twitter profile should
    console.log(profile);
        findOrCreateUser = function(){
            // find a user in Mongo with provided username
            User.findOne({'tw_user_id': profile.id}, function(err, user) {
                // In case of any error, return using the done method
                if (err){
                    return cb(err);
                }
                // already exists
                if (user) {
                    user.tw_token = token;
                    user.tw_token_secret = tokenSecret;
                    user.save(function(err){
                        if (err) {
                            throw err;
                        } 
                        console.log("User Updating successfull !");
                    })
                    return cb(null, user);
                } else {
                    // create the user
                    var newUser = new User();
                    // set the user's local credentials
                    newUser.password = createHash(token);
                    newUser.username = profile.username;
                    newUser.email = null; 
                    newUser.tw_token = token;
                    newUser.tw_user_id = profile.id;
                    newUser.tw_token_secret = tokenSecret;
                    // save the user
                    newUser.save(function(err) {
                        if (err){
                            console.log('Error in Saving user: '+err);  
                            throw err;  
                        }
                        console.log('User Registration succesful');    
                        return cb(null, newUser);
                    });
                }
            });
        };

        process.nextTick(findOrCreateUser);

  }));

问题是如何在此函数 function(token, tokenSecret, profile, cb) 中访问 c​​urrent_user 或有关当前用户的任何信息? 正如我所想,如果我访问它,我会将当前用户与这些 token 相关联。

或者

是否有更好的(任何)方式将 Twitter 与当前用户关联起来?

提前致谢..

最佳答案

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 to true. 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 on req, including req.session, can be used as well.

顺便说一下,您可以处理与当前用户及其数据相关联的任何社交策略,包括 Twitter。

关于javascript - 使用 passportjs 完成本地用户身份验证后,将 Twitter 帐户与 Passportjs 关联起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34495417/

相关文章:

javascript - 如何从 AsyncSubject(消费者模式)订阅一次元素

javascript - 即使可用堆内存远大于已用内存,也会出现堆内存不足的错误

javascript - switch 语句在 javascript 中不起作用

javascript - AngularJS ng-绑定(bind)到动态变量名称

node.js - 使用jade创建无序列表树

javascript - Browserify 使用我系统中文件夹的路径

node.js - 我的后期操作不起作用

node.js - AWS 无服务器函数 : Can't access methods of aws-sdk objects. 。 ."is not a function"

json - 如何使用 Node.js 返回复杂的 JSON 响应?

javascript - Node.js回调函数问题