我正在尝试使用 passport.js 创建 google 和 facebook OpenId 身份验证。
当我尝试通过 google 和 facebook 登录但它显示 [TypeError: Cannot read property 'userId' of undefined]
请解决此错误。
在这里我附上了我的模型、控制器和 express.js 文件
模型 User.js
userId : {type: 'string'},
loginName : {type: 'string'},
userName : {type: 'string'},
password : {type: 'string'},
userEmail : {type: 'string'}
用户控制器.js
google: function(req, res)
{
passport.authenticate('google',
{
failureRedirect: '/login', scope: ['https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/plus.profile.emails.read']
}, function(err, user) {
req.logIn(user, function(err) {
if (err) {
console.log(err);
res.view('500');
return;
}
res.redirect('/user/index');
return;
});
})(req, res);
},
facebook: function(req, res) {
passport.authenticate('facebook', { failureRedirect: '/login', scope: ['email'] }, function(err, user) {
req.logIn(user, function(err) {
if (err) {
console.log(err);
res.view('500');
return;
}
res.redirect('/user/index');
return;
});
})(req, res);
}
express.js 文件
var passport = require('passport')
, FacebookStrategy = require('passport-facebook').Strategy
, GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
var verifyHandler = function(token, tokenSecret, profile, done) {
process.nextTick(function() {
User.findOne({ userId : profile.id}, function(err, user) {
if (user)
{
return done(null, user);
}
else
{
var data = {
//provider: profile.provider,
userId : profile.id,
name: profile.displayName
};
if (profile.emails && profile.emails[0] && profile.emails[0].value)
{
data.email = profile.emails[0].value;
}
if (profile.name && profile.name.givenName)
{
data.firstname = profile.name.givenName;
}
if (profile.name && profile.name.familyName)
{
data.lastname = profile.name.familyName;
}
User.create(data, function(err, user)
{
return done(err, user);
});
}
});
});
};
passport.serializeUser(function(user, done) {
done(null, user. userId );
});
passport.deserializeUser(function(userId, done) {
User.findOne({ userId : userId }, function(err, user) {
done(err, user);
});
});
module.exports.http = {
customMiddleware: function(app) {
passport.use(new FacebookStrategy({
clientID: "1628965017378018",
clientSecret: "85ad33be64ef80b4c53528d91c58713f",
callbackURL: "http://localhost:1337/user/facebook/callback"
}, verifyHandler));
passport.use(new GoogleStrategy({
clientID: '775943647612-hpqptpku90s37d2m3114r8olm50ef0ar.apps.googleusercontent.com',
clientSecret: 'JIqGkBqRqFGYd_zL6wzxJcko',
callbackURL: 'http://localhost:1337/user/google/callback'
}, verifyHandler));
app.use(passport.initialize());
app.use(passport.session());
}
};
module.exports.cache = {
maxAge: 31557600000
};