You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.4 KiB
52 lines
1.4 KiB
<template>
|
|
<!-- 未登录 → 登录页 -->
|
|
<LoginPage v-if="!auth.loggedIn" @login-success="onLoginSuccess" />
|
|
<!-- 已登录 → 管理后台 -->
|
|
<MainLayout v-else />
|
|
</template>
|
|
|
|
<script setup lang="ts">
|
|
import { onMounted, onUnmounted } from 'vue'
|
|
import { useAuthStore } from '@/stores/auth'
|
|
import LoginPage from '@/views/LoginPage.vue'
|
|
import MainLayout from '@/layouts/MainLayout.vue'
|
|
import { isLoggedIn, cleanupLegacyTokens } from '@/utils/token'
|
|
import { toast } from '@/utils/toast'
|
|
|
|
const auth = useAuthStore()
|
|
|
|
function onLoginSuccess(user: any) {
|
|
auth.onLoginSuccess(user)
|
|
}
|
|
|
|
// 401 全局事件处理器:拦截器已尝试刷新并失败后触发,这里直接登出
|
|
async function handleUnauthorized() {
|
|
await auth.doLogout()
|
|
toast('登录已过期,请重新登录', 'error')
|
|
}
|
|
|
|
onMounted(async () => {
|
|
// 启动时清理历史遗留的 refresh token
|
|
cleanupLegacyTokens()
|
|
|
|
// 启动时验证登录态
|
|
if (isLoggedIn()) {
|
|
const ok = await auth.fetchUser()
|
|
if (!ok) {
|
|
// 尝试刷新 Token
|
|
const refreshed = await auth.tryRefreshToken()
|
|
if (refreshed) {
|
|
await auth.fetchUser().catch(() => {})
|
|
} else {
|
|
await auth.doLogout()
|
|
}
|
|
}
|
|
}
|
|
|
|
window.addEventListener('auth:unauthorized', handleUnauthorized)
|
|
})
|
|
|
|
onUnmounted(() => {
|
|
window.removeEventListener('auth:unauthorized', handleUnauthorized)
|
|
})
|
|
</script>
|