permission.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import router from './index'
  2. import store from '../store'
  3. import { Message } from 'element-ui'
  4. import NProgress from 'nprogress' // progress bar
  5. import 'nprogress/nprogress.css' // progress bar style
  6. import { getToken, setToken, getAuthRoutes } from '@/utils/auth' // get token from cookie
  7. import permission from '@/utils/permission'
  8. import getPageTitle from '@/utils/getPageTitle'
  9. NProgress.configure({ showSpinner: false }) // NProgress Configuration
  10. const whiteList = ['/login', '/redirect', '/404'] // no redirect whitelist
  11. function handleRoute(to, routes, next) {
  12. let validPath = !permission.enable_404;
  13. let hasToken = getToken()
  14. if (!validPath && to.path && routes.length) {
  15. for (let _route of routes) {
  16. if (to.path == _route[permission.RESOURCE_KEY] || (to.meta && to.meta.activeMenu == _route[permission.RESOURCE_KEY])) {
  17. validPath = true;
  18. break;
  19. }
  20. }
  21. }
  22. if (hasToken) {
  23. //console.log("已登录", validPath);
  24. if (to.path === '/login') {
  25. // if is logged in, redirect to the home page
  26. next({ path: '/redirect' })
  27. NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
  28. } else if (!validPath) {
  29. next({ path: '/404' })
  30. NProgress.done()
  31. } else {
  32. next();
  33. }
  34. } else {
  35. //console.log("未登录", to.path, hasToken);
  36. /* has no token*/
  37. if (whiteList.indexOf(to.path) !== -1) {
  38. // in the free login whitelist, go directly
  39. next()
  40. NProgress.done()
  41. } else {
  42. // other pages that do not have permission to access are redirected to the login page.
  43. next(`/login?redirect=${to.path}`)
  44. NProgress.done()
  45. }
  46. }
  47. }
  48. router.beforeEach(async(to, from, next) => {
  49. // start progress bar
  50. NProgress.start()
  51. // set page title
  52. document.title = getPageTitle(to.meta.title)
  53. if (whiteList.indexOf(to.path) >= 0) {
  54. next();
  55. } else {
  56. // determine whether the user has logged in
  57. //console.log("权限控制", to, from);
  58. const routes = store.getters.resources
  59. if (routes.length == 0) {
  60. getAuthRoutes(rs => {
  61. if (rs) {
  62. if (rs.length) {
  63. store.commit("user/SET_RESOURCES", rs);
  64. store.commit('permission/SET_ROUTES', rs);
  65. routes.push(...rs);
  66. handleRoute(to, routes, next);
  67. } else {
  68. next({ path: '/404' })
  69. NProgress.done()
  70. }
  71. } else {
  72. next({ path: '/login' })
  73. NProgress.done()
  74. }
  75. });
  76. } else {
  77. handleRoute(to, routes, next);
  78. }
  79. }
  80. })
  81. router.afterEach(() => {
  82. // finish progress bar
  83. NProgress.done()
  84. })