he wei
2025-04-23 b9bd29a1a81f6f7de479e3cc3fdfe3d85fc660bf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import router from './router';
import { storeToRefs } from 'pinia';
import pinia from '@/utils/pinia';
import { useUserStore } from './store/user';
import { usePermissionStore } from './store/permission';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { getToken } from '@/utils/auth'; // get token from cookie
import getPageTitle from '@/utils/get-page-title';
import { ElMessage } from 'element-plus';
const userStore = useUserStore(pinia);
const { roles } = storeToRefs(userStore);
const { getInfo, resetToken } = userStore;
const permissionStore = usePermissionStore(pinia);
const { generateRoutes } = permissionStore;
 
NProgress.configure({ showSpinner: false }); // NProgress Configuration
 
const whiteList = ['/login', '/auth-redirect']; // no redirect whitelist
 
router.beforeEach(async (to, from, next) => {
  // console.log('router.beforeEach', to.path, from.path);
  // start progress bar
  NProgress.start();
 
  // set page title
  document.title = getPageTitle(to.meta.title);
 
  // determine whether the user has logged in
  const hasToken = getToken();
 
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      NProgress.done(); // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
      next({ path: '/' });
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = roles.value && roles.value.length > 0;
      if (hasRoles) {
        next();
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          const infoRes = await getInfo();
          console.log('infoRes=', infoRes, '=============');
          
          let roles = [];
          if (infoRes.roles) {
            roles = infoRes.roles;
          }
 
          // generate accessible routes map based on roles
          const accessRoutes = await generateRoutes(roles);
          console.log('accessRoutes=', accessRoutes);
 
          // dynamically add accessible routes
          // router.addRoutes(accessRoutes);
          accessRoutes.forEach(item => {
            router.addRoute(item);
          });
          console.log('next=', accessRoutes, to);
 
          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true });
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
        } catch (error) {
          // remove token and go to login page to re-login
          await resetToken();
          ElMessage.error(error.message || 'Has Error');
          NProgress.done();
          next(`/login?redirect=${to.path}`);
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      NProgress.done();
      next(`/login?redirect=${to.path}`);
    }
  }
});
 
router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});