refresh-token.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { apiPrefix } from '@/config'
  2. import { fetchWithRetry } from '@/utils'
  3. const LOCAL_STORAGE_KEY = 'is_other_tab_refreshing'
  4. let isRefreshing = false
  5. function waitUntilTokenRefreshed() {
  6. return new Promise<void>((resolve, reject) => {
  7. function _check() {
  8. const isRefreshingSign = globalThis.localStorage.getItem(LOCAL_STORAGE_KEY)
  9. if ((isRefreshingSign && isRefreshingSign === '1') || isRefreshing) {
  10. setTimeout(() => {
  11. _check()
  12. }, 1000)
  13. }
  14. else {
  15. resolve()
  16. }
  17. }
  18. _check()
  19. })
  20. }
  21. // only one request can send
  22. async function getNewAccessToken(): Promise<void> {
  23. try {
  24. const isRefreshingSign = globalThis.localStorage.getItem(LOCAL_STORAGE_KEY)
  25. if ((isRefreshingSign && isRefreshingSign === '1') || isRefreshing) {
  26. await waitUntilTokenRefreshed()
  27. }
  28. else {
  29. isRefreshing = true
  30. globalThis.localStorage.setItem(LOCAL_STORAGE_KEY, '1')
  31. globalThis.addEventListener('beforeunload', releaseRefreshLock)
  32. const refresh_token = globalThis.localStorage.getItem('refresh_token')
  33. // Do not use baseFetch to refresh tokens.
  34. // If a 401 response occurs and baseFetch itself attempts to refresh the token,
  35. // it can lead to an infinite loop if the refresh attempt also returns 401.
  36. // To avoid this, handle token refresh separately in a dedicated function
  37. // that does not call baseFetch and uses a single retry mechanism.
  38. const [error, ret] = await fetchWithRetry(globalThis.fetch(`${apiPrefix}/refresh-token`, {
  39. method: 'POST',
  40. headers: {
  41. 'Content-Type': 'application/json;utf-8',
  42. },
  43. body: JSON.stringify({ refresh_token }),
  44. }))
  45. if (error) {
  46. return Promise.reject(error)
  47. }
  48. else {
  49. if (ret.status === 401)
  50. return Promise.reject(ret)
  51. const { data } = await ret.json()
  52. globalThis.localStorage.setItem('console_token', data.access_token)
  53. globalThis.localStorage.setItem('refresh_token', data.refresh_token)
  54. }
  55. }
  56. }
  57. catch (error) {
  58. console.error(error)
  59. return Promise.reject(error)
  60. }
  61. finally {
  62. releaseRefreshLock()
  63. }
  64. }
  65. function releaseRefreshLock() {
  66. if (isRefreshing) {
  67. isRefreshing = false
  68. globalThis.localStorage.removeItem(LOCAL_STORAGE_KEY)
  69. globalThis.removeEventListener('beforeunload', releaseRefreshLock)
  70. }
  71. }
  72. export async function refreshAccessTokenOrRelogin(timeout: number) {
  73. return Promise.race([new Promise<void>((resolve, reject) => setTimeout(() => {
  74. releaseRefreshLock()
  75. reject(new Error('request timeout'))
  76. }, timeout)), getNewAccessToken()])
  77. }