I am currently trying to get an jQuery alert box to pop when a user fails to authenticate using passport for not entering the right username and password in my node/express application.
I do have an alert box pop when this happens, but it literally shows for about 0.5 seconds, then vanishes again before you can read it. But I need it to stay until the user interacts with it accordingly and I am unsure of why it wont.
Reference to what it looks like am what am using found here.
I have attempted to use connect- flash but couldn't get it to work at all with all the examples I found. Is there any way for me just to have the alert box stay instead of appear and then instantly just vanish.
Server Side Code
//Global vars
var ari = require('ari-client');
var util = require('util');
var error;
var state;
var response;
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'test',
password : '',
database : 'test'
});
var express = require('express');
var app = express();
var passport = require('passport');
var passportLocal = require('passport-local');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3010, function () {
console.log('listening on *:3010');
});
//All express middleware located here.
//Access to local folder called public, enables the usage of local path files for CSS/JS/Images etc.
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(flash());
app.use(bodyParser.urlencoded({
extended : false
}));
app.set('view engine', 'ejs');
app.use(session({
secret : 'testersecret',
name: 'Test-cookie',
resave : false,
saveUninitialized : false,
cookie : {
maxAge : 3600000
} // 1 Hour
})); // session secret
app.use(passport.initialize());
app.use(passport.session());
//Use passport and local strategy, outcome for success or failure is then dependent on if the users details that they entered matched up with the values in the database.
passport.use(new passportLocal.Strategy(function (username, password, done) {
//SQL Query to run. where the values passed are paired which and compared in the DB table.
connection.query({
sql : 'SELECT * from `userman_users` WHERE `username`= ?AND`password` = sha1(?)',
timeout : 40000, // 40s
values : [username, password]
}, function (err, results, rows) {
if (results.length > 0) {
response = "Success";
console.log(results);
} else {
console.log('Error while performing Query.');
console.log(error);
response = "Failed";
}
if (response === "Success") {
done(null, {
id : username
});
} else if (response === "Failed") {
error = ("Incorrect username or password");
Error();
done(null, null);
}
});
}));
//Serialize user information
passport.serializeUser(function (user, done) {
done(null, user.id);
});
//Deserialize User information
passport.deserializeUser(function (id, done) {
done(null, {
id : id
});
});
//Gets the login route and renders the page.
app.get('/', redirectToIndexIfLoggedIn, function (req, res) {
res.render('login');
});
//The index page, isLoggedIn function always called to check to see if user is authenticated or in a session, if they are they can access the index route, if they are not they will be redirected to the login route instead.
app.get('/index', checkLoggedIn, function (req, res) {
res.render('index', {
isAuthenticated : req.isAuthenticated(),
user : req.user
});
});
//This is where the users log in details are posted to, if they are successfull then redirect to index otherwise keep them on the login route.
app.post('/login', passport.authenticate('local', {
successRedirect : '/index',
failureRedirect : '/',
failureFlash : 'Invalid username or password.'
}));
//When logout is clicked it gets the user, logs them out and deletes the session, session cookie included then redirects the user back to the login route.
app.get('/logOut', function (req, res) {
req.logOut();
req.session.destroy();
res.redirect('/')
});
//Check to see if logged in, if so carry on otherwise go back to login.
function checkLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on to the next middleware stack.
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the index page
res.redirect('/');
}
// If user authenticated then redirect to index, than arry on to the next middleware stack.
function redirectToIndexIfLoggedIn(req, res, next) {
if (req.isAuthenticated())
res.redirect('/index');
return next();
}
/*Server side listeners for all the ARI functionality from the client side E.G Kick/Mute,
This handles all real time updating/maintains proper state even if page refreshed.*/
io.sockets.on('connection', function (socket) {
});
//Updates the web page, used to update webpage in real time, and call channel dump function.
//Used for error handling, emits error message to the server side to be displayed.
function Error() {
io.sockets.emit("error", error);
error = '';
}
Client Side Code
jQuery(function ($) {
//Global Varibles
var socket = io.connect();
//Handles all error messages for the stasis application being passed from the server side functions.
socket.on("error", function (err) {
$("<div title='Error Message'>" + err + "</div>").dialog({
modal : true,
buttons : {
Ok : function () {
$(this).dialog("close");
}
}
});
});
});
Form
<div class="container">
<form action="/login" id="form_reset" method="post" class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputUser" class="sr-only">Username</label>
<input type="text" id="inputUser" name ="username" class="form-control username" placeholder="Username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control password" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block clear" type="submit">Sign in</button>
</form>
</div>
I am not too great with passport as I have only recently started using it, so sorry if its a simple question.....I just need the jQuery alert box to stay!
Any advice or guidance would help.
failureFlash means it's flashing the message, but I don't see how can you tell for how long it should be kept.
Maybe you should redirect to /error#Incorrect Password, and display the hash (what is after #) in the dialog.