首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在passport-twitter策略中使用会话变量req.user

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

Stack Overflow用户
提问于 2018-08-23 19:57:47
回答 2查看 576关注 0票数 7

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

代码语言:javascript
复制
passport.authenticate("jwt", { session: false })

我希望允许用户使用twitter登录,而不是本地登录,所以我在node.js应用程序接口中有一个通行证-twitter策略。如何使用req.user访问本地登录的用户?

代码语言:javascript
复制
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);
          }
        )
      }
    )
  );
};
EN

回答 2

Stack Overflow用户

发布于 2018-09-04 23:10:11

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

不要忘记将includeEmail选项添加到策略中:

代码语言:javascript
复制
TwitterStrategy({
    consumerKey: "",
    consumerSecret: "",
    callbackURL: "http://localhost:3000"
    includeEmail: true, // <======= this
  }
)

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

代码语言:javascript
复制
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在下一个中间件中访问用户配置文件。

票数 3
EN

Stack Overflow用户

发布于 2018-09-05 00:06:31

Google Passport策略提供了将请求传递给verify回调的选项。它似乎做了我们正在寻找的事情。来自类似问题的This stackoverflow answer指出了这一点,但专门针对该策略。下面的示例是从该答案复制而来的。

代码语言:javascript
复制
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 Github repo中的This comment建议,该选项也适用于该策略。我还没有确认,因为我还没有在我自己的项目中实现推特作为OAuth策略。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51985307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档