I am using passport and flash to manage authentication. I want to send flash messages back to the UI per the documentation. In my scenario in the UI I am using a modal so doing a
res.render('login.ejs', { message: req.flash('loginMessage') });
won't work because you can only render on a page refresh. Therefore how can I send flash dataor any other kind of data to my page when fails to log in for some reason. Regardless of flash data in particular I cannot figure out how to render data to a modal with express.
routes.js
below the res.render never happens on a authentication failure.
//Home Page ===================================
app.get('/', function(req, res) {
res.render('login.ejs', { message: req.flash('loginMessage') });
});
//Login Modal =================================
app.post('/login', passport.authenticate('local-login', {
successRedirect : '/profile',
failureFlash : true
}));
index.ejs (where my modal is)
<div id="openModal" class="modalDialog">
<div>
<a href="#close" title="Close" class="close">X</a>
<h2 id="logintitle">Log In</h2>
<% if (message.length>0) { %>
<div class="alert alert-danger">
<%= message %>
</div>
<% } %>
<form class="form-horizontal" action="/login" method="post" id="loginform">
<div class="form-group inner-addon left-addon">
<label class="sr-only" for="login_email">Email</label>
<i class="glyphicon glyphicon-user"></i>
<input type="email" class="form-control" name="email" placeholder="Email Address" />
</div>
<div class="form-group inner-addon left-addon">
<label class="sr-only" for="login_pass">Password</label>
<i class="glyphicon glyphicon-star-empty"></i>
<input type="password" class="form-control" name="password" placeholder="Password" />
</div>
<div id="forgotpass">
<a href="#openModal3" id="forgotpass">Forgot Password?</a>
</div>
<div class="form-group">
<button type="submit" class="btn form-login-button">Log In</button>
</div>
</form>
<div class="strike">
<span>Log in with</span>
</div>
<div id="test" class="test">
<a href="/auth/facebook" class="btn btn-primary"><span class="fa fa-facebook"></span> Facebook</a>
<a href="/auth/google" class="btn btn-danger"><span class="fa fa-google-plus"></span> Google</a>
</div>
</div>
</div>
My understanding is I need to use javascript/ajax to prevent the post for being the redirect but I cannot figure out how to get the flash data to this point:
index.ejs (javascript)
$(function () {
$("#loginform").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
beforeSend: function () {
},
success: function (data) {
}
});
});
});
EDIT added some code from passport.js
function passport_login(req, email, password, done) {
//doing some validate and found bad password
return done(null, false, req.flash('loginMessage', 'Invalid Password'));
})