简体   繁体   中英

Node.js: Conditional content depending on user authentication

I have this method in my controller to check if a user is logged in. It uses passport.js and works fine.

exports.isLoggedIn = (req, res, next) => {
  if (req.isAuthenticated()) {
    next();
    return;
  }

In one of my views I want to show certain content to the user only if he is logged in. The view is part of the header of the page. If the user is logged out he is presented with the two buttons "register" and "log in". If he is logged in, he should be presented with "account" (to manage his account) and "log out".

I use pug and tried the following. It obivously doesn't work as the function isn't defined in the pug file. Also I am not sure if this is the right approach.

if !isAuthenticated()
  a(href="/register") Register
  a(href="/login") Log in
if isAuthenticated()
  a(href="/account") Account
  a(href="/logout") Log out

It seems like you want to pass the value of isAuthenticated to your view.

I don't usually use pug myself, but it looks like you need to do the following to pass variables:

var isAuthenticated = req.isAuthenticated();
pug.renderFile('template.pug', {
  authenticated: isAuthenticated
})

and then use authenticated in your pug file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM