passport-local
passport-local copied to clipboard
Checking if user is logged in
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?
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' })
})
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 .
use connect-ensure-login for this
app.get('/api/auth/account',
require('connect-ensure-login').ensureLoggedIn(),
AuthController.account
)
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..