Przeglądaj źródła

自动登录实现

dengrui 2 miesięcy temu
rodzic
commit
01c8b484c2

+ 1 - 1
.env.development

@@ -11,6 +11,6 @@ VITE_APP_BASE_API = '/dev-api'
 VITE_APP_UPLOAD_URL = 'http://192.168.101.4:9000'
 # 开发接口地址
 #VITE_APP_API_URL = 'http://192.168.101.4:8078'
-VITE_APP_API_URL = 'http://127.0.0.1:8058'
+VITE_APP_API_URL = 'http://192.168.1.4:8058'
 # 是否启用 Mock 服务
 VITE_MOCK_DEV_SERVER = false

+ 6 - 0
src/layout/components/Sidebar/components/SidebarMixTopMenu.vue

@@ -50,6 +50,7 @@ const mixTopMenus = ref<RouteRecordRaw[]>([]);
  * 菜单选择事件
  */
 const handleMenuSelect = (routePath: string) => {
+  console.log("handleMenuSelect", routePath);
   appStore.activeTopMenu(routePath);
   permissionStore.setMixLeftMenus(routePath);
   // 获取左侧菜单集合,默认跳转到第一个菜单
@@ -83,5 +84,10 @@ onMounted(() => {
     appStore.activeTopMenu("");
     permissionStore.mixLeftMenus = [];
   }
+  let routePath = "/" + route.fullPath.split("/")[1];
+  if (routePath == "/deviceList") {
+    routePath = "/device";
+  }
+  handleMenuSelect(routePath);
 });
 </script>

+ 1 - 1
src/main.ts

@@ -30,7 +30,7 @@ setupElIcons(app);
 // 国际化
 setupI18n(app);
 // 注册动态路由
-setupPermission();
+setupPermission("/deviceList");
 
 setupEleAvue(app);
 

+ 67 - 53
src/plugins/permission.ts

@@ -5,74 +5,88 @@ import { useDictionaryStore } from "@/store/modules/dictionary";
 
 import NProgress from "@/utils/nprogress";
 import { getUserDicts } from "@/api/auth";
+import { ElStep } from "element-plus";
 
-export function setupPermission() {
+export function setupPermission(path: string) {
   // 白名单路由
   const whiteList = [""];
 
   router.beforeEach(async (to, from, next) => {
     NProgress.start();
     const hasToken = localStorage.getItem("token");
-    if (hasToken) {
-      if (to.path === "/login") {
-        // 如果已登录,跳转首页
-        next({ path: "/" });
-        NProgress.done();
-      } else {
-        const dictStore = useDictionaryStore();
-        if (
-          !dictStore.dicts.value ||
-          JSON.stringify(dictStore.dicts.value) === "{}"
-        ) {
-          const res = await getUserDicts(dictStore.types);
-          if (res.data) {
-            dictStore.dicts = res?.data;
-          }
-        }
 
-        const userStore = useUserStore();
-        // const hasRoles =
-        //   userStore.user.roles && userStore.user.roles.length > 0;
-        if (userStore.isGetAuth) {
-          // 未匹配到任何路由,跳转404
-          if (to.matched.length === 0) {
-            from.name ? next({ name: from.name }) : next("/404");
+    const dictStore = useDictionaryStore();
+    if (
+      !dictStore.dicts.value ||
+      JSON.stringify(dictStore.dicts.value) === "{}"
+    ) {
+      const res = await getUserDicts(dictStore.types);
+      if (res.data) {
+        dictStore.dicts = res?.data;
+      }
+    }
+    const userStore = useUserStore();
+    if (!hasToken) {
+      //自动登录
+      await userStore
+        .login({
+          userName: "admin",
+          password: "123456",
+          orgId: 1,
+        })
+        .then(async () => {
+          if (userStore.isGetAuth) {
+            // 未匹配到任何路由,跳转404
+            if (to.matched.length === 0) {
+              from.name ? next({ name: from.name }) : next("/404");
+            } else {
+              next();
+            }
           } else {
-            next();
-          }
-        } else {
-          const permissionStore = usePermissionStore();
-          try {
-            const { menus } = await userStore.getUserInfo();
+            const permissionStore = usePermissionStore();
+            try {
+              const { menus } = await userStore.getUserInfo();
+              const accessRoutes = await permissionStore.generateRoutes(menus);
+              accessRoutes.forEach((route) => {
+                router.addRoute(route);
+              });
+              console.log(router, path);
 
-            const accessRoutes = await permissionStore.generateRoutes(menus);
+              next({ path: path });
+            } catch (error) {
+              console.error("beforeEach error", error);
+              // 移除 token 并跳转登录页
+              await userStore.resetToken();
 
-            accessRoutes.forEach((route) => {
-              router.addRoute(route);
-            });
-            next({ ...to, replace: true });
-          } catch (error) {
-            console.error("beforeEach error", error);
-            // 移除 token 并跳转登录页
-            await userStore.resetToken();
-            next(`/login?redirect=${to.path}`);
-            NProgress.done();
+              NProgress.done();
+            }
           }
-        }
-      }
+        });
     } else {
-      // 未登录可以访问白名单页面
-      if (whiteList.indexOf(to.path) !== -1) {
-        // const dictStore = useDictionaryStore();
-        // dictStore.checkDicts();
-        next();
-      } else {
-        if (to.path === "/login") {
-          next();
+      if (userStore.isGetAuth) {
+        // 未匹配到任何路由,跳转404
+        if (to.matched.length === 0) {
+          from.name ? next({ name: from.name }) : next("/404");
         } else {
-          next(`/login`);
+          next();
+        }
+      } else {
+        const permissionStore = usePermissionStore();
+        try {
+          const { menus } = await userStore.getUserInfo();
+
+          const accessRoutes = await permissionStore.generateRoutes(menus);
+
+          accessRoutes.forEach((route) => {
+            router.addRoute(route);
+          });
+          next({ path: path });
+        } catch (error) {
+          console.error("beforeEach error", error);
+          // 移除 token 并跳转登录页
+          await userStore.resetToken();
+          NProgress.done();
         }
-        NProgress.done();
       }
     }
   });

+ 1 - 1
src/store/modules/user.ts

@@ -12,7 +12,7 @@ export const useUserStore = defineStore("user", () => {
     perms: [],
   });
 
-  const isGetAuth = ref(false); //是否已经请求过auth接口活的role和menus了
+  const isGetAuth = ref(false); //是否已经请求过auth接口获得role和menus了
 
   /**
    * 登录

+ 2 - 0
src/views/login/index.vue

@@ -122,6 +122,7 @@ import router from "@/router";
 import defaultSettings from "@/settings";
 import { ThemeEnum } from "@/enums/ThemeEnum";
 import { usePermissionStore } from "@/store/modules/permission";
+import { log } from "console";
 // Stores
 const userStore = useUserStore();
 const settingsStore = useSettingsStore();
@@ -215,6 +216,7 @@ const toLogin = () => {
   localStorage.setItem("local_pwd", loginData.value.password);
 
   loading.value = true;
+  console.log(loginData.value);
   userStore
     .login(loginData.value)
     .then(async () => {