node.js PassportJS:如何在我的视图中获取 req.user
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11186174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PassportJS: How to get req.user in my views
提问by Sven
I am using pssportjs with express 2.x and a sessions storage. After a login I am getting req.User only once. As soon as I redirect again req.User is undefined.
我正在使用带有 express 2.x 和会话存储的 pssportjs。登录后,我只收到 req.User 一次。一旦我再次重定向req.User 是未定义的。
Here is my config:
这是我的配置:
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'));
});
These are my routes:
这些是我的路线:
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
});
});
And finally this is how I am trying to access the user object in my view:
最后,这就是我试图在我的视图中访问用户对象的方式:
<div class="page-header">
<h3><%= siteTitle %></h3>
</div>
<% if (!user) { %>
<p>Not logged in !</p>
<% } else { %>
<p>Hello, <%= user.firstname %> <%= user.lastname %>.</p>
<% } %>
After authenticating with facebook my view displays firstname and lastname correctly. After another page request req.User is undefiend (deserializing is not being invoced).
使用 facebook 进行身份验证后,我的视图正确显示名字和姓氏。在另一个页面请求 req.User 之后是 undefiend(没有调用反序列化)。
What am I doing wrong?
我究竟做错了什么?
采纳答案by mvbl fst
Use dynamic helpers. Here's an example of my barebones userobject:
使用动态助手。这是我的准系统user对象的示例:
app.dynamicHelpers({
user: function(req, res){
var roles, name;
if (req.session && req.session.auth == true) {
roles = ['member'];
name = (req.session.user) ? req.session.user.name : 'Registered member';
id = (req.session.user) ? req.session.user.id : 0;
}
else {
roles = ['guest'];
name = 'Guest';
id = null;
}
return {
name: name,
id: id,
roles: roles,
isGuest: roles.indexOf('guest') !== -1,
isAdmin: roles.indexOf('admin') !== -1
}
}
});
Then from views you can simply use #{user.name}or if user.isAdminetc as object useris now accessible to other parts of the app.
然后从视图可以简单地使用#{user.name}或if user.isAdmin等作为对象user,现在到应用程序的其他部分访问。
You can add it to app.js or require from an external file. I keep all of my dynamic helpers under /utils/helpers.js
您可以将其添加到 app.js 或从外部文件中要求。我将所有的动态助手都保存在 /utils/helpers.js 下
回答by smagch
Did you set passport middleware? From the document, you need to do
您是否设置了护照中间件?从文档中,你需要做
app.configure(function() {
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(YOUR_STATIC_DIR_PATH));
});
if you are using Express 3.x or Connect 2.x, set cookie secret instead of session secret
如果您使用的是 Express 3.x 或 Connect 2.x,请设置 cookie 机密而不是会话机密
app.configure(function() {
app.use(express.cookieParser('keyboard cat'));
app.use(express.session());
app.use(express.bodyParser());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(YOUR_STATIC_DIR_PATH));
});
回答by Sven
All right I got it:
好吧,我明白了:
The mistake I did was not being in the code I posted above, which is correct. I had a wrong way of linking to URLs so I somehow forced express to create a new session every time I used one of the broken links. With the new session I also lost my req.user object.
我犯的错误不在我上面发布的代码中,这是正确的。我链接到 URL 的方式错误,所以每次我使用一个损坏的链接时,我都以某种方式强迫 express 创建一个新会话。在新会话中,我也丢失了 req.user 对象。
So if you are having similar issues, also check your links inside your html.
因此,如果您遇到类似问题,请同时检查 html 中的链接。
Thank you everyone for your help.
感谢大家的帮助。
回答by IT Vlogs
You can pass user info to view in Router:
您可以传递用户信息以在路由器中查看:
res.render('user/dashboad', {
...
user: req.session.passport.user,
...

