Bladeren bron

迭代用户登录机制

songxy 1 jaar geleden
bovenliggende
commit
dc271f1f79

+ 2 - 2
client_h5/.env.dev

@@ -1,5 +1,5 @@
-VITE_BASE_URL='http://10.10.10.7:18080'
-# VITE_BASE_URL='http://oa.zjugis.com:28080/'
+# VITE_BASE_URL='http://10.10.10.7:18080'
+VITE_BASE_URL='http://oa.zjugis.com:28080/'
 # VITE_BASE_URL='http://localhost:6090/'
 
 

+ 0 - 64
client_h5/src/App.vue

@@ -1,68 +1,4 @@
 <script setup lang="ts">
-import { useUserStoreWithOut, UserInterface } from "@/stores/modules/user";
-import { getAuthCode } from "dingtalk-jsapi";
-import reqest from "@/utils/request";
-import { useDictStoreWithOut } from "@/utils/dict";
-
-const userStore = useUserStoreWithOut();
-
-const initUserInfoHandler = async () => {
-  const code: string = (await getDDAuthCode()) as string;
-  const userIdResult = await getUserIdByDD({ code });
-  if (userIdResult && userIdResult?.data) {
-    localStorage.setItem("ACCESS_TOKEN", userIdResult?.data.accessToken);
-    useDictStoreWithOut();
-    const userResult = await getUserInfoById();
-    if (userResult && userResult?.data) {
-      const userInfo: UserInterface = {
-        id: userResult?.data.user.id,
-        avatar:  userResult?.data.user.avatar,
-        nickname: userResult?.data.user.nickname,
-        deptId: userResult?.data.user.deptId,
-        deptName: userResult?.data.user.deptName,
-        signatureUrl: userResult?.data.user.signatureUrl,
-      };
-      userStore.setUser(userInfo);
-      localStorage.setItem("_userInfo", JSON.stringify(userInfo));
-    }
-  }
-};
-initUserInfoHandler();
-function getDDAuthCode() {
-  return new Promise((resolve, reject) => {
-    getAuthCode({
-      corpId: "ding65143abf9aeea2ec",
-      success: (res: any) => {
-        const { code } = res;
-        if (code) {
-          resolve(code);
-        }
-      },
-      fail: (ex: any) => {
-        reject(ex);
-      },
-      complete: () => {},
-    });
-  });
-}
-interface UserIdParam {
-  code: string;
-}
-const getUserIdByDD = async (data: Required<UserIdParam>) => {
-  return reqest.post(
-    `/app-api/system/auth/login-ding?code=${data.code}`,
-    null,
-    {
-      headers: {
-        isAuth: false,
-      },
-    }
-  );
-};
-//@ts-ignore
-const getUserInfoById = async () => {
-  return reqest.get("/admin-api/system/auth/get-permission-info");
-};
 </script>
 
 <template>

+ 1 - 1
client_h5/src/pages/home/index.scss

@@ -71,7 +71,7 @@
               position: absolute;
               right: 8px;
               bottom: 8px;
-              z-index: 9999999;
+              z-index: 999;
               width: 13vw;
               height: 13vw;
             }

+ 87 - 0
client_h5/src/router/getUserInfo.ts

@@ -0,0 +1,87 @@
+
+import { useUserStoreWithOut, UserInterface } from "@/stores/modules/user";
+import { getAuthCode } from "dingtalk-jsapi";
+import { getStoreObject, getStoreString, setStoreObject } from '@/utils/common'
+import reqest from "@/utils/request";
+import { useDictStoreWithOut } from "@/utils/dict";
+
+const USERINFO_KEY: string = '_userInfo';
+const TOKEN_KEY: string = 'ACCESS_TOKEN'
+
+const initUserInfoHandler = async () => {
+  const userStore = useUserStoreWithOut();
+  const userInfoObject = getStoreObject(USERINFO_KEY);
+  if (getStoreString(TOKEN_KEY) && userInfoObject) {
+    userStore.setUser(userInfoObject);
+    return true;
+  };
+  try {
+    const code: string = (await getDDAuthCode()) as string;
+    const userIdResult = await getUserIdByDD({ code });
+    if (userIdResult && userIdResult?.data) {
+      setStoreObject(TOKEN_KEY, userIdResult?.data.accessToken);
+      useDictStoreWithOut();
+      const userResult = await getUserInfoById();
+      if (userResult && userResult?.data) {
+        const userInfo: UserInterface = {
+          id: userResult?.data.user.id,
+          avatar:  userResult?.data.user.avatar,
+          nickname: userResult?.data.user.nickname,
+          deptId: userResult?.data.user.deptId,
+          deptName: userResult?.data.user.deptName,
+          signatureUrl: userResult?.data.user.signatureUrl,
+        };
+        userStore.setUser(userInfo);
+        setStoreObject(USERINFO_KEY, userInfo);
+        return true;
+      } else {
+        return false;
+      }
+    } else {
+      return false;
+    }
+  } catch (err: any) {
+    console.error("获取用户Error:" + JSON.stringify(err));
+    return false;
+  }
+};
+function getDDAuthCode() {
+  return new Promise((resolve, reject) => {
+    getAuthCode({
+      corpId: "ding65143abf9aeea2ec",
+      success: (res: any) => {
+        const { code } = res;
+        if (code) {
+          resolve(code);
+        }
+      },
+      fail: (ex: any) => {
+        reject(ex);
+      },
+      complete: () => {},
+    });
+  });
+}
+interface UserIdParam {
+  code: string;
+}
+const getUserIdByDD = async (data: Required<UserIdParam>) => {
+  return reqest.post(
+    `/app-api/system/auth/login-ding?code=${data.code}`,
+    null,
+    {
+      headers: {
+        isAuth: false,
+      },
+    }
+  );
+};
+//@ts-ignore
+const getUserInfoById = async () => {
+  return reqest.get("/admin-api/system/auth/get-permission-info");
+};
+export const getUserInfoPromise = () => {
+  return new Promise(async (resolve, reject) => {
+    resolve(await initUserInfoHandler());
+  })
+}

+ 20 - 0
client_h5/src/router/index.ts

@@ -1,8 +1,11 @@
 import type {App} from 'vue';
 import type { RouteRecordRaw } from 'vue-router'
 import { createRouter, createWebHistory } from 'vue-router'
+import { showDialog, closeDialog } from 'vant'
 import routes from './routes'
 
+import { getUserInfoPromise } from './getUserInfo'
+
 const router = createRouter({
   history: createWebHistory('/html_h5'),
   strict: true,
@@ -10,6 +13,23 @@ const router = createRouter({
   scrollBehavior: () => ({ left: 0, top: 0 })
 })
 
+// 路由加载前
+router.beforeEach(async (to, from, next) => {
+  const isLogin = await getUserInfoPromise()
+  next(); 
+  if (!isLogin) {
+    showDialog({
+      message: '很抱歉,用户未登录,请先重新加载!',
+      confirmButtonText: '重新加载',
+      beforeClose: function(action) {
+        if (action === 'confirm') {
+          closeDialog()
+          window.location.reload()
+        }
+      },
+    })
+  }
+})
 const setupRouter = (app: App<Element>): void => {
   app.use(router)
 }

+ 7 - 0
client_h5/src/utils/common.ts

@@ -89,6 +89,13 @@ export const getStoreObject = (lKey: string, key?: string) => {
   return obj[key];
 }
 
+export const getStoreString = (lKey: string) => { 
+  if (!lKey) throw new Error('key不能为空!');
+  const result: string | null = localStorage.getItem(lKey);
+  if (!result) return null;
+  return result
+}
+
 export const setStoreObject = (lKey: string, data: any) => {
   if (!lKey) throw new Error('key不能为空!');
   if (!data) return;