Renew token in authenticated component

This commit is contained in:
kolaente 2020-11-01 17:46:42 +01:00
parent 31c02cfe58
commit d43c16e654
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
2 changed files with 29 additions and 32 deletions

View File

@ -45,11 +45,6 @@ export default {
KeyboardShortcuts, KeyboardShortcuts,
Notification, Notification,
}, },
data() {
return {
currentDate: new Date(),
}
},
beforeMount() { beforeMount() {
// Check if the user is offline, show a message then // Check if the user is offline, show a message then
this.$store.commit(ONLINE, navigator.onLine) this.$store.commit(ONLINE, navigator.onLine)
@ -93,33 +88,7 @@ export default {
this.$router.push({name: 'home'}) this.$router.push({name: 'home'})
} }
// Try renewing the token every time vikunja is loaded initially this.renewTokenOnFocus()
// (When opening the browser the focus event is not fired)
this.$store.dispatch('auth/renewToken')
// Check if the token is still valid if the window gets focus again to maybe renew it
window.addEventListener('focus', () => {
if (!this.userAuthenticated) {
return
}
const expiresIn = this.userInfo.exp - +new Date() / 1000
// If the token expiry is negative, it is already expired and we have no choice but to redirect
// the user to the login page
if (expiresIn < 0) {
this.$store.dispatch('auth/checkAuth')
this.$router.push({name: 'user.login'})
return
}
// Check if the token is valid for less than 60 hours and renew if thats the case
if (expiresIn < 60 * 3600) {
this.$store.dispatch('auth/renewToken')
console.log('renewed token')
}
})
}, },
computed: { computed: {
authUser() { authUser() {

View File

@ -42,6 +42,9 @@ export default {
watch: { watch: {
'$route': 'doStuffAfterRoute', '$route': 'doStuffAfterRoute',
}, },
created() {
this.renewTokenOnFocus()
},
computed: mapState({ computed: mapState({
fullpage: IS_FULLPAGE, fullpage: IS_FULLPAGE,
namespaces(state) { namespaces(state) {
@ -74,6 +77,31 @@ export default {
this.$store.commit(CURRENT_LIST, {}) this.$store.commit(CURRENT_LIST, {})
} }
}, },
renewTokenOnFocus() {
// Try renewing the token every time vikunja is loaded initially
// (When opening the browser the focus event is not fired)
this.$store.dispatch('auth/renewToken')
// Check if the token is still valid if the window gets focus again to maybe renew it
window.addEventListener('focus', () => {
const expiresIn = this.userInfo.exp - +new Date() / 1000
// If the token expiry is negative, it is already expired and we have no choice but to redirect
// the user to the login page
if (expiresIn < 0) {
this.$store.dispatch('auth/checkAuth')
this.$router.push({name: 'user.login'})
return
}
// Check if the token is valid for less than 60 hours and renew if thats the case
if (expiresIn < 60 * 3600) {
this.$store.dispatch('auth/renewToken')
console.debug('renewed token')
}
})
},
}, },
} }
</script> </script>