authentication.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { watch } from 'vue'
  3. import { useApplicationStore } from '#shared/stores/application.ts'
  4. import { useAuthenticationStore } from '#shared/stores/authentication.ts'
  5. import log from '#shared/utils/log.ts'
  6. import type { WatchStopHandle } from 'vue'
  7. import type {
  8. NavigationGuard,
  9. RouteLocationNormalized,
  10. NavigationGuardNext,
  11. } from 'vue-router'
  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