useAuthenticationUpdates.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { watch } from 'vue'
  3. import { useRoute, useRouter } from 'vue-router'
  4. import { useApplicationStore } from '#shared/stores/application.ts'
  5. import { useAuthenticationStore } from '#shared/stores/authentication.ts'
  6. import { useSessionStore } from '#shared/stores/session.ts'
  7. // Add a watcher for authenticated changes (e.g. login/logout in a other browser tab).
  8. const useAuthenticationChanges = () => {
  9. const session = useSessionStore()
  10. const authentication = useAuthenticationStore()
  11. const application = useApplicationStore()
  12. const router = useRouter()
  13. const route = useRoute()
  14. authentication.$subscribe(async (mutation, state) => {
  15. if (state.authenticated && !session.id) {
  16. session.checkSession().then(async (sessionId) => {
  17. if (sessionId) {
  18. await authentication.refreshAfterAuthentication()
  19. }
  20. if (route.name === 'Login') {
  21. router.replace('/')
  22. }
  23. })
  24. } else if (!state.authenticated && session.id && !state.externalLogout) {
  25. await authentication.clearAuthentication()
  26. router.replace('/login')
  27. }
  28. })
  29. watch(
  30. () => application.config.maintenance_mode,
  31. async (newValue, oldValue) => {
  32. if (
  33. !oldValue &&
  34. newValue &&
  35. authentication.authenticated &&
  36. !session.hasPermission(['admin.maintenance', 'maintenance'])
  37. ) {
  38. await authentication.logout()
  39. router.replace('/login')
  40. }
  41. },
  42. )
  43. }
  44. export default useAuthenticationChanges