Nodejs Passport display username

假装没事ソ 提交于 2019-12-17 17:44:33

问题


In nodeJS I am using the passport module for authentication. I would like to show the username of the currently logged in user.

I tried the following code:

passport.displayName

and

Localstrategy.username

And for more info please also see: http://passportjs.org/docs/profile

But that is not working. Any suggestions?

Thanks


回答1:


The user (as supplied by the verify callback), is set as a property on the request at req.user.

Any properties of the user can be accessed through that object, in your case req.user.username and 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:

app.get('/hello', function(req, res) {
    res.render('index.jade', { username: req.user.username });
});



回答2:


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 auth on your views, for example auth.user.xxxx.




回答3:


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 -

Welcome:  <%= user %>  



回答4:


Helpers are not supported with Express v4.x

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.




回答5:


This might help req.session.passport.user



来源:https://stackoverflow.com/questions/9216185/nodejs-passport-display-username

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!