Skip to content

Commit

Permalink
fix: add last_refresh_time to track the validity of is_other_tab_refr…
Browse files Browse the repository at this point in the history
…eshing sign
  • Loading branch information
douxc committed Dec 31, 2024
1 parent fc29f20 commit 9c88cf7
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions web/service/refresh-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,23 @@ function waitUntilTokenRefreshed() {
})
}

const isRefreshingSignAvailable = function (delta: number) {
const nowTime = new Date().getTime()
const lastTime = globalThis.localStorage.getItem('last_refresh_time') || '0'
return nowTime - parseInt(lastTime) <= delta
}

// only one request can send
async function getNewAccessToken(): Promise<void> {
async function getNewAccessToken(timeout: number): Promise<void> {
try {
const isRefreshingSign = globalThis.localStorage.getItem(LOCAL_STORAGE_KEY)
if ((isRefreshingSign && isRefreshingSign === '1') || isRefreshing) {
if ((isRefreshingSign && isRefreshingSign === '1' && isRefreshingSignAvailable(timeout)) || isRefreshing) {
await waitUntilTokenRefreshed()
}
else {
isRefreshing = true
globalThis.localStorage.setItem(LOCAL_STORAGE_KEY, '1')
globalThis.localStorage.setItem('last_refresh_time', new Date().getTime().toString())
globalThis.addEventListener('beforeunload', releaseRefreshLock)
const refresh_token = globalThis.localStorage.getItem('refresh_token')

Expand Down Expand Up @@ -72,6 +79,7 @@ function releaseRefreshLock() {
if (isRefreshing) {
isRefreshing = false
globalThis.localStorage.removeItem(LOCAL_STORAGE_KEY)
globalThis.localStorage.removeItem('last_refresh_time')
globalThis.removeEventListener('beforeunload', releaseRefreshLock)
}
}
Expand All @@ -80,5 +88,5 @@ export async function refreshAccessTokenOrRelogin(timeout: number) {
return Promise.race([new Promise<void>((resolve, reject) => setTimeout(() => {
releaseRefreshLock()
reject(new Error('request timeout'))
}, timeout)), getNewAccessToken()])
}, timeout)), getNewAccessToken(timeout)])
}

0 comments on commit 9c88cf7

Please sign in to comment.