繁体   English   中英

如何使用node.js模块Passport-google

[英]How do I use the node.js module passport-google

我正在尝试制作一个告诉用户使用其gmail登录的node.js Web应用程序。

因此,我尝试使用此处的说明: http : //passportjs.org/guide/google/ 我将网址www.example.com更改为localhost,然后运行了该应用程序。 它告诉我找不到用户。 这是整个日志:User.findOrCreate({openID:identifier},function(err,user){(然后在下一行)ReferenceError:未定义用户。

您需要通过从模型中调用“用户”来定义它。 创建用户模型(如果尚未创建)并将其作为变量导入。 例如

var User = require('/path/to/User'); 

有时,我发现将回调记录到控制台对调试很有帮助,以查看所需的输出是否已吐出。

我刚刚实现了一个方法,可能会有所帮助,我在底部使用“快速路由”部分。.记住在Google Key中设置主机,我的应用程序具有AWS Server的完整URL

var passport = require('passport');
// ====== Passport and OAuth2 API 
var GoogleStretegy = require('passport-google-oauth').OAuth2Strategy;

passport.serializeUser(function (user, done) {
    done(null, user);});
passport.deserializeUser(function (obj, done){
    done(null, obj);});

// Set Passport Initialize and Sessions
app.use(passport.initialize());
app.use(passport.session());

passport.use(new GoogleStretegy({
clientID: CREDENTIALS.google.GOOGLE_CLIENT_ID,
clientSecret: CREDENTIALS.google.GOOGLE_CLIENT_SECRET,
callbackURL:"<host>/oauth2callback"    
},
function (req, accessToken, refreshToken, profile, done) {
    process.nextTick(function () {
        console.log(JSON.stringify(profile));
        console.log(req);
        var username= profile.emails[0].value.split('@');
        User.findOne({email: profile.emails[0].value,username:username[0]}).exec(function (err,user) {
            if(!user){        
                var user = new User({username: username[0]});
                user.set('email',profile.emails[0].value);
                user.set('FullName',profile.DisplayName);
                user.save(function (err) {
                    if(err){
                        console.log(err);
                        profile=null;
                        return done(null,profile);
                    }else {
                        return done(null, profile);        
                    }
                });
            }else {
                return done(null, profile);
            }
        });
        // return done(null, profile);
    });
}
));

///路线!

router.get('/logout', function (req, res) {

req.session.destroy(function () {
// Google log out
    req.logout();
    res.redirect('/login');
});
});
//Google OAuth2
router.get('/auth/google',passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/userinfo.profile','https://www.googleapis.com/auth/userinfo.email'] }));
router.get('/oauth2callback', passport.authenticate('google', { failureRedirect: '/login' }), function (req, res) {
    res.redirect('/');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM