// Every 2.5 seconds check to see the login status of the current user. If it changes to external, logout var login_status = {}; var loginStatusChecker = function() { this.usertype = false; this.userid = false; this.ttl = false; this.timeout = false; this.initializeDialog = function() { var t = this; var attemptLogin = function() { var u = $('#login_check_username').val(); var p = $('#login_check_password').val(); t.login(u, p); }; $('#dlg_login_check').find('input').keypress(function(e) { if(e.keyCode == 13) { attemptLogin(); } }); $('#dlg_login_check').dialog({ 'autoOpen': false, 'width': 480, 'height': 260, 'modal': true, 'open': function() { $(this).find('input').val(''); }, 'beforeclose': function(ev, ui) { if(t.usertype == 'external') { window.location.href = 'index.php'; return false; } else { return true; } }, 'buttons': { 'Cancel': function() { $(this).dialog('close'); }, 'Submit': attemptLogin } }); }; this.login = function(username, password) { /* Attempt a login 1. Failed: show error message and allow another attempt to login 2. Success: Check if returned userid and usertype are same as previous 1. Yes: Populate new ttl, initiate new timeout, allow user to stay on page 2. No: Redirect to welcome page */ var t = this; $.ajax({ 'type': 'post', 'dataType': 'json', 'data': {'username': username, 'password': password}, 'url': 'index.php?page=core.login_status', 'success': function(o) { if(o.usertype == 'external') { // Login Failure app.msg('Please check your username and password', 'Login Failure'); } else { // Login Success if(t.isSameUser(o.user, o.usertype)) { t.ttl = (o.ttl + 1) * 1000; t.timeout = setTimeout(t.check, t.ttl); $('#dlg_login_check').dialog('close'); } else { window.location.href = 'index.php?page=welcome'; } } } }); }; this.isSameUser = function(id, type) { return (this.userid == id && this.usertype == type); }; this.check = function() { var t = this; if(this.userid === false) { this.initializeDialog(); } $.ajax({ 'type': 'get', 'dataType': 'json', 'url': 'index.php?page=core.login_status', 'success': function(o) { // If no login info is present, assign new info and set delay if(t.userid === false && o.usertype == 'external') { // Do nothing, no need to check login status } else if(o.usertype == 'external') { // User has been logged out due to expiry, give them the chance to log back in again $('#dlg_login_check').dialog('open'); } else { // User is logged in if(t.userid === false) { // Initial attempt, setup userID t.userid = o.user; t.usertype = o.usertype; } else if(!t.isSameUser(o.user, o.usertype)) { // A different username or type was observer - redirect to welcome page window.location.href = 'index.php?page=welcome'; } t.ttl = (o.ttl + 1) * 1000; t.timeout = setTimeout(t.check, t.ttl); } } }); }; }; $(function() { login_status = new loginStatusChecker(); login_status.check(); });