我回答是否为时已晚,但我认为我的解决方案更好,更传统。 在官方文档here。有一节“协会确认回调”,其中提到,如果我们的战略的passReqToCallback选项设置为真,这使REQ,它将作为第一个参数验证传递回电话。
所以我FacebookStrategy现在看起来像:
var User = require('../models/UserModel.js');
var FacebookStrategy = require('passport-facebook').Strategy;
exports.facebookStrategy = new FacebookStrategy({
clientID: 'REPLACE_IT_WITH_CLIENT_ID',
clientSecret: 'REPLACE_IT_WITH_CLIENT_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback',
passReqToCallback: true
},function(req,accessToken,refreshToken,profile,done){
User.findOne({
'facebook.id' : profile.id
},function(err,user){
if(err){
done(err);
}
if(user){
req.login(user,function(err){
if(err){
return next(err);
}
return done(null,user);
});
}else{
var newUser = new User();
newUser.facebook.id = profile.id;
newUser.facebook.name = profile.displayName;
newUser.facebook.token = profile.token;
newUser.save(function(err){
if(err){
throw(err);
}
req.login(newUser,function(err){
if(err){
return next(err);
}
return done(null,newUser);
});
});
}
});
}
);
在我的代码示例我已经增加了一些逻辑保存在数据库中的会话保存用户信息的用户信息和。我认为这可能对人们有帮助。
req.user给出存储在护照会话中的用户信息。
这也适用于我与facebook身份验证。 – TulioPa 2013-11-12 03:56:00
谢谢!这是一个很大的帮助。 – Tyguy7 2015-04-14 15:26:17