unis-oa/frontend/src/utils/sessionRecovery.ts

31 lines
1.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* 登录态过期后的自愈:先拿 refresh_token 静默换一张新的访问令牌,换到了就把原请求
* 重发一次;换不到才清掉本地会话,并把用户送回登录页(登录成功后回到原来那一页)。
*
* 缺这段逻辑时,标签页挂过 access_token_minutes(默认 12 小时)只会停在一张空列表上:
* 路由守卫只看本地有没有令牌,401 又只清了 store,于是页面既不报错也不跳登录,
* 看起来像数据丢了。
*/
import type { Router } from 'vue-router'
import { onUnauthorized, type SessionRecovery } from '@/api/client'
import type { useAuthStore } from '@/stores/auth'
export function bindSessionRecovery(
auth: ReturnType<typeof useAuthStore>,
router: Router
): SessionRecovery {
const recover: SessionRecovery = async () => {
if (await auth.refreshSession()) return true
const current = router.currentRoute.value
if (current.name !== 'login') {
await router.replace({
name: 'login',
query: current.fullPath === '/' ? {} : { redirect: current.fullPath }
})
}
return false
}
onUnauthorized(recover)
return recover
}