import router from "@/router/index-user.js"; import NProgress from "nprogress"; import "nprogress/nprogress.css"; import { userInfoCookie } from "@/utils/auth"; import store from "@/store"; NProgress.configure({ showSpinner: false }); // NProgress Configuration const whiteList = [ "/login", "/reg", "/forget-pwd", "/auth-redirect", "/print", "/inbound/purchase/print-barcode", // 网站 "/index", "/upload-card-id", "/contact-us", "/business", "/store-search", "/way-search", "/newsinfo" ]; // no redirect whitelist /* * * 查找菜单是否有权限 * @param routes asyncRouterMap * @param path */ function findRouter(routes, path, parentPath) { let isExist = false; routes.forEach(route => { var currentPath = route.path; if (currentPath.indexOf("/") !== 0) { currentPath = parentPath + "/" + currentPath; } if (currentPath.toLowerCase() === path.toLowerCase()) { isExist = true; return true; } else { if (route.children) { if (findRouter(route.children, path, currentPath)) { isExist = true; } } } }); return isExist; } /* * * 校验是否存在白名单中 * @param path */ function checkWhite(path) { var isOK = false; whiteList.forEach(item => { if (path.toLowerCase().indexOf(item) >= 0) isOK = true; }); return isOK; } router.beforeEach((to, from, next) => { NProgress.start(); // start progress bar if (checkWhite(to.path)) { // 在免登录白名单,直接进入 const userInfo = store.getters.userInfo; if (!userInfo || !userInfo.accessToken) { store.dispatch("GetUserInfo").then(res => { next(); NProgress.done(); return; }); } else { next(); NProgress.done(); } return; } var userInfo = userInfoCookie.getUserInfo(); if (userInfo && userInfo.accessToken) { // determine if there has token /* has token */ if (to.path === "/login") { next(); NProgress.done(); // if current page is dashboard will not trigger afterEach hook, so manually handle it } else { const userInfo = store.getters.userInfo; // var addRouters = store.getters.routers; if (!userInfo || !userInfo.accessToken) { store.dispatch("GetUserInfo").then(res => { if (!res.menuList) { next(`/login?redirect=${to.path}`); // 否则全部重定向到登录页 NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it return; } // 生成菜单 store.dispatch("GenerateUserRoutes", res.menuList).then(() => { // 根据roles权限生成可访问的路由表 /* var routers = store.getters.routers; if (!routers.length) { Message.error('没有设置任何权限!'); next(`/login?redirect=${to.path}`) // 全部重定向到登录页 } router.addRoutes(routers); // 动态添加可访问路由表 */ next({ ...to, replace: true }); }); }); } else { var routes = store.getters.permission_routers; const existRoute = findRouter(routes, to.path, ""); if (existRoute) { next(); } else { next({ path: "/401", replace: true, query: { noGoBack: true } }); } } NProgress.done(); // finish progress bar } } else { next(`/login?redirect=${to.path}`); // 否则全部重定向到登录页 NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it } }); router.afterEach(() => { NProgress.done(); // finish progress bar });