Engo Engo - 10 days ago 6
Javascript Question

How to show logged on username in NodeJS/ExpressJS/Passport?

I want to display the username in case the user is logged in (

function 3
). Initially, I only had
function 1
. I've changed
function 1
into
function 2
in order to display the username of the logged in user. I am not sure if this is the right way to do this, because I don't know if I need parameters
res
and
next
, and function
next()
. Any idea?

I am using
NodeJS
,
ExpressJS
and
Passport


1.

function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next()
} else {
res.redirect('/login')
}
}


2.

function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return true
}
return false
}


3.

router.get('/', function(req, res) {
if (isLoggedIn) {
res.render('index', {
username: req.user.username
})
} else {
res.render('index')
}
})

Answer

You are pretty much doing the right but calling the method isLoggedIn like a variable. I have corrected the same below.

2.

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated()) {
    return true;
  }

  return false;
}

3.

router.get('/', function(req, res, next) {
  if (isLoggedIn(req, res, next)) {
    res.render('index', {
      username: req.user.username
    });
  } else {
    res.render('index');
  }
});

Also, you can refactor the isLoggedIn method as below.

function isLoggedIn(req, res, next) {
    return req.isAuthenticated();
}