我正在使用带有 express 2.x 和会话存储的 pssportjs。登录后,我只得到 req.User 一次。一旦我再次重定向req.User 未定义。
这是我的配置:
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(userId, done) {
User.findOne({_id: userId} ,function(err, user){
done(err, user);
});
});
// Authentication Strategy
passport.use(new FacebookStrategy({
clientID: CONFIG.fb.appId,
clientSecret: CONFIG.fb.appSecret,
callbackURL: CONFIG.fb.callbackURL
},
function(accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
User.findOne({ 'accounts.uid': profile.id, 'accounts.provider': 'facebook' }, function(err, olduser) {
if(olduser) {
done(null, olduser);
} else {
var newuser = new User();
var account = {provider: "facebook", uid: profile.id};
newuser.accounts.push(account);
newuser.firstname = profile.name.givenName;
newuser.lastname = profile.name.familyName;
newuser.email = "TBD...";
newuser.save(function(err) {
if(err) { throw err; }
done(null, newuser);
});
}
});
});
}
));
var app = module.exports = express.createServer();
// configure express
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.compiler({ src : __dirname + '/public', enable: ['less']}));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
//app.use(express.session({ secret: "keyboard cat" }));
app.use(express.session({
secret: "victory cat",
store: new MongoStore({
url: CONFIG.dbMongo.url
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
这些是我的路线:
app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['user_status', 'user_photos'] }));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { successRedirect: '/index', failureRedirect: '/' }));
app.get('/index', function(req, res) {
res.render('index.ejs', {
siteTitle: "Welcome",
siteUrl: CONFIG.server.siteUrl,
user: req.user
});
});
最后,这就是我试图在我的视图中访问用户对象的方式:
<div class="page-header">
<h3><%= siteTitle %></h3>
</div>
<% if (!user) { %>
<p>Not logged in !</p>
<% } else { %>
<p>Hello, <%= user.firstname %> <%= user.lastname %>.</p>
<% } %>
使用 facebook 进行身份验证后,我的视图正确显示了名字和姓氏。在另一个页面请求 req.User 之后是 undefiend (不调用反序列化)。
我究竟做错了什么?