fix: auth check redirect

This commit is contained in:
engigu
2025-12-24 22:39:13 +08:00
parent a8aeb57c39
commit 6107b056f1
3 changed files with 26 additions and 1 deletions
+2
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { RouterLink, RouterView, useRoute } from 'vue-router'
import { resetAuthCache } from '@/router'
import { LayoutDashboard, ListTodo, FileCode, Settings, LogOut, ScrollText, Terminal, Variable, KeyRound, Package, Menu, X } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import ThemeToggle from '@/components/ThemeToggle.vue'
@@ -42,6 +43,7 @@ async function logout() {
} catch {
// 忽略错误
}
resetAuthCache()
window.location.href = '/login'
}
+22 -1
View File
@@ -1,6 +1,25 @@
import { createRouter, createWebHistory } from 'vue-router'
import { checkAuth } from '@/api'
// 缓存认证状态,避免每次路由跳转都请求
let authChecked = false
let isAuth = false
async function getAuthStatus(force = false): Promise<boolean> {
if (!force && authChecked) {
return isAuth
}
isAuth = await checkAuth()
authChecked = true
return isAuth
}
// 重置认证状态(登录/登出时调用)
export function resetAuthCache() {
authChecked = false
isAuth = false
}
const router = createRouter({
history: createWebHistory(),
routes: [
@@ -31,7 +50,9 @@ const router = createRouter({
// 路由守卫
router.beforeEach(async (to, _from, next) => {
const isAuthenticated = await checkAuth()
// 首次访问或访问登录页时强制检查
const forceCheck = !authChecked || to.path === '/login'
const isAuthenticated = await getAuthStatus(forceCheck)
// 检查是否需要认证
if (to.matched.some(record => record.meta.requiresAuth)) {
+2
View File
@@ -7,6 +7,7 @@ import { Label } from '@/components/ui/label'
import ThemeToggle from '@/components/ThemeToggle.vue'
import { api } from '@/api'
import { toast } from 'vue-sonner'
import { resetAuthCache } from '@/router'
const router = useRouter()
const username = ref('')
@@ -46,6 +47,7 @@ async function handleLogin() {
loading.value = true
try {
await api.auth.login({ username: username.value, password: password.value })
resetAuthCache() // 重置认证缓存
toast.success('登录成功')
router.push('/')
} catch {