31 lines
1.1 KiB
TypeScript
31 lines
1.1 KiB
TypeScript
/**
|
||
* 登录态过期后的自愈:先拿 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
|
||
}
|