Skip to content

Instantly share code, notes, and snippets.

@didinkaj
Created September 9, 2023 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save didinkaj/402a0cbc6ac8519cc936014a5d532b38 to your computer and use it in GitHub Desktop.
Save didinkaj/402a0cbc6ac8519cc936014a5d532b38 to your computer and use it in GitHub Desktop.
Implementing AutoLogout Feature in Web Applications (VueJS)
<template>
<div v-if="warningZone" class="text-danger">Are you still with us?</div>
</template>
<script>
export default {
name: 'AutoLogout',
data () {
return {
events: ['click', 'mousemove', 'mousedown', 'scroll', 'keypress', 'load'],
warningTimer: null,
logoutTimer: null,
warningZone: false,
}
},
mounted() {
this.events.forEach(function (event) {
window.addEventListener(event, this.resetTimer);
}, this);
this.setTimers();
},
destroyed() {
this.events.forEach(function (event) {
window.removeEventListener(event, this.resetTimer);
}, this);
this.resetTimer();
},
methods: {
setTimers() {
this.warningTimer = setTimeout(this.warningMessage, 0.5 * 1000 * 60); // 14 minutes - 14 * 60 * 1000
this.logoutTimer = setTimeout(this.logoutUser, 0.6 * 1000 * 60); // 15 minutes - 15 * 60 * 1000
this.warningZone = false;
},
warningMessage() {
this.warningZone = true;
this.autoLogoutAlert();
},
logoutUser() {
document.getElementById('logout-button').click();
},
resetTimer() {
clearTimeout(this.warningTimer);
clearTimeout(this.logoutTimer);
this.setTimers();
},
autoLogoutAlert() {
this.$swal({
type: 'warning',
icon: 'warning',
title: 'Are you still with us?',
text: "The page will automatically logout in 2 minutes!",
showCancelButton: false,
confirmButtonColor: '#008000',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, Cancel it!',
}).then((result) => {
if (result.value) {
document.getElementById('logout-button').click();
}
});
},
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment