PassportJS: How to get req.user in my views

Use dynamic helpers. Here's an example of my barebones user object:

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.isAdmin etc as object user is now accessible to other parts of the app.

You can add it to app.js or require from an external file. I keep all of my dynamic helpers under /utils/helpers.js


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

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));
});