permission.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import router from './router'
  2. import Performance from '@/tools/performance'
  3. import { usePermissionStore } from "@/store/permission"
  4. import { useUserStore } from "@/store/user"
  5. export function usePermission() {
  6. let end = null
  7. const whiteList = ['/login'] // 不重定向白名单
  8. router.beforeEach(async (to, from, next) => {
  9. const { GenerateRoutes, routers } = usePermissionStore()
  10. const { GetUserInfo, token, roles, logOut } = useUserStore()
  11. end = Performance.startExecute(`${from.path} => ${to.path} 路由耗时`) /// 路由性能监控
  12. if (token) {
  13. if (to.path === '/login') {
  14. next({ path: '/' })
  15. } else {
  16. const hasRoles = roles && roles.length > 0;
  17. if (hasRoles && routers && routers.length > 0) {
  18. next()
  19. } else {
  20. try {
  21. const roles = await GetUserInfo()
  22. const accessRoutes = await GenerateRoutes(roles)
  23. accessRoutes.forEach(item => {
  24. router.addRoute(item)
  25. })
  26. next({ ...to, replace: true })
  27. } catch (error) {
  28. await logOut()
  29. console.error(error)
  30. next('/login')
  31. }
  32. }
  33. }
  34. } else {
  35. if (whiteList.includes(to.path)) {
  36. next()
  37. } else {
  38. next('/login')
  39. }
  40. }
  41. setTimeout(() => {
  42. end()
  43. }, 0)
  44. })
  45. router.afterEach(() => { })
  46. }