permission.ts 2.7 KB

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