000a137a3d
authLoader 中 initFromStorage() 后需重新调用 getState() 获取最新状态, 否则 isAuthenticated 检查使用过时的快照值导致已登录用户被重定向到登录页。 同步修复 usePermissionStore 的相同问题。
41 lines
918 B
TypeScript
41 lines
918 B
TypeScript
import { redirect } from 'react-router'
|
|
import { useAuthStore } from '@/stores/useAuthStore'
|
|
import { usePermissionStore } from '@/stores/usePermissionStore'
|
|
|
|
export async function authLoader() {
|
|
const token = localStorage.getItem('token')
|
|
|
|
if (!token) {
|
|
return redirect('/login')
|
|
}
|
|
|
|
let authState = useAuthStore.getState()
|
|
|
|
if (!authState.initialized) {
|
|
authState.initFromStorage()
|
|
authState = useAuthStore.getState()
|
|
}
|
|
|
|
if (!authState.isAuthenticated) {
|
|
return redirect('/login')
|
|
}
|
|
|
|
let permState = usePermissionStore.getState()
|
|
|
|
if (!permState.loaded) {
|
|
const restored = permState.initFromStorage()
|
|
if (!restored) {
|
|
try {
|
|
await permState.fetchUserMenus()
|
|
} catch {
|
|
authState = useAuthStore.getState()
|
|
authState.logout()
|
|
return redirect('/login')
|
|
}
|
|
}
|
|
permState = usePermissionStore.getState()
|
|
}
|
|
|
|
return null
|
|
}
|