diff --git a/src/background.js b/src/background.js index 8f1eeb5..b3d7d0e 100644 --- a/src/background.js +++ b/src/background.js @@ -12,7 +12,12 @@ class AccessToken { injectLoggedInStatus(!!AccessToken.TOKEN); } - static get() { + static async get() { + const token = AccessToken.TOKEN; + if (token) { + return token; + } + await AccessToken.refresh(); return AccessToken.TOKEN; } diff --git a/src/token-pool.js b/src/token-pool.js index 94e1a31..e3ab37e 100644 --- a/src/token-pool.js +++ b/src/token-pool.js @@ -201,7 +201,7 @@ class TokenPool { return; } - const accessToken = AccessToken.get(); + const accessToken = await AccessToken.get(); if (!accessToken) { return; } @@ -215,16 +215,17 @@ class TokenPool { pretokens.push({ token, blindFactor }); } - const response = await fetch(`${API_BASE_URL}/tokens/new`, { - method: 'POST', - headers: { - 'Authorization': `Bearer ${accessToken}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - blindTokens, - }), - }); + let response = await this._fetchNewTokens(accessToken, blindTokens); + if (response.status === 401) { + // try to refresh token and try again if authorization failed + // as the token technically could have expired by the time the request + // arives + const accessToken = await AccessToken.get(); + if (!accessToken) { + return; + } + response = await this._fetchNewTokens(accessToken, blindTokens); + } if (response.ok) { const { tokens } = await response.json(); const res = []; @@ -246,9 +247,19 @@ class TokenPool { })); console.warn(`Adding ${res.length} tokens to acquired pool`); this.tokens.push(...res); - } else if (response.status === 401) { - // refresh the access token. This will call generateTokens if the refresh is successful - AccessToken.refresh(); } } + + async _fetchNewTokens(accessToken, blindTokens) { + return fetch(`${API_BASE_URL}/tokens/new`, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${accessToken}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + blindTokens, + }), + }); + } }