2012-04-11 120 views
8

我在我的應用程序中使用護照模塊(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得到的變量,以便我可以在護照驗證完成後相應地重新定向(「/ welcome」或「/ 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('/'); 
    }); 

回答

9

在你驗證回調,我會改變一些事情,從而使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'); 
    }); 
+0

謝謝,很好的回答! – toxinlabs 2012-04-18 08:48:29

+2

@Jared Hanson,那也適用於我。有一個網站或文件,我可以學習這一點? – 2015-01-01 23:13:42