user7327830
user7327830

Reputation:

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

Upvotes: 0

Views: 375

Answers (1)

aprabaldi
aprabaldi

Reputation: 141

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.

Upvotes: 1

Related Questions