Skip to content

Instantly share code, notes, and snippets.

@ThrivingKings
Last active December 17, 2015 02:09
Show Gist options
  • Save ThrivingKings/5533620 to your computer and use it in GitHub Desktop.
Save ThrivingKings/5533620 to your computer and use it in GitHub Desktop.
Using localStorage, Sess-io will check against a stored expiration stamp and force the user to log-out once the session has expired
// Sess-io by @ThrivingKings
// http://thrivingkings.com/read/Sess-iojs-handles-session-expiration-in-pure-JavaScript
// Date fix for good ole IE8
if (!Date.now) {
Date.now = function() {
return new Date().valueOf();
}
}
// Local Storage functions for the ages
if (!window.localStorage) {
window.localStorage = {
getItem: function (sKey) {
if (!sKey || !this.hasOwnProperty(sKey)) { return null; }
return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
},
key: function (nKeyId) {
return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]);
},
setItem: function (sKey, sValue) {
if(!sKey) { return; }
document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
this.length = document.cookie.match(/\=/g).length;
},
length: 0,
removeItem: function (sKey) {
if (!sKey || !this.hasOwnProperty(sKey)) { return; }
document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
this.length--;
},
hasOwnProperty: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
}
};
window.localStorage.length = (document.cookie.match(/\=/g) || window.localStorage).length;
}
// Store the end time
localStorage.setItem('session_to', (Date.now() + 15*60000));
var page_title = document.title,
blinking;
// Checker interval
var sessio_check = window.setInterval(function() {
// Fetch the timeout stamp
var end = localStorage.getItem('session_to');
if(end) {
// Set current stamp
var now = Date.now();
// Expired
if(now>=end) {
// Clear interval
sessio_check = window.clearInterval(sessio_check);
sessio_check = null;
// Clear storage for other tabs
localStorage.setItem('session_to', 0);
// Redirect to logout
window.location = '/logout';
// Nearing the expiration
} else if( (end-now)/60000 <= 1) {
blinkTitle(page_title, 'Session expiring...');
} else {
if(blinking) {
// Reset title
document.title = page_title;
// Clear the blinking
blinking = window.clearInterval(blinking);
blinking = null;
}
}
}
}, 100);
// Blink the title every second
function blinkTitle(oT, nT) {
if(!blinking) {
blinking = window.setInterval(function() {
if(document.title==oT) {
document.title = nT;
} else {
document.title = oT;
}
}, 1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment