我正在使用Passport.js尝试通过Google OAuth 2.0登录Node.js中的东西,但它给了我以下错误:
ReferenceError:在passport.js中未定义id
无法检测来自auth / google / callback的配置文件对象的id属性,这可能是导致此错误的原因之一。请提供帮助。
passport.js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const GoogleStrategy=require( 'passport-google-oauth2' ).Strategy;
const User = require('../models/User');
const configAuth = require('./auth');
module.exports = function(passport) {
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
/**
* Sign in with Google.
*/
passport.use(new GoogleStrategy({
clientID : configAuth.googleAuth.clientID,
clientSecret : configAuth.googleAuth.clientSecret,
callbackURL : configAuth.googleAuth.callbackURL,
passReqToCallback: true
},function(token, refreshToken, profile, done) {
process.nextTick(function() {
User.findOne({ 'google.id': profile.id }, function(err, user) {
if (err)
return done(err);
if (user) {
return done(null, user);
} else {
var newUser = new User();
newUser.google.id = profile.id;
newUser.google.token = token;
newUser.google.name = profile.displayName;
newUser.google.email = profile.emails[0].value;
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
routes.js
router.get('/profile',isLoggedIn, function(req, res) {
res.render('profile.ejs', {
user : req.user // get the user out of session and pass to template
});
});
router.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));
// the callback after google has authenticated the user
router.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect: '/profile',
failureRedirect: '/',
}));