permission.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { to as tos } from 'await-to-js';
  2. import router from './router';
  3. import NProgress from 'nprogress';
  4. import 'nprogress/nprogress.css';
  5. import { getToken } from '@/utils/auth';
  6. import { isHttp, isPathMatch } from '@/utils/validate';
  7. import { isRelogin } from '@/utils/request';
  8. import { useUserStore } from '@/store/modules/user';
  9. import { useSettingsStore } from '@/store/modules/settings';
  10. import { usePermissionStore } from '@/store/modules/permission';
  11. import { ElMessage } from 'element-plus/es';
  12. NProgress.configure({ showSpinner: false });
  13. const whiteList = [
  14. '/login',
  15. '/register',
  16. '/social-callback',
  17. '/register*',
  18. '/register/*',
  19. '/ofService/*',
  20. '/ofService',
  21. '/policy/*',
  22. '/policy',
  23. '/terms',
  24. '/agreement'
  25. ];
  26. const isWhiteList = (path: string) => {
  27. return whiteList.some((pattern) => isPathMatch(pattern, path));
  28. };
  29. router.beforeEach(async (to, from, next) => {
  30. NProgress.start();
  31. /*
  32. console.log('当前访问路径:', to.path);
  33. console.log('是否在白名单:', isWhiteList(to.path));
  34. console.log('是否有 token:', getToken());
  35. console.log('用户角色数量:', useUserStore().roles.length); // 打印角色数量
  36. */
  37. if (getToken()) {
  38. to.meta.title && useSettingsStore().setTitle(to.meta.title as string);
  39. /* has token*/
  40. if (to.path === '/login') {
  41. next({ path: '/' });
  42. NProgress.done();
  43. } else if (isWhiteList(to.path)) {
  44. next();
  45. } else {
  46. if (useUserStore().roles.length === 0) {
  47. isRelogin.show = true;
  48. // 判断当前用户是否已拉取完user_info信息
  49. const [err] = await tos(useUserStore().getInfo());
  50. if (err) {
  51. await useUserStore().logout();
  52. ElMessage.error(err);
  53. next({ path: '/' });
  54. } else {
  55. isRelogin.show = false;
  56. const accessRoutes = await usePermissionStore().generateRoutes();
  57. // 根据roles权限生成可访问的路由表
  58. accessRoutes.forEach((route) => {
  59. if (!isHttp(route.path)) {
  60. router.addRoute(route); // 动态添加可访问路由表
  61. }
  62. });
  63. // @ts-expect-error hack方法 确保addRoutes已完成
  64. next({ path: to.path, replace: true, params: to.params, query: to.query, hash: to.hash, name: to.name as string }); // hack方法 确保addRoutes已完成
  65. }
  66. } else {
  67. next();
  68. }
  69. }
  70. } else {
  71. // 没有token
  72. if (isWhiteList(to.path)) {
  73. // 在免登录白名单,直接进入
  74. next();
  75. } else {
  76. const redirect = encodeURIComponent(to.fullPath || '/');
  77. next(`/login?redirect=${redirect}`); // 否则全部重定向到登录页
  78. NProgress.done();
  79. }
  80. }
  81. });
  82. router.afterEach(() => {
  83. NProgress.done();
  84. });