LoongPanel-Asp/web/middleware/auth.ts

58 lines
1.6 KiB
TypeScript
Executable File

import type {HttpType} from "~/types/baseType";
import {defineNuxtRouteMiddleware} from "#app";
import {useToast} from 'vue-toastification'
interface RouteBackType extends HttpType<any> {
}
export default defineNuxtRouteMiddleware(async (to, from) => {
const toast = useToast();
const runtimeConfig = useRuntimeConfig();
const token = useCookie('token').value;
if (!token) {
toast.error('未登录', {timeout: 3000})
return navigateTo("/SignIn");
}
//如果导航到/
if (to.path === '/' && token) {
return navigateTo("/Home");
}
// 获取当前导航路径
const currentPath = to.path;
try {
const response = await $fetch('/Api/Rote/RoteVerify', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token
},
baseURL: runtimeConfig.public.baseUrl,
params: {'path': currentPath}
});
// 直接从响应中获取状态码
const data = response as HttpType<any>;
if (data.code !== 200) {
toast.error('未登录', {timeout: 3000})
if (data.code === 403) {
if (to.path === from.path) {
return navigateTo("/Home");
}
return navigateTo(from.path);
}
return navigateTo("/SignIn");
}
} catch (error) {
// 处理错误情况
console.error('请求验证路由时发生错误:', error);
toast.error('请求错误', {timeout: 3000})
return navigateTo("/SignIn");
}
return true;
});