护照:不同重定向用于登录,帐户注册(passport: different redirect for

2019-07-28 21:44发布

我使用我的应用程序护照模块(GitHub的认证),我想这取决于操作重定向...我检查,如果它只是一个正常的登录,或者在首次用户登录。

passport.use(new GitHubStrategy({
    clientID: conf.github.app_id,
    clientSecret: conf.github.app_secret,
    callbackURL: conf.github.callback_url
  },
  function(accessToken, refreshToken, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // To keep the example simple, the user's GitHub profile is returned to
      // represent the logged-in user.  In a typical application, you would want
      // to associate the GitHub account with a user record in your database,
      // and return that user instead.

      Models_User.findOrCreateUser(profile, function(msg){
        console.log("auth type:" + msg);
      });

      return done(null, profile);

    });
  }
));

在我findOrCreateUser功能我检查它是否是一个新用户,并完成所有的数据库操作...测试我让函数返回一个Msg变量中这是唯一一个字符串,上面写着“登录”或“new_registration”。

所以我的问题是如何“运输”这个变量,我从findOrCreateUser得到,这样我可以相应护照身份验证完成(“/欢迎”或“/ back_again”)后重定向。

在我的应用程序的其他护照代码:

// GET /auth/github
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in GitHub authentication will involve redirecting
//   the user to github.com.  After authorization, GitHubwill redirect the user
//   back to this application at /auth/github/callback
app.get('/auth/github',
  passport.authenticate('github'),
  //passport.authenticate('github', { scope: ['user', 'public_repo', 'gist'] }),
  function(req, res){
    // The request will be redirected to GitHub for authentication, so this
    // function will not be called.
  });

// GET /auth/github/callback
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get('/auth/github/callback', 
  passport.authenticate('github', { successRedirect: '/', failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

Answer 1:

在您的验证回调,我会改变一些事情,从而使findOrCreateUser函数提供的实际记录的回调,然后再传递通过对done() ,像这样:

Models_User.findOrCreateUser(profile, function(user){
  console.log("auth type:" + msg);
  return done(null, user);
});

// take this out, use the actual model above
//return done(null, profile);

现在,处理身份验证后回调URL时,可以检查该用户的记录,看看它是否是新的(我假设在这里有一个是否新款属性):

app.get('/auth/github/callback', 
  passport.authenticate('github', { failureRedirect: '/login' }),
  function(req, res) {
    // successful auth, user is set at req.user.  redirect as necessary.
    if (req.user.isNew) { return res.redirect('/back_again'); }
    res.redirect('/welcome');
  });


文章来源: passport: different redirect for login and account registration