New to nodejs, liking it so far, trying to do some custom handling for passport authentication. The success redirect works fine, however upon an unsuccessful attempt i would like to not continue the post event.
What I'm trying to accomplish is fire an alert off that opens a dialog (this part is working like I want, via the socket call) to the current page if there is an issue with the login attempt.
The browser just waits if I don't call res.send() for example, or attempts to redirect to a page that does not exist if I do.
routes.js
app.post('/login', function (req, res, next) {
passport.authenticate('local-login', function (err, user, msg) {
if (err) {
io.emit('status alert', err);
}
if (!user) {
io.emit('status alert', msg);
//res.send();
}
req.logIn(user, function (err) {
if (err) {
io.emit('status alert', err);
}
if (user) {
return res.redirect('/loginsplash');
}
});
})(req, res, next);
});
passport.js
passport.use(
'local-login',
new LocalStrategy({
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true
},
function (req, username, password, done) {
db.getConnection().query("SELECT * FROM users WHERE uname = ?", [username], function (err, rows) {
if (err)
return done(err);
if (!rows.length) {
return done(null, false, 'Invalid Username or Password.');
}
// if the user is found but the password is wrong
if (!bcrypt.compareSync(password, rows[0].upw))
return done(null, false, 'Invalid Username or Password.');
// all is well, return successful user
return done(null, rows[0]);
});
})
);
Well after a weekend of persistence and trial/error, my hunch to use ajax seems to be right. I finally came across a similar so here that was helpful. Hope this helps someone else, I'm probably going to tweak it some, but right now basically if the ajax response is empty (res.end), my custom dialog pops up. If there's something in it (from the res.redirect), it redirects to the intended page :
passport.js, no changes from above
routes.js
app.post('/login/ajax', function (req, res, next) {
passport.authenticate('local-login', function (err, user, info) {
if (err) { return next(err); }
if (!user) { return res.end(); }
req.logIn(user, function (err) {
if (err) { return next(err); }
return res.redirect('/loggedin');
});
})(req, res, next);
});
ajax call in .ejs page
$.ajax({
type: "POST",
url: "/login/ajax",
data: { username: username , password: password },
dataType: 'html',
success: function(data) {
if (data) {
window.location.href = '/loginsplash';
}
else {
OpenFeedbackMsgDlg("Login Failed");
}
}
}).done(function () {
console.log("http request succeeded");
alert("login success");
});
});
If anyone has suggestions/alternate approaches, I'd still be interested in learning.