authentication.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { watch } from 'vue'
  3. import type { WatchStopHandle } from 'vue'
  4. import type {
  5. NavigationGuard,
  6. RouteLocationNormalized,
  7. NavigationGuardNext,
  8. } from 'vue-router'
  9. import log from '#shared/utils/log.ts'
  10. import { useApplicationStore } from '#shared/stores/application.ts'
  11. import { useAuthenticationStore } from '#shared/stores/authentication.ts'
  12. const checkAuthenticated = (
  13. to: RouteLocationNormalized,
  14. next: NavigationGuardNext,
  15. ) => {
  16. const { authenticated } = useAuthenticationStore()
  17. if (to.name !== 'Login' && to.meta.requiresAuth && !authenticated) {
  18. log.debug(
  19. `Route guard for '${to.path}': authentication - forbidden - unauthenticated.`,
  20. )
  21. if (to.fullPath !== '/') {
  22. next({ path: '/login', query: { redirect: to.fullPath } })
  23. } else {
  24. next({ path: '/login' })
  25. }
  26. } else if (to.meta.redirectToDefaultRoute && authenticated) {
  27. // Use the default route here.
  28. log.debug(
  29. `Route guard for '${to.path}': authentication - forbidden - authenticated.`,
  30. )
  31. next('/')
  32. } else {
  33. log.debug(
  34. `Route guard for '${to.path}': authentication - allowed - public.`,
  35. )
  36. next()
  37. }
  38. }
  39. const authenticationGuard: NavigationGuard = (
  40. to: RouteLocationNormalized,
  41. from: RouteLocationNormalized,
  42. next: NavigationGuardNext,
  43. ) => {
  44. let unwatch: WatchStopHandle | undefined
  45. const application = useApplicationStore()
  46. if (application.loading) {
  47. unwatch = watch(
  48. () => application.loaded,
  49. () => {
  50. checkAuthenticated(to, next)
  51. },
  52. )
  53. } else {
  54. if (unwatch) {
  55. unwatch()
  56. unwatch = undefined
  57. }
  58. checkAuthenticated(to, next)
  59. }
  60. }
  61. export default authenticationGuard