Passport.js - 隐式地将{user:req.user}传递给模板?

时间:2022-07-29 23:58:08

Using Passport.js and Express for multiple projects now, I have noticed myself doing this over and over again, namely specifying { user: req.user } explicitly for my Express routes. Ocassionally I forget to pass it, and suddenly it's like user is not even logged in anymore.

现在使用Passport.js和Express进行多个项目,我注意到自己一遍又一遍地这样做,即为Express路由明确指定{user:req.user}。偶尔我会忘记传递它,突然间用户甚至不再登录了。

How can I pass a user variable in my routes without having to explicitly write it for each route like this?

如何在我的路由中传递用户变量,而不必为此类路由显式写入?

app.get = function(req, res, next) {
    res.render('home', {
        title: 'Home',
        user: req.user
    });
};

I think everyauth has such Express helper, but does Passport.js?

我认为Everyauth有这样的Express助手,但Passport.js呢?

1 个解决方案

#1


30  

You could use a simple middleware for that:

你可以使用一个简单的中间件:

app.use(function(req, res, next) {
  res.locals.user = req.user;
  next();
});

This will make a user variable available in all templates, provided that req.user is populated. Make sure that you declare that middleware after you declare the passport.session middleware, but before any routes.

如果填充了req.user,这将使所有模板中的用户变量可用。确保在声明passport.session中间件之后但在任何路由之前声明该中间件。

#1


30  

You could use a simple middleware for that:

你可以使用一个简单的中间件:

app.use(function(req, res, next) {
  res.locals.user = req.user;
  next();
});

This will make a user variable available in all templates, provided that req.user is populated. Make sure that you declare that middleware after you declare the passport.session middleware, but before any routes.

如果填充了req.user,这将使所有模板中的用户变量可用。确保在声明passport.session中间件之后但在任何路由之前声明该中间件。