如何将用户数据传递到所有视图?

时间:2021-07-23 18:28:01

I can't work out how best to pass user details (email, name, etc.) to 'logged in' views (I'm using jade).

我无法弄清楚如何最好地将用户详细信息(电子邮件,姓名等)传递给“登录”视图(我正在使用jade)。

I'm using passport and have access to session.passport.user in my views but only the user's _id is saved on here, and i've been told it would be bad security practice to persist it locally in the session cookie.

我正在使用护照并且可以访问我的视图中的session.passport.user,但只有用户的_id保存在这里,并且我被告知在会话cookie中将其保存在本地是不好的安全做法。

I don't want to have to pass a user object to res.render on each controller that I need the user.

我不想在我需要用户的每个控制器上将用户对象传递给res.render。

this is how i have sessions setting up locally

这就是我在本地设置会话的方式

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

and this is my middleware to check if a user is logged in

这是我的中间件,用于检查用户是否已登录

function isLoggedIn(req, res, next) {
  // if user is authenticated in the session, carry on 
  if (req.isAuthenticated()) {
    return next();
  }

  // if they aren't redirect them to the home page
  res.redirect('/');
}

I have looked at dynamic helpers but I'm using express v3.0.0rc4.

我看过动态助手,但我正在使用express v3.0.0rc4。

1 个解决方案

#1


1  

You can use res.locals for this purpose. Anything you put in that object will be available in the view context (unless, of course, it's overridden by a later context). So, for example, you could modify your isLoggedIn middleware thusly:

您可以使用res.locals来实现此目的。您放入该对象的任何内容都将在视图上下文中可用(当然,除非它被后面的上下文覆盖)。因此,例如,您可以这样修改isLoggedIn中间件:

function isLoggedIn(req, res, next) {
  // if user is authenticated in the session, carry on 
  if (req.isAuthenticated()) {
    // obviouisly, don't use static strings...
    // get these values from your authentication
    // mmechanism
    res.locals.user = 'username';
    res.locals.userEmail = 'user@domain.com';
    return next();
  }

  // if they aren't redirect them to the home page
  res.redirect('/');
}

#1


1  

You can use res.locals for this purpose. Anything you put in that object will be available in the view context (unless, of course, it's overridden by a later context). So, for example, you could modify your isLoggedIn middleware thusly:

您可以使用res.locals来实现此目的。您放入该对象的任何内容都将在视图上下文中可用(当然,除非它被后面的上下文覆盖)。因此,例如,您可以这样修改isLoggedIn中间件:

function isLoggedIn(req, res, next) {
  // if user is authenticated in the session, carry on 
  if (req.isAuthenticated()) {
    // obviouisly, don't use static strings...
    // get these values from your authentication
    // mmechanism
    res.locals.user = 'username';
    res.locals.userEmail = 'user@domain.com';
    return next();
  }

  // if they aren't redirect them to the home page
  res.redirect('/');
}