Skip to content

Instantly share code, notes, and snippets.

@beshur
Forked from cultofmetatron/gist:5349630
Last active August 21, 2019 04:02
Show Gist options
  • Save beshur/a84a60369036d0ba560a to your computer and use it in GitHub Desktop.
Save beshur/a84a60369036d0ba560a to your computer and use it in GitHub Desktop.
Javascript Node.js Express Login route with ajax responses
app.post('/login', function(req, res) {
console.log(res);
passport.authenticate('local', function(err, user, params) {
if (req.xhr) {
//thanks @jkevinburton
if (err) { return res.json({ error: err.message }); }
// e.g. in auth.js:
// if (!user.emailVerified) { return done(null, false, { message: 'Email is not verified. Please check your email for the link.' }); }
if (!user && params) { return res.json({error : params.error}); }
if (!user) { return res.json({error : "Invalid Login"}); }
req.login(user, {}, function(err) {
if (err) { return res.json({error:err}); }
return res.json(
{ user: {
id: req.user.id,
email: req.user.email,
joined: req.user.joined
},
success: true
});
});
} else {
if (err) { return res.redirect('/login'); }
if (!user) { return res.redirect('/login'); }
req.login(user, {}, function(err) {
if (err) { return res.redirect('/login'); }
return res.redirect('/');
});
}
})(req, res);
});
@deanshub
Copy link

Have you checked if the requests, after the ajax call, are able to answer req.isAuthenticated() with true?

@deanshub
Copy link

Never mind, problematic test case, great gist!

@Globik
Copy link

Globik commented Mar 14, 2015

Excuse me, but how does look then the new LocalStrategy function?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment