permission.js 2.98 KB
/*
 * @Description: 
 * @Autor: renchao
 * @LastEditTime: 2023-03-07 09:43:25
 */
import router from "./router";
import store from "./store";
import { getMenuInfo } from "@/api/user";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import getPageTitle from "@/utils/get-page-title";
import Cookies from "js-cookie";
NProgress.configure({ showSpinner: false }); // NProgress Configuration

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  document.title = getPageTitle(to.meta.title);
  let hasAddDict = store.state.dict.addDict;
  let hasUser = store.state.user.hasUser;
  let hasAddRoute = store.state.permission.addRoutes;

  if (to.path == "/login/sb") {
    sessionStorage.removeItem("token");
    next();
  } else if (to.path !== "/login/jg") {
    //判断token是否存在
    const hasToken = sessionStorage.getItem("token");
    if (hasToken) {
      //请求用户信息
      if (!hasUser) {
        store.dispatch("user/getUserInfo");
      }
      if (hasAddRoute) {
        next();
      } else {
        //请求菜单
        const { result: getMenuData } = (await getMenuInfo()) || [];
        const accessRoutes = await store.dispatch(
          "permission/generateRoutes",
          getMenuData
        );
        router.addRoutes([
          ...accessRoutes,
          { path: "*", redirect: "/404", hidden: true },
        ]);
        const routeTo = Cookies.get("routerTo");
        if (!hasAddDict) {
          await store.dispatch("dict/generateDic");
        }
        if (routeTo && routeTo !== "/") {
          next({ ...to, replace: true });
        } else {
          alert("上报")
          next("/home");
        }
      }
    } else {
      next("/login/sb");
    }
  }
  if (to.path == "/login/jg") {
    sessionStorage.removeItem("token");
    next();
  } else if (to.path !== "/login/sb") {
    //判断token是否存在
    const hasToken = sessionStorage.getItem("token");
    if (hasToken) {
      //请求用户信息
      if (!hasUser) {
        store.dispatch("user/getUserInfo");
        import("@/styles/public.scss");
      }
      if (hasAddRoute) {
        next();
      } else {
        //请求菜单
        const { result: getMenuData } = (await getMenuInfo()) || [];
        const accessRoutes = await store.dispatch(
          "permission/generateRoutes",
          getMenuData
        );
        router.addRoutes([
          ...accessRoutes,
          { path: "*", redirect: "/404", hidden: true },
        ]);
        const routeTo = Cookies.get("routerTo");
        if (!hasAddDict) {
          await store.dispatch("dict/generateDic");
        }
        if (routeTo && routeTo !== "/") {
          next({ ...to, replace: true });
        } else {
          alert("监管")
          next("/home");
        }
      }
    } else {
      next("/login/jg");
    }
  }
  NProgress.done();
});
router.afterEach((to) => {
  // 解决刷新页面报404问题
  Cookies.set("routerTo", to.fullPath);
  NProgress.done();
});