permission.ts 2.4 KB

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