javascript – 如何在passport-twitter策略中使用会话变量req.user

因为我可以使用req.user通过传入来获取任何路由中的登录用户
passport.authenticate("jwt",{ session: false })

我想允许用户使用除本地登录之外的Twitter登录,因此我在node.js API中有一个passport-twitter策略.如何使用req.user访问本地登录用户

module.exports = passport => {
  passport.use(
    new Strategy({
        consumerKey: "",consumerSecret: "",callbackURL: "http://localhost:3000"
      },function(token,tokenSecret,profile,cb) {
        Profile.findOne({
          user: req.user._id
        }).then(
          userdetail => {
            userdetail.twuser = profile._json.screen_name;
            userdetail.token = token;
            userdetail.tokenSecret = tokenSecret;

            userdetail.save().then();
            return cb(null,profile);
          }
        )
      }
    )
  );
};

解决方法

首先,我会检查您的系统中是否已有用户具有给定的Twitter个人资料ID.
然后我会检查是否有用户具有相同的电子邮件地址.这意味着,用户已经注册了他的电子邮件.
如果您的数据库中没有给定电子邮件地址或推特ID的用户,请创建一个新用户并将推特ID和电子邮件分配给此配置文件.

别忘了将includeEmail选项添加到策略中:

TwitterStrategy({
    consumerKey: "",callbackURL: "http://localhost:3000"
    includeEmail: true,// <======= this
  }
)

twitter oauth的回调可能如下所示:

async (token,cb) => {
   const existingProfileWithTwitterId = await Profile.findOne({ twid: profile.id }
   if (existingProfileWithTwitterId) {
     return callback(null,profile)
   }

   const existingProfileWithEmail = await Profile.findOne({ email: profile.emails[0].value }
   if (existingProfileWithEmail) {
     existingProfileWithEmail.twid = profile.id
     // Add some more stuff from twitter profile if you want
     await existingProfileWithEmail.save()
     return callback(null,existingProfileWithEmail)
   }

   // Create a new Profile
   const profile = new Profile({
      twid: profile.id,// add some more properties
   })
   return callback(null,profile)
})

之后,您可以使用req.user访问下一个中间件中的用户配置文件.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...