gpt4 book ai didi

node.js - req.user undefined - node + express + passport-facebook

转载 作者:IT老高 更新时间:2023-10-28 23:06:34 25 4
gpt4 key购买 nike

我正在尝试让 Passport 与我的 Node express 服务器一起工作。我可以使用 Facebook 登录并在我的数据库中找到正确的用户;但是,当我重定向 req.user 时总是未定义。这是我的服务器代码:

var express = require('express'),
path = require('path'),
http = require('http'),
passport = require('passport'),
FacebookStrategy = require('passport-facebook').Strategy,
user = require('./routes/users');


var app = express();

passport.use(new FacebookStrategy({
clientID: "HIDDEN",
clientSecret: "HIDDEN",
callbackURL: "http://MYURL.com/auth/facebook/callback",
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
user.findOrCreate(profile, function(err, user) {
if (err) { return done(err); }
done(null, user);
});
}
));

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

passport.deserializeUser(function(id, done) {
user.findById(id, function(err, user) {
done(err, user);
});
});

app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'foobar' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});

app.get('/auth/user', function (req, res) {
console.log(req);
});

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


http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});

我转到/auth/facebook,它会找到正确的用户并将我重定向到/。但是后来我转到/auth/user 并且 req.user 未定义,我的 session 显示:

cookies: { 'connect.sid': 's:JFdQkihKQQyR4q70q7h2zWFt.VS+te0pT0z/Gtwg7w5B33naCvA/ckKMk60SFenObxUU' },
signedCookies: {},
url: '/auth/user',
method: 'GET',
sessionStore:
{ sessions:
{ '5sk3Txa2vs5sYhvtdYwGaUZx': '{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"passport":{"user":"50c527c9c6cb41860b000001"}}',
'Au6m0hAj/3warKOGNSWw0yu2': '{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"passport":{}}',
JFdQkihKQQyR4q70q7h2zWFt: '{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"passport":{}}' },
generate: [Function],
_events: { disconnect: [Function], connect: [Function] } },
sessionID: 'JFdQkihKQQyR4q70q7h2zWFt',

是否与我的 sessionID 与设置 Passport 用户的 session 不匹配有关?

更新

所以我确定 sessionID 不匹配是因为我在 c9.io 上运行我的代码,它实际上有两个 URL。当我使用正确的 URL 并转到/auth/user 时,我的 sessionID 与带有 Passport 用户集的 session 匹配,我可以在日志中看到我的 deserializeUser 找到了正确的用户对象。但是,此后 req.user 仍然是未定义的。

Trying to find user with id: 50c527c9c6cb41860b000001
{ sessions:
{ yoOUOxyXZ0SmutA0t5xUr6nI: '{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"passport":{"user":"50c527c9c6cb41860b000001"}}',
goZpmK3y3tOfn660hRbz2hSa: '{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"passport":{}}',
'O5Sz1GuZqUO8aOw4Vm/hriuC': '{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"passport":{}}' },
generate: [Function],
_events: { disconnect: [Function], connect: [Function] } }
sessionID: yoOUOxyXZ0SmutA0t5xUr6nI
req.user: undefined
{ cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
passport: {} }

更新2

我发现了问题所在。它在我的 user.findByID 函数中:

exports.findById = function(id, callback) {    
console.log('Trying to find user with id: ' + id);
db.collection('users').findOne({'_id':id}, function(err, user) {
callback(err, user);
});
};

改为:

exports.findById = function(id, callback) {    
console.log('Trying to find user with id: ' + id);
db.collection('users').findOne({'_id':new BSON.ObjectID(id)}, function(err, user) {
callback(err, user);
});
};

最佳答案

正如您在更新中所说的那样,user._id 变量的格式不正确。为了避免这种情况,并且以后在其他请求和方法中必须注意这种格式,我建议您在注册时生成一个新的用户 ID。

你可以使用这个模块:

node-uuid

var uuid = require('node-uuid');

function findOrCreate(profile, callback) {
// save new profile
profile.uid = uuid.v1().replace(/\-/g, '');
}

关于node.js - req.user undefined - node + express + passport-facebook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13824314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com