Files
td_official/src/permission.ts

85 lines
2.2 KiB
TypeScript
Raw Normal View History

2025-08-28 03:35:18 +08:00
import $cache from '@/plugins/cache';
2025-05-21 11:24:53 +08:00
import { to as tos } from 'await-to-js';
import router from './router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken } from '@/utils/auth';
import { isHttp, isPathMatch } from '@/utils/validate';
import { isRelogin } from '@/utils/request';
import useUserStore from '@/store/modules/user';
import useSettingsStore from '@/store/modules/settings';
import usePermissionStore from '@/store/modules/permission';
2025-08-28 20:10:46 +08:00
let isFirst = false;
2025-05-21 11:24:53 +08:00
NProgress.configure({ showSpinner: false });
2025-08-14 18:53:01 +08:00
const whiteList = ['/login', '/register', '/social-callback', '/register*', '/register/*', '/materials/purchaseDoc/uploadCode'];
2025-05-21 11:24:53 +08:00
const isWhiteList = (path: string) => {
2025-08-09 09:54:23 +08:00
return whiteList.some((pattern) => isPathMatch(pattern, path));
};
2025-05-21 11:24:53 +08:00
2025-08-28 20:10:46 +08:00
router.beforeEach(async (to, from) => {
2025-05-21 11:24:53 +08:00
NProgress.start();
2025-08-28 20:10:46 +08:00
// 特殊页面放行
if (['/indexEquipment', '/materials/purchaseDoc/uploadCode', '/codeDetail'].includes(to.path)) {
return true;
}
// 已登录
if (getToken()) {
if (to.meta.title) useSettingsStore().setTitle(to.meta.title);
2025-05-21 11:24:53 +08:00
if (to.path === '/login') {
NProgress.done();
2025-08-28 20:10:46 +08:00
return { path: '/' };
2025-05-21 11:24:53 +08:00
}
2025-08-28 20:10:46 +08:00
2025-05-21 11:24:53 +08:00
if (isWhiteList(to.path)) {
2025-08-28 20:10:46 +08:00
return true;
}
if ((!isFirst && useUserStore().roles.length === 0) || $cache.local.getJSON('isCheckRole') === 'true') {
isFirst = true;
isRelogin.show = true;
const [err] = await tos(useUserStore().getInfo());
if (err) {
await useUserStore().logout();
ElMessage.error(err);
NProgress.done();
return { path: '/' };
}
isRelogin.show = false;
const accessRoutes = await usePermissionStore().generateRoutes();
accessRoutes.forEach((route) => {
if (!isHttp(route.path)) router.addRoute(route);
});
$cache.local.remove('isCheckRole');
// 确保路由已添加后再跳转
return { ...to, replace: true };
2025-05-21 11:24:53 +08:00
}
2025-08-28 20:10:46 +08:00
return true;
} else {
isFirst = false;
}
// 未登录
if (isWhiteList(to.path)) {
return true;
2025-05-21 11:24:53 +08:00
}
2025-08-28 20:10:46 +08:00
const redirect = encodeURIComponent(to.fullPath || '/');
NProgress.done();
return { path: `/login?redirect=${redirect}` };
2025-05-21 11:24:53 +08:00
});
router.afterEach(() => {
NProgress.done();
});