验证某些用户的护照策略

时间:2018-08-20 08:31:48

标签: javascript node.js passport.js

我正在为ReactJS前端构建一个nodeJS后端,并且想知道处理验证某些用户的最佳方法。

到目前为止,基本上,如果用户在我的mongoDB集合中,那么身份验证流程将按预期工作。

MongoDB模式

OfficeSchema = new Schema({
  outlookID: String,
  displayName: String
});

我正在使用Windows Live身份验证(通过Outlook进行身份验证)。当前的实现如下所示。

passport.use(
  new OutlookStrategy(
    {
      clientID: keys.OUTLOOK_CLIENT_ID,
      clientSecret: keys.OUTLOOK_SECRET,
      callbackURL: "/authorize-outlook"
    },
    async (accessToken, refreshToken, profile, done) => {
      const existingUser = await Office.findOne({ outlookID: profile.id });

      if (existingUser) {
        console.log("existing: ", existingUser);
        return done(null, existingUser);
      } else {
        console.log("no user found!");
        return done(null, false);
      }
    }
  )
);

最后,这是我的路线:

app.get(
    "/auth/outlook",
    passport.authenticate("windowslive", {
      scope: [
        "openid",
        "profile",
        "offline_access",
        "https://outlook.office.com/Mail.Read"
      ]
    })
  );

  app.get(
    "/authorize-outlook",
    passport.authenticate("windowslive", { failureRedirect: "/login_failure" }),
    function(req, res) {
      // Successful authentication, redirect home.
      res.redirect("/");
    }
  );

这是我的问题:

  1. 目前,我不知道在我的策略中使用done()函数的最佳方法,任何技巧都很棒。
  2. 如何在未授权用户的身份验证流中传递错误消息(不在数据库中),可以使用静态消息(“您无权”)
  3. 将用户添加到该数据库的最佳方法是什么(因为我目前为用户存储他们的outlookID)

回答我的任何问题都会有很大帮助。

谢谢您的时间。

1 个答案:

答案 0 :(得分:-1)

要保存新用户,您只需保存新用户并返回新对象:

 Office.findOne({
          outlookId: profile.id
        }).then(existingUser => {
          if (existingUser) {
           //hand over the existing object no need to create
            done(null, existingUser);
          } else {
            //assuming that you want to save the new user and grant access
            new Office({ outlookId: profile.id }).save().then(newUser => {
             //hand over the new user object back to the passport session
            //same arguments, new user object
              done(null, newUser);
            });
          }
        });

//假设您不想保存用户else {done(error, null}

关于完成的对象,有可能在您的策略对象中对此添加错误和信息对象响应。

done ("error string","user obj","info string")  

虽然看起来不太好,所以您可能要使用官方documents中所述的自定义回调:

然后,您可以让后端将错误对象返回到前端并进行适当处理。

相关问题