permission.js 3.34 KB
/*
 * @Description:
 * @Autor: renchao
 * @LastEditTime: 2023-06-09 09:43:07
 */
import Vue from 'vue'
import axios from 'axios'
import store from "./store";
import router from "./router";
import { getMenuInfo } from "@/api/user";
import { getUrlParam } from '@/utils/operation';
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import getPageTitle from "@/utils/get-page-title";
import getTheme from "@/utils/theme";
import Cookies from "js-cookie";
NProgress.configure({ showSpinner: false });
router.beforeEach(async (to, from, next) => {
  getTheme()
  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;
  // cas操作
  const token = localStorage.getItem("token") || Cookies.get('token');
  if (to.path === '/login') {
    if (token) {
      next('/')
    } else {
      next()
    }
    return
  }
  if (window._config.casEnable === true) {
    let locationUrl = window.location.protocol + '//' + window.location.host + window.location.pathname;
    if (!token) {
      let ticket = getUrlParam('ticket');
      if (ticket) {
        axios.get(Vue.prototype.BASE_API.ip + "/management/cas/validate", {
          params: {
            'ticket': ticket,
            'service': locationUrl
          }
        }).then(async (res) => {
          if (process.env.NODE_ENV === 'development') {
            localStorage.setItem('token', res.data.content.accessToken)
          } else {
            Cookies.set('token', res.data.content.accessToken)
          }
          window.location.href = localStorage.getItem('location')

        }).catch(e => {
          console.log(e)
        })
      } else {
        localStorage.setItem("location", window.location.href)
        window.location.href = window._config.casBaseURL + '/login?service=' + encodeURIComponent(locationUrl);
      }
    } else {
      permission()
    }
    async function permission () {
      if (!hasUser) {
        store.dispatch("user/getUserInfo");
        if (!hasAddDict) {
          await store.dispatch("dict/generateDic");
        }
      }
      if (hasAddRoute) {
        next();
      } else {
        //请求菜单
        const { result: getMenuData } = (await getMenuInfo(Vue.prototype.BASE_API.CODE)) || [];
        const accessRoutes = await store.dispatch(
          "permission/generateRoutes",
          getMenuData
        );
        let path = JSON.parse(getMenuData[0].metadata)?.path + JSON.parse(getMenuData[0].children[0].metadata)?.path
        router.addRoutes([
          ...accessRoutes,
          { path: "*", redirect: "/404", hidden: true }
        ]);
        const routeTo = Cookies.get("routerTo");
        if (routeTo && routeTo !== "/") {
          next({ ...to, replace: true });
        } else {
          next(path)
        }
      }
    }
  } else {
    if (!token) {
      const redirectData = {
        path: '/login',
        replace: true,
      }
      if (to.path) {
        redirectData.query = {
          ...redirectData.query,
          redirect: to.path,
        };
      }
      next(redirectData)
      return
    }
    next()
  }
  NProgress.done()
});
router.afterEach((to) => {
  // 解决刷新页面报404问题
  Cookies.set("routerTo", to.fullPath);
  NProgress.done();
})