routing.global.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { useAbility } from '@casl/vue'
  2. import { useRedirect } from '~/composables/utils/useRedirect'
  3. /**
  4. * Détermine les autorisations d'accès aux pages
  5. */
  6. export default defineNuxtRouteMiddleware((to, _) => {
  7. const ability = useAbility()
  8. const candidates = to.matched.map((route) => route.name)
  9. const restrictedPages = ability.rules
  10. .filter((rule) => rule.action.toString() === 'display')
  11. .map((rule) => rule.subject.toString())
  12. candidates.forEach((routeName) => {
  13. const name: string = routeName?.toString() ?? ''
  14. // <<- TODO: remove after 2.6 release
  15. const inDevPages = []
  16. const runtimeConfig = useRuntimeConfig()
  17. if (
  18. runtimeConfig.public.env === 'production' &&
  19. inDevPages.includes(name)
  20. ) {
  21. const { redirectToHome } = useRedirect()
  22. redirectToHome()
  23. }
  24. // ->>
  25. if (
  26. name &&
  27. restrictedPages.includes(name) &&
  28. !ability.can('display', name)
  29. ) {
  30. console.error('No right to see this page')
  31. const { redirectToHome } = useRedirect()
  32. redirectToHome()
  33. }
  34. })
  35. })