permission.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import router from './router';
  2. // import systemSetting from './router/modules/systemSetting';
  3. import store from '@/vendors/vuex'
  4. import NProgress from 'nprogress';
  5. import 'nprogress/nprogress.css';
  6. import {
  7. getToken
  8. } from './utils/auth';
  9. NProgress.configure({
  10. showSpinner: false
  11. });
  12. const whiteList = ['/login', '/ship_login', '/userAgreement', '/privacyAgreement', '/about', 'lab', '/contractManagement'];
  13. router.beforeEach(async (to, _, next) => {
  14. NProgress.start();
  15. // 用户刷新页面,localStorage还在,但vuex.store里的东西会reset
  16. const hasToken = getToken();
  17. console.log(hasToken)
  18. if (hasToken) {
  19. if (whiteList.includes(to.path)) {
  20. next({
  21. path: '/'
  22. });
  23. NProgress.done();
  24. } else {
  25. console.log(store.getters.token)
  26. if (!store.getters.token) {
  27. console.log(to)
  28. // 首次以及用户手动刷新,token都会还原回空字符串
  29. const accessRoutes = await store.dispatch('permission/generateRoutes');
  30. router.addRoutes(accessRoutes);
  31. // router.addRoutes([systemSetting]);
  32. // router.addRoutes([{
  33. // path: '*',
  34. // redirect: '/404',
  35. // meta: {},
  36. // hidden: true
  37. // }]);
  38. store.commit('user/SET_TOKEN', 'admin'); // 之所以放到这儿是因为想让store.getters.toke成为上面的标识
  39. next({
  40. ...to,
  41. replace: true
  42. });
  43. const value = to.query.src || to.fullPath;
  44. const label = to.query.name || to.name;
  45. const meta = to.meta || {};
  46. const i18n = to.query.i18n;
  47. if (
  48. meta.isTab !== false
  49. ) {
  50. store.commit('ADD_TAG', {
  51. label: label,
  52. value: value,
  53. params: to.params,
  54. query: to.query,
  55. meta: (() => {
  56. if (!i18n) {
  57. return meta;
  58. }
  59. return {
  60. i18n: i18n
  61. };
  62. })(),
  63. group: to.group || []
  64. });
  65. }
  66. next();
  67. } else {
  68. if (!whiteList.includes(to.path)) {
  69. checkLoginUser();
  70. }
  71. next();
  72. }
  73. }
  74. } else {
  75. if (whiteList.indexOf(to.path) !== -1) {
  76. if (!whiteList.includes(to.path)) {
  77. checkLoginUser();
  78. }
  79. next();
  80. } else {
  81. next(getLoginOutUrl() + `?redirect=${to.path}`);
  82. NProgress.done();
  83. }
  84. }
  85. });
  86. router.afterEach(() => {
  87. NProgress.done();
  88. });
  89. function checkLoginUser() {
  90. if (location.port) {
  91. return;
  92. }
  93. }
  94. function getLoginOutUrl() {
  95. if (process.env.VUE_APP_PACKAGE_ENV === 'ship') {
  96. return '/ship_login';
  97. }
  98. return '/login';
  99. }