如何在护照twitter策略中使用会话变量req.user

时间:2018-08-23 11:57:47

标签: javascript node.js api passport-local passport-twitter

因为我可以使用req.user通过传递以下任何一条路由来获取登录用户:

passport.authenticate("jwt", { session: false })

除了本地登录外,我想允许用户使用Twitter进行登录,因此我在node.js API中采用了通行证推特策略。如何使用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);
          }
        )
      }
    )
  );
};

2 个答案:

答案 0 :(得分:3)

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

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

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

twitter oauth的回调看起来像这样:

async (token, tokenSecret, profile, 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访问下一个中间件中的用户配置文件。

答案 1 :(得分:3)

Google Passport策略提供了一种将请求传递到verify回调的选项。它似乎完全符合我们的期望。 This stackoverflow answer指出了类似的问题,但专门针对该策略。下面的示例就是从该答案中复制的。

passport.use(new GoogleStrategy({
  clientID: process.env.GOOGLE_CLIENTID,
  clientSecret: process.env.GOOGLE_CLIENTSECRET,
  callbackURL: "http://127.0.0.1:7777/google/callback",
  passReqToCallback: true
},
// google will send back the token and profile
function(req, token, refreshToken, profile, done) {
  // req.user is the currently logged-in user
  …
})
passport-twitter仓库中的

This comment建议该策略也可以使用该选项。我尚未确认,因为我尚未在自己的项目中将Twitter实施为OAuth策略。