passport-local icon indicating copy to clipboard operation
passport-local copied to clipboard

Checking if user is logged in

Open jbeckton opened this issue 9 years ago • 4 comments

I am struggling to figure out how to implement a simple route middleware that checks to see if a user is logged in.

In my middleware function I assume I am to look for req.user but it is always undefined. Can someone provide some code or a blog about using sessions with passport local?

jbeckton avatar Feb 05 '16 00:02 jbeckton

You can try this if you're using sessions, passport.serializeUser, and passport.deserializeUser.

/*
 * Check the request if the user is authenticated.
 * Return an error message if not, otherwise keep going :)
 */
function ensureLoggedIn() {
  return function(req, res, next) {
    // isAuthenticated is set by `deserializeUser()`
    if (!req.isAuthenticated || !req.isAuthenticated()) {
      res.status(401).send({
        success: false,
        message: 'You need to be authenticated to access this page!'
      })
    } else {
      next()
    }
  }
}

You can then pass this to your routes to ensure authentication.

app.get('/logout/check', ensureLoggedIn(), (req, res, next) => {
  res.send({ success: true, message: 'You are authenticated' })
})

puradox avatar Feb 06 '16 00:02 puradox

Sam,

I must be missing something because I do not have req.isAuthenticated nor do I have req.user. Also seems like my session id changes on every request.

On Fri, Feb 5, 2016 at 5:37 PM, Sam Balana [email protected] wrote:

You can try this if you're using sessions http://passportjs.org/docs/#sessions, passport.serializeUser, and passport.deserializeUser.

/*

  • Check the request if the user is authenticated.
  • Return an error message if not, otherwise keep going :) */ function ensureLoggedIn() { return function(req, res, next) { // isAuthenticated is set by deserializeUser() if (!req.isAuthenticated || !req.isAuthenticated()) { res.status(401).send({ success: false, message: 'You need to be authenticated to access this page!' }) } else { next() } } }

You can then pass this to your routes to ensure authentication.

app.get('/logout/check', ensureLoggedIn(), (req, res, next) => { res.send({ success: true, message: 'You are authenticated' }) })

— Reply to this email directly or view it on GitHub https://github.com/jaredhanson/passport-local/issues/125#issuecomment-180635647 .

jbeckton avatar Feb 08 '16 21:02 jbeckton

use connect-ensure-login for this

app.get('/api/auth/account',
    require('connect-ensure-login').ensureLoggedIn(),
    AuthController.account
)

SET001 avatar Sep 06 '16 23:09 SET001

I had this issue when I used secure cookies without using https: https://www.npmjs.com/package/express-session#cookiesecure

I disabled it for dev..

kdar avatar Mar 10 '17 01:03 kdar