7

因为我可以req.user通过传入来获取任何路由中的登录用户:

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

我想允许用户使用本地登录以外的推特登录,所以我在 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);
          }
        )
      }
    )
  );
};
4

2 回答 2

3

Google Passport 策略提供了将请求传递给verify回调的选项。它似乎完全符合我们的要求。This stackoverflow answer from a similar question指出了这一点,但专门针对该策略。下面的示例是从该答案复制而来的。

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-twitterGithub 存储库中的此评论表明该选项也适用于该策略。我还没有确认,因为我还没有在我自己的项目中将 Twitter 实现为 OAuth 策略。

于 2018-09-04T16:06:31.143 回答
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 在下一个中间件中访问用户配置文件。

于 2018-09-04T15:10:10.830 回答