permission.ts 1.6 KB

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