Forráskód Böngészése

[Feat 0000] 自动登录修改实现方式

houzekong 7 hónapja
szülő
commit
04567d1214

+ 17 - 14
src/hooks/vent/useAutoLogin.ts

@@ -1,44 +1,47 @@
-// 本来应该是后端做,出于工期考虑转到前端
-
 import QueryString from 'qs';
 import { useUserStore } from '/@/store/modules/user';
 import { RouteLocationNormalized } from 'vue-router';
 import { useMessage } from '../web/useMessage';
 import { AUTO_LOGIN_URL_QUERY } from '/@/router/constant';
+import { AxiosError } from 'axios';
 
 /** 自动登录功能的Hook,该Hook是为了部署在同一局域网内的多套系统之间能够无缝切换 */
 export function useAutoLogin() {
   /** 启用自动登录功能来跳转新的页面 */
-  function open(url: string, redirect?: string, target?: string) {
+  function open(url: string, target?: string) {
     const userStore = useUserStore();
     const qs = QueryString.stringify({
       [AUTO_LOGIN_URL_QUERY.key]: AUTO_LOGIN_URL_QUERY.val,
       username: userStore.getUserInfo.username,
       workNo: userStore.getUserInfo.workNo,
-      redirect,
     });
     window.open(`${url}?${qs}`, target);
   }
 
   /** 用在路由守卫里,执行自动登录的逻辑,如果存在符合自动登录标准的query则执行自动登录,返回是否需要重定向 */
-  async function doAutoLogin(route: RouteLocationNormalized): Promise<boolean> {
-    const userStore = useUserStore();
-    if (!route.query) return false;
-    if (route.query[AUTO_LOGIN_URL_QUERY.key] !== AUTO_LOGIN_URL_QUERY.val) return false;
+  async function doAutoLogin(route: RouteLocationNormalized): Promise<void> {
+    if (!route.query) return;
+    if (route.query[AUTO_LOGIN_URL_QUERY.key] !== AUTO_LOGIN_URL_QUERY.val) return;
+
     const { username, workNo } = route.query;
-    if (!username || !workNo) return false;
+    if (!username || !workNo) return;
+
     const params = {
       username: username as string,
       workNo: workNo as string,
       checkKey: new Date().getTime(),
     };
+    const userStore = useUserStore();
     try {
-      await userStore.autoLogin(params);
-      return true;
-    } catch (e: any) {
+      await userStore.autoLogin({
+        ...params,
+        goHome: false,
+      });
+      return;
+    } catch (e) {
       const message = useMessage().createMessage;
-      message.error(e.message);
-      return false;
+      message.error((e as AxiosError).message);
+      return;
     }
   }
 

+ 26 - 34
src/router/guard/permissionGuard.ts

@@ -41,13 +41,15 @@ const glob = useGlobSetting();
 export function createPermissionGuard(router: Router) {
   const userStore = useUserStoreWithOut();
   const permissionStore = usePermissionStoreWithOut();
+  const { doAutoLogin } = useAutoLogin();
 
-  router.beforeEach(async (to, from, next) => {
+  router.beforeEach(async (to, from) => {
     RootRoute.redirect = glob.homePath || PageEnum.BASE_HOME;
 
     if (_.isEmpty(history.state.current)) {
       _.assign(history.state, { current: from.fullPath });
     }
+
     if (
       from.path === ROOT_PATH &&
       to.path === (glob.homePath || PageEnum.BASE_HOME) &&
@@ -55,17 +57,12 @@ export function createPermissionGuard(router: Router) {
       userStore.getUserInfo.homePath !== (glob.homePath || PageEnum.BASE_HOME)
     ) {
       // mountMicroApp(userStore.getUserInfo.homePath);
-      next(userStore.getUserInfo.homePath);
       document.title = '首页';
-      return;
+      return userStore.getUserInfo.homePath;
     }
 
     // 如果符合自动登录的相关条件则直接执行自动登录,覆盖原有的登录信息
-    const { doAutoLogin } = useAutoLogin();
-    const redirect = await doAutoLogin(to);
-    if (redirect && to.query.redirect) {
-      next(to.query.redirect as string);
-    }
+    await doAutoLogin(to);
 
     const token = userStore.getToken;
 
@@ -81,9 +78,8 @@ export function createPermissionGuard(router: Router) {
 
         try {
           if (!isSessionTimeout) {
-            next((to.query?.redirect as string) || '/');
             document.title = '';
-            return;
+            return (to.query?.redirect as string) || '/';
           }
         } catch {}
         //update-begin---author:wangshuai ---date:20220629  for:[issues/I5BG1I]vue3不支持auth2登录------------
@@ -94,27 +90,24 @@ export function createPermissionGuard(router: Router) {
         // if (to.query.tenantId) {
         //   setAuthCache(OAUTH2_THIRD_LOGIN_TENANT_ID, to.query.tenantId);
         // }
-        next({ path: OAUTH2_LOGIN_PAGE_PATH });
         document.title = '登录';
+        return { path: OAUTH2_LOGIN_PAGE_PATH };
         ///
 
         //update-end---author:wangshuai ---date:20230224  for:[QQYUN-3440]新建企业微信和钉钉配置表,通过租户模式隔离------------
-        return;
+        return true;
         //update-end---author:wangshuai ---date:20220629  for:[issues/I5BG1I]vue3不支持auth2登录------------
       }
-      next();
-
       document.title = to.meta.title;
-      return;
+      return true;
     }
 
     // token does not exist
     if (!token) {
       // You can access without permission. You need to set the routing meta.ignoreAuth to true
       if (to.meta.ignoreAuth) {
-        next();
         document.title = to.meta.title;
-        return;
+        return true;
       }
       // query如果没有明确要求跳过sso则执行sso登录
       if (to.query[SKIP_SSO_URL_QUERY.key] !== SKIP_SSO_URL_QUERY.val) {
@@ -128,10 +121,10 @@ export function createPermissionGuard(router: Router) {
         await userStore.mockLogin({
           goHome: false,
         });
-        return next({
+        return {
           path: to.path,
           query: to.query,
-        });
+        };
       }
 
       //update-begin---author:wangshuai ---date:20220629  for:[issues/I5BG1I]vue3 Auth2未实现------------
@@ -139,13 +132,13 @@ export function createPermissionGuard(router: Router) {
       if (whitePathList.includes(to.path as PageEnum)) {
         // 在免登录白名单,如果进入的页面是login页面并且当前是OAuth2app环境,就进入OAuth2登录页面
         if (to.path === LOGIN_PATH && isOAuth2AppEnv()) {
-          next({ path: OAUTH2_LOGIN_PAGE_PATH });
           document.title = '登录';
+          return { path: OAUTH2_LOGIN_PAGE_PATH };
         } else {
           //在免登录白名单,直接进入
           // mountMicroApp(to.path);
-          next();
           document.title = to.meta.title;
+          return true;
         }
       } else {
         //update-begin---author:wangshuai ---date:20230302  for:只有首次登陆并且是企业微信或者钉钉的情况下才会调用------------
@@ -196,16 +189,14 @@ export function createPermissionGuard(router: Router) {
         };
       }
       // mountMicroApp(redirectData.path);
-      next(redirectData);
       document.title = '';
-      return;
+      return redirectData;
     }
     //==============================【首次登录并且是企业微信或者钉钉的情况下才会调用】==================
     //判断是免登录页面,如果页面包含/tenantId/,那么就直接前往主页
     if (isOAuth2AppEnv() && to.path.indexOf('/tenantId/') != -1) {
-      next(userStore.getUserInfo.homePath || PageEnum.BASE_HOME);
       document.title = '首页';
-      return;
+      return userStore.getUserInfo.homePath || PageEnum.BASE_HOME;
     }
     //==============================【首次登录并且是企业微信或者钉钉的情况下才会调用】==================
 
@@ -216,9 +207,8 @@ export function createPermissionGuard(router: Router) {
       to.fullPath !== (userStore.getUserInfo.homePath || glob.homePath || PageEnum.BASE_HOME)
     ) {
       // mountMicroApp(userStore.getUserInfo.homePath || PageEnum.BASE_HOME);
-      next(userStore.getUserInfo.homePath || PageEnum.BASE_HOME);
       document.title = '首页';
-      return;
+      return userStore.getUserInfo.homePath || PageEnum.BASE_HOME;
     }
 
     // get userinfo while last fetch time is empty
@@ -228,16 +218,17 @@ export function createPermissionGuard(router: Router) {
       } catch (err) {
         console.info(err);
         // mountMicroApp(to.path);
-        next();
         document.title = to.meta.title;
+        return true;
       }
     }
+    console.log('debug getIsDynamicAddedRoute');
     if (permissionStore.getIsDynamicAddedRoute) {
       // mountMicroApp(to.path);
-      next();
       document.title = to.meta.title;
-      return;
+      return true;
     }
+    console.log('debug escape the  404 page exp');
 
     const routes = await permissionStore.buildRoutesAction();
 
@@ -250,16 +241,17 @@ export function createPermissionGuard(router: Router) {
 
     permissionStore.setDynamicAddedRoute(true);
 
+    console.log('debug reach the last exp');
     if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
+      console.log('debug redirect');
       // 动态添加路由后,此处应当重定向到fullPath,否则会加载404页面内容
-      next({ path: to.fullPath, replace: true, query: to.query });
+      return { path: to.fullPath, replace: true, query: to.query };
     } else {
       const redirectPath = (from.query.redirect || to.path) as string;
       const redirect = decodeURIComponent(redirectPath);
-      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
-      // mountMicroApp(nextData.path);
-      next(nextData);
+      // mountMicroApp(return Data.path);
       document.title = '';
+      return to.path === redirect ? { ...to, replace: true } : { path: redirect };
     }
   });
 }

+ 9 - 12
src/store/modules/user.ts

@@ -192,7 +192,7 @@ export const useUserStore = defineStore({
           router.addRoute(QIANKUN_ROUTE as unknown as RouteRecordRaw);
           permissionStore.setDynamicAddedRoute(true);
         }
-        await this.setLoginInfo({ ...data, isLogin: true });
+        this.setLoginInfo({ ...data, isLogin: true });
         //update-begin-author:liusq date:2022-5-5 for:登录成功后缓存拖拽模块的接口前缀
         localStorage.setItem(JDragConfigEnum.DRAG_BASE_URL, useGlobSetting().domainUrl);
         //update-end-author:liusq date:2022-5-5 for: 登录成功后缓存拖拽模块的接口前缀
@@ -405,17 +405,14 @@ export const useUserStore = defineStore({
         mode?: ErrorMessageMode;
       }
     ) {
-      try {
-        const { goHome = true, mode, ...loginParams } = params;
-        const data = await autoLoginApi(loginParams, mode);
-        const { token, userInfo } = data;
-        // save token
-        this.setToken(token);
-        this.setTenant(userInfo.loginTenantId);
-        return this.afterLoginAction(goHome, data);
-      } catch (error) {
-        return Promise.reject(error);
-      }
+      const { goHome = true, mode, ...loginParams } = params;
+      const data = await autoLoginApi(loginParams, mode);
+      const { token, userInfo } = data;
+      // save token
+      this.setToken(token);
+      this.setTenant(userInfo.loginTenantId);
+      await this.afterLoginAction(goHome, data);
+      return;
     },
   },
 });

+ 2 - 2
src/views/vent/home/billboard/index.vue

@@ -136,8 +136,8 @@
   // 页面跳转
   function openHandler(ip: string) {
     // const url = `http://localhost:3100/login`;
-    const url = `http://${ip}:8092/login`;
-    open(url, routePathMap[props.billboardType]);
+    const url = `http://${ip}:8092/${routePathMap[props.billboardType]}`;
+    open(url);
   }
 
   // 返回首页

+ 2 - 2
src/views/vent/home/clique/components/dialog-modal.vue

@@ -215,8 +215,8 @@
   // 重新向到新的页面,业务上讲是公司端跳转矿端
   function redictTo() {
     if (!props.centerDetail.ip) return;
-    const url = `http://${props.centerDetail.ip}:8092/login`;
-    open(url, '/micro-vent-3dModal/dashboard/analysis');
+    const url = `http://${props.centerDetail.ip}:8092/micro-vent-3dModal/dashboard/analysis`;
+    open(url);
   }
 </script>
 <style lang="less" scoped>