Nodejs Passport 显示用户名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9216185/
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
Nodejs Passport display username
提问by The Code Buccaneer
In nodeJS I am using the passport module for authentication. I would like to show the username of the currently logged in user.
在 nodeJS 中,我使用通行证模块进行身份验证。我想显示当前登录用户的用户名。
I tried the following code:
我尝试了以下代码:
passport.displayName
and
和
Localstrategy.username
And for more info please also see: http://passportjs.org/docs/profile
有关更多信息,请参阅:http: //passportjs.org/docs/profile
But that is not working. Any suggestions?
但这行不通。有什么建议?
Thanks
谢谢
回答by Jared Hanson
The user (as supplied by the verify callback), is set as a property on the request at req.user.
用户(由验证回调提供)被设置为请求的属性req.user。
Any properties of the user can be accessed through that object, in your case req.user.usernameand req.user.displayName.
用户的任何属性都可以通过该对象访问,在您的情况下req.user.username和req.user.displayName.
If you're using Express, and want to expose the username as a variable within a template, that can be done when rendering:
如果您使用 Express,并希望将用户名公开为模板中的变量,则可以在渲染时完成:
app.get('/hello', function(req, res) {
res.render('index.jade', { username: req.user.username });
});
回答by Eduardo Nunes
I've created a simple view helper to have access to authentication status and user information
我创建了一个简单的视图助手来访问身份验证状态和用户信息
var helpers = {};
helpers.auth = function(req, res) {
var map = {};
map.isAuthenticated = req.isAuthenticated();
map.user = req.user;
return map;
}
app.dynamicHelpers(helpers);
After doing that you will be able to acess the object authon your views, for example auth.user.xxxx.
这样做之后,您将能够访问auth视图中的对象,例如auth.user.xxxx。
回答by ipungdev
Routes Code -
路线代码 -
router.get('/', ensureAuthenticated, function(req, res){
res.render('administrator/dashboard',{title: 'Dashboard', user:req.user.username });
console.log(req.user.username);
});
.ejs File Code -
.ejs 文件代码 -
Welcome: <%= user %>
回答by Code Tree
This might help req.session.passport.user
这可能有助于 req.session.passport.user
回答by pjehan
Helpers are not supported with Express v4.x
Express v4.x 不支持 Helpers
A good alternative is to create a middleware such as:
一个不错的选择是创建一个中间件,例如:
app.use((req, res, next) => {
res.locals.user = req.user;
next();
});
Then you can use the "user" variable in your views.
然后您可以在视图中使用“用户”变量。

