permissionGuard.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import type { Router, RouteRecordRaw } from 'vue-router';
  2. import { usePermissionStoreWithOut } from '/@/store/modules/permission';
  3. import { PageEnum } from '/@/enums/pageEnum';
  4. import { useUserStoreWithOut, useUserStore } from '/@/store/modules/user';
  5. import { getAppEnvConfig } from '/@/utils/env';
  6. import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
  7. import { RootRoute } from '/@/router/routes';
  8. import { getMenuList } from '/@/api/sys/menu';
  9. import { USER_INFO_KEY } from '/@/enums/cacheEnum';
  10. import { getAuthCache } from '/@/utils/auth';
  11. import SingleSignOn from '/@/utils/singleSignOn';
  12. import eventBus from '/@/utils/eventBus';
  13. const LOGIN_PATH = PageEnum.BASE_LOGIN;
  14. const DEVICE_LIST = PageEnum.DEVICE_LIST;
  15. const ROOT_PATH = RootRoute.path;
  16. const whitePathList: string[] = [LOGIN_PATH, DEVICE_LIST];
  17. let deveProType = false;
  18. if (import.meta.env.MODE === 'development') {
  19. // 开发环境下的逻辑
  20. deveProType = false;
  21. } else if (import.meta.env.MODE === 'production') {
  22. // 生产环境下的逻辑
  23. deveProType = true;
  24. } else {
  25. // 其他环境下的逻辑
  26. }
  27. export async function createPermissionGuard(router: Router) {
  28. const userStore = useUserStoreWithOut();
  29. const permissionStore = usePermissionStoreWithOut();
  30. if (location.href.indexOf('refreshToken') > -1) {
  31. var token = location.href.split('refreshToken=')[1].replace('#/', '').replace('home', '');
  32. // sessionStorage.setItem('refreshToken', token);home
  33. // sessionStorage.setItem('token', token);
  34. // userStore
  35. // .LiGongLogin({
  36. // username: 'admin',
  37. // password: 'Cdut@123',
  38. // breakCaptcha: '1',
  39. // })
  40. // .then((res) => {
  41. // console.log('首次位置:', res);
  42. // });
  43. //修改地址栏链接
  44. window.history.pushState('', '', location.href.split('?')[0]);
  45. userStore.setLigongTokenWay(token);
  46. await userStore.process({ refreshToken: token, token: token }, true);
  47. }
  48. const userStore2 = useUserStore();
  49. if (location.href.indexOf('code') > -1) {
  50. let code = location.href.split('code=')
  51. console.log('有response_type后', code[1]);
  52. var c = code[1].split('&');
  53. const userInfo = await userStore2.kidlogin({ code: c[0] })
  54. console.log('传参成功', userInfo);
  55. }
  56. router.beforeEach(async (to, from, next) => {
  57. console.log('to', to);
  58. console.log('from', from);
  59. debugger
  60. // console.log('Refresh token', sessionStorage.getItem('refreshToken'));
  61. // console.log('token', sessionStorage.getItem('refreshToken'));
  62. let userInfo = await getAuthCache(USER_INFO_KEY);
  63. // if (!userInfo) {
  64. // const obj = SingleSignOn();
  65. // if (Object.keys(obj).length != 0) {
  66. // userStore.singlesignon(obj);
  67. // }
  68. // }
  69. if (
  70. from.path === ROOT_PATH &&
  71. to.path === PageEnum.BASE_HOME &&
  72. userStore.getUserInfo.homePath &&
  73. userStore.getUserInfo.homePath !== PageEnum.BASE_HOME
  74. ) {
  75. next(userStore.getUserInfo.homePath);
  76. return;
  77. }
  78. const token = userStore.jwtToken; // || JSON.parse(sessionStorage.getItem('refreshToken'));
  79. // Whitelist can be directly entered
  80. // 路由守卫拦截, 如果是已经登陆情况, 就不要回到登陆页面了;
  81. if (whitePathList.includes(to.path as PageEnum)) {
  82. if (to.path === LOGIN_PATH && token) {
  83. const isSessionTimeout = userStore.getSessionTimeout;
  84. try {
  85. // await userStore.afterLoginAction();
  86. if (!isSessionTimeout) {
  87. next((to.query?.redirect as string) || '/');
  88. return;
  89. }
  90. } catch { }
  91. }
  92. if (to.path == '/login') sessionStorage.removeItem('refreshToken');
  93. next();
  94. return;
  95. }
  96. // token does not exist
  97. if (!token) {
  98. // You can access without permission. You need to set the routing meta.ignoreAuth to true
  99. if (to.meta.ignoreAuth) {
  100. next();
  101. return;
  102. }
  103. // redirect login page
  104. const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
  105. path: LOGIN_PATH,
  106. replace: true,
  107. };
  108. if (to.path) {
  109. redirectData.query = {
  110. ...redirectData.query,
  111. redirect: to.path,
  112. };
  113. }
  114. if (redirectData.path == '/login') {
  115. const { VITE_GLOB_ADMIN_LOGIN, VITE_GLOB_IS_IDC } = getAppEnvConfig();
  116. if (VITE_GLOB_IS_IDC && VITE_GLOB_IS_IDC.length) {
  117. window.location.href = VITE_GLOB_IS_IDC;
  118. return;
  119. } else if (deveProType) {
  120. window.location.href = VITE_GLOB_ADMIN_LOGIN;
  121. return;
  122. }
  123. }
  124. next(redirectData);
  125. return;
  126. }
  127. if (from.path === LOGIN_PATH && userInfo?.needSetPwd == false) {
  128. const getMenuListData = getAuthCache('MENU_LIST') || (await getMenuList());
  129. const getHomePage = getMenuListData.find((f) => {
  130. return f.path == '/home';
  131. });
  132. if (getHomePage?.path == '/home') {
  133. setTimeout(() => {
  134. router.push('/home');
  135. }, 1);
  136. } else {
  137. const routeF = PageEnum.BASE_HOME; //getMenuListData[0]?.children[0]?.path || getMenuListData[0]?.path;
  138. setTimeout(() => {
  139. router.push(routeF); //sjl,注销默认跳转
  140. }, 1);
  141. }
  142. }
  143. if (from.path === LOGIN_PATH && userInfo?.needSetPwd == true) {
  144. setTimeout(() => {
  145. router.push('/system/changePassword');
  146. }, 1);
  147. }
  148. if (from.path === LOGIN_PATH && to.name === PAGE_NOT_FOUND_ROUTE.name && to.fullPath !== (userStore.getUserInfo.homePath || PageEnum.BASE_HOME)) {
  149. next(userStore.getUserInfo.homePath || PageEnum.BASE_HOME);
  150. return;
  151. }
  152. if (permissionStore.getIsDynamicAddedRoute) {
  153. next();
  154. return;
  155. }
  156. const routes = await permissionStore.buildRoutesAction();
  157. routes?.forEach((route) => {
  158. router.addRoute(route as unknown as RouteRecordRaw);
  159. });
  160. router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
  161. permissionStore.setDynamicAddedRoute(true);
  162. console.log(to.query);
  163. if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
  164. // 动态添加路由后,此处应当重定向到fullPath,否则会加载404页面内容
  165. next({ path: to.fullPath, replace: true, query: to.query });
  166. } else {
  167. const redirectPath = (from.query.redirect || to.path) as string;
  168. const redirect = decodeURIComponent(redirectPath);
  169. const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
  170. next(nextData);
  171. }
  172. });
  173. }