permission.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import type {
  3. NavigationGuard,
  4. RouteLocationNormalized,
  5. NavigationGuardNext,
  6. } from 'vue-router'
  7. import log from '#shared/utils/log.ts'
  8. import { useAuthenticationStore } from '#shared/stores/authentication.ts'
  9. import { useSessionStore } from '#shared/stores/session.ts'
  10. import { ErrorStatusCodes } from '#shared/types/error.ts'
  11. import { errorOptions } from '../../error.ts'
  12. const permissionGuard: NavigationGuard = (
  13. to: RouteLocationNormalized,
  14. from: RouteLocationNormalized,
  15. next: NavigationGuardNext,
  16. ) => {
  17. // When no required permission are defined or no authentication
  18. // exists, the permission check can be skipped.
  19. if (!to.meta.requiredPermission || !useAuthenticationStore().authenticated) {
  20. log.debug(`Route guard for '${to.path}': permission - skip.`)
  21. next()
  22. return
  23. }
  24. // check the permission for the current user...
  25. const hasPermission = useSessionStore().hasPermission(
  26. to.meta.requiredPermission,
  27. )
  28. if (!hasPermission) {
  29. log.debug(`Route guard for '${to.path}': permission - forbidden.`)
  30. errorOptions.value = {
  31. title: __('Forbidden'),
  32. message: __(
  33. "You don't have the necessary permissions to access this page.",
  34. ),
  35. statusCode: ErrorStatusCodes.Forbidden,
  36. route: to.fullPath,
  37. }
  38. next({
  39. name: 'Error',
  40. query: {
  41. redirect: '1',
  42. },
  43. replace: true,
  44. })
  45. return
  46. }
  47. log.debug(`Route guard for '${to.path}': permission - allowed.`)
  48. next()
  49. }
  50. export default permissionGuard