-
-
Notifications
You must be signed in to change notification settings - Fork 392
/
session_timeouter.js
78 lines (67 loc) · 2.19 KB
/
session_timeouter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import moment from "moment"
import Foundation from "foundation-sites";
$(() => {
const $timeoutModal = $("#timeoutModal");
const timeoutInSeconds = parseInt($timeoutModal.data("session-timeout"), 10);
const secondsUntilTimeoutPath = $timeoutModal.data("seconds-until-timeout-path");
const interval = $timeoutModal.data("session-timeouter-interval");
let endsAt = moment().add(timeoutInSeconds, "seconds");
const popup = new Foundation.Reveal($timeoutModal);
const $continueSessionButton = $("#continueSession");
// Ajax request is made at timeout_modal.html.erb
$continueSessionButton.on("click", () => {
$("#timeoutModal").foundation("close")
// In admin panel we have to hide all overlays
$(".reveal-overlay").css("display", "none");
})
if (!timeoutInSeconds) {
return;
}
const setTimer = (secondsUntilExpiration) => {
if (!secondsUntilExpiration) {
return;
}
endsAt = moment().add(secondsUntilExpiration, "seconds")
}
const sessionTimeLeft = () => {
return $.ajax({
method: "GET",
url: secondsUntilTimeoutPath,
contentType: "application/json",
headers: {
"X-CSRF-Token": $("meta[name=csrf-token]").attr("content")
}
})
}
const exitInterval = setInterval(() => {
const diff = endsAt - moment();
const diffInSeconds = Math.round(diff / 1000);
if (diffInSeconds > 150) {
return;
}
sessionTimeLeft().then((result) => {
const secondsUntilSessionExpires = result.seconds_remaining;
setTimer(secondsUntilSessionExpires)
if (secondsUntilSessionExpires <= 90) {
$timeoutModal.find("#reveal-hidden-sign-out")[0].click();
} else if (secondsUntilSessionExpires <= 150) {
popup.open();
}
});
}, interval);
// Devise restarts its own timer on ajax requests,
// so here we restart our.
$(document).on("ajax:complete", () => {
setTimer(timeoutInSeconds);
});
$(document).ajaxComplete((_event, _xhr, settings) => {
if (settings && settings.url === secondsUntilTimeoutPath) {
return;
}
setTimer(timeoutInSeconds);
});
window.addEventListener("beforeunload", () => {
clearInterval(exitInterval);
return;
});
})