Skip to content

Instantly share code, notes, and snippets.

@xorenio
Last active March 20, 2017 16:16
Show Gist options
  • Save xorenio/21d0423c478c8c31967a30b1b0813987 to your computer and use it in GitHub Desktop.
Save xorenio/21d0423c478c8c31967a30b1b0813987 to your computer and use it in GitHub Desktop.
built in Laravel using sweetalert2 idle monitor with prompt for password on session time out.
// set timeout
var tid = setTimeout(idleCheck, 5000);
function idleCheck() {
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
type: "post",
url: '/keep-alive',
data: {'action' : 'ping'},
cache: false,
success: function(res){
if(res.auth)
{
if(res.auth._token)
{
$('meta[name=_token]').remove();
$('head').append( '<meta name="_token" content="'+res.auth._token+'">' );
$("input[value='_token']").val(res.auth._token);
}
if(res.auth.status == 0)
showIdle();
if(res.auth.status == 1 && $('.idleDialog').is(':visible') !== false)
swal.close();
}else
showIdle();
},
error : function(res){
showIdle();
}
});
tid = setTimeout(idleCheck, 5000); // repeat myself
}
function abortTimer() { // to be called when you want to stop the timer
clearTimeout(tid);
}
// timeout solution from
// http://stackoverflow.com/questions/2133166/loop-timer-in-javascript
function logOut()
{
swal("Logging out..", "", "success");
window.location.href = "/logout";
}
function showIdle()
{
if($('.idleDialog').is(':visible') === false)
{
swal({
title: "Idle",
input: 'password',
inputAttributes: {
'maxlength': 32,
'autocapitalize': 'off',
'autocorrect': 'off'
},
allowOutsideClick: false,
showCancelButton: true,
allowEscapeKey: false,
confirmButtonText: 'Login',
customClass: "idleDialog",
showLoaderOnConfirm: true,
html: '<p>Please confirm password</p><br/><a class="btn btn-warning swal2-styled btn-lg" href="#" onclick="logOut(); return false;">Logout</a>',
allowOutsideClick: false,
showCancelButton: false,
inputValidator: function (result) {
return new Promise(function (resolve, reject) {
if (result === false || result === "")
reject("Please comfirm your password");
else
{
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
type: "post",
url: '/keep-alive',
data: {'action' : 'check', 'id': $('#userID').val(), 'inputValue': result},
cache: false,
success: function(res){
if(res.auth)
{
if(res.auth._token)
{
$('meta[name=_token]').remove();
$('head').append( '<meta name="_token" content="'+res.auth._token+'">' );
$("input[value='_token']").val(res.auth._token);
}
if(res.auth.status == 0 && res.auth.error)
reject(res.auth.error);
if(res.auth.status == 1)
resolve();
}else
reject();
},
error : function(res){
reject();
}
});
}
});
}
})
.then(function (input) {
swal({
type: "success",
title: 'Welcome back',
timer: 1000
}).then(
function () {},
// handling the promise rejection
function () {}
);
}
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment