This commit is contained in:
2025-06-02 21:06:39 +08:00
parent 7d77a11dee
commit 86c7e52551
9 changed files with 380 additions and 228 deletions

View File

@@ -1,4 +1,6 @@
import { createRouter, createWebHistory } from 'vue-router'
import { hasValidToken, getUserInfo, logoutUser } from '../utils/jwt';
import { justLoggedIn } from '../utils/authSessionState';
const routes = [
{
@@ -97,21 +99,43 @@ const router = createRouter({
})
// 路由守卫
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('access_token')
router.beforeEach(async (to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!token) {
if (requiresAuth) {
const tokenExists = hasValidToken();
if (justLoggedIn.value) {
justLoggedIn.value = false;
if (tokenExists) {
next();
} else {
logoutUser();
next({ path: '/backend/login', query: { redirect: to.fullPath, sessionExpired: 'true' }});
}
return;
}
if (tokenExists) {
const user = await getUserInfo();
if (user) {
next();
} else {
logoutUser();
next({
path: '/backend/login',
query: { redirect: to.fullPath, sessionExpired: 'true' }
});
}
} else {
next({
path: '/backend/login',
query: { redirect: to.fullPath }
})
} else {
next()
});
}
} else {
next()
next();
}
})
});
export default router