permission.ts 2.3 KB

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