permissionGuard.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import type { Router, RouteRecordRaw } from 'vue-router';
  2. import { appStore } from '/@/store/modules/app';
  3. import { permissionStore } from '/@/store/modules/permission';
  4. import { PageEnum } from '/@/enums/pageEnum';
  5. import { getToken } from '/@/utils/auth';
  6. import { PAGE_NOT_FOUND_ROUTE } from '/@/router/constant';
  7. // import { RootRoute } from '../routes/index';
  8. const LOGIN_PATH = PageEnum.BASE_LOGIN;
  9. const whitePathList: PageEnum[] = [LOGIN_PATH];
  10. export function createPermissionGuard(router: Router) {
  11. router.beforeEach(async (to, from, next) => {
  12. // Jump to the 404 page after processing the login
  13. if (from.path === LOGIN_PATH && to.name === PAGE_NOT_FOUND_ROUTE.name) {
  14. next(PageEnum.BASE_HOME);
  15. return;
  16. }
  17. // Whitelist can be directly entered
  18. if (whitePathList.includes(to.path as PageEnum)) {
  19. next();
  20. return;
  21. }
  22. const token = getToken();
  23. // token does not exist
  24. if (!token) {
  25. // You can access without permission. You need to set the routing meta.ignoreAuth to true
  26. if (
  27. to.meta.ignoreAuth
  28. // || to.name === FULL_PAGE_NOT_FOUND_ROUTE.name
  29. ) {
  30. next();
  31. return;
  32. }
  33. // redirect login page
  34. const redirectData: { path: string; replace: boolean; query?: { [key: string]: string } } = {
  35. path: LOGIN_PATH,
  36. replace: true,
  37. };
  38. if (to.path) {
  39. redirectData.query = {
  40. ...redirectData.query,
  41. redirect: to.path,
  42. };
  43. }
  44. next(redirectData);
  45. return;
  46. }
  47. if (permissionStore.getIsDynamicAddedRouteState) {
  48. next();
  49. return;
  50. }
  51. const routes = await permissionStore.buildRoutesAction();
  52. routes.forEach((route) => {
  53. // router.addRoute(RootRoute.name!, route as RouteRecordRaw);
  54. router.addRoute(route as RouteRecordRaw);
  55. });
  56. const redirectPath = (from.query.redirect || to.path) as string;
  57. const redirect = decodeURIComponent(redirectPath);
  58. const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
  59. permissionStore.commitDynamicAddedRouteState(true);
  60. next(nextData);
  61. });
  62. router.afterEach((to) => {
  63. // Just enter the login page and clear the authentication information
  64. if (to.path === LOGIN_PATH) {
  65. appStore.resumeAllState();
  66. }
  67. });
  68. }