护照和Node.JS结构

Passport and Node.JS Structure

本文关键字:JS 结构 Node      更新时间:2023-09-26

我正在使用MEAN堆栈,并希望将Passport集成到其中。然而,我不完全确定我应该如何构建它。我最终想包括几个策略,但让我们从谷歌开始。

在我的routes.js文件中:

app.get('/auth/google', passport.authenticate('google'));
app.get('/auth/google/return', passport.authenticate('google', { successRedirect: '/',
                                failureRedirect: '/login' }));

有道理。但是,我应该把GoogleStrategy()构造函数/成功回调代码,在我的顶级服务器。js?假设我有5种不同的策略,它们应该都放进去吗?

对于我们的应用,我们创建了一个单独的passport.js文件,其中包含我们所有的社交注册策略以及一个单独的路由文件,这是我们的Google的样子:

app.js

var social  = require('./routes/social.js')
..
app.get('/auth/google', passport.authenticate('google'));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/signup', failureFlash: true}), social.googleCallback);

passport.js(位于根)

var passport = require('passport'),
    GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
    config = require('./config');
var socialAuth = config.socialAuth; //contains keys
module.exports = function(passport) {
    /*DEFINE LOGIN STRATS HERE*/
    //GOOGLE+
    passport.use(new GoogleStrategy({
        clientID: socialAuth.google.GOOGLE_CLIENT_ID,
        clientSecret: socialAuth.google.GOOGLE_CLIENT_SECRET,
        callbackURL: config.callbackDomain + "/auth/google/callback",
        scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
    }, function(accessToken, refreshToken, profile, done) {
            //code for strat here
            return done(null, userDoc);
       }
    });
}

social.js (route)

exports.googleCallback = function(req, res) {
    //do stuff with the return from passport
}

它可以很好地管理你想要的每种策略,并且很容易添加。