Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Refresh access_token if expired #24

Merged
merged 9 commits into from Nov 5, 2020

move refresh to cookieListener

  • Loading branch information
fcjr committed Nov 5, 2020
commit bffc2e5b1633e37fe5b1b52fcb7bd56ebdab9381
@@ -11,12 +11,7 @@ class AccessToken {
tokenPool.generateTokens();
}

static async get() {
const token = AccessToken.TOKEN;
if (token) {
return token;
}
await AccessToken.refresh();
static get() {
return AccessToken.TOKEN;
This conversation was marked as resolved by fcjr

This comment has been minimized.

@sammacbeth

sammacbeth Nov 5, 2020
Contributor

I'm not sure this will return the new token after a refresh. AccessToken.refresh will resolve after the fetch to the refresh token endpoint has completed, but AccessToken.TOKEN is updated after the cookie updated event.

}

@@ -55,6 +50,9 @@ const cookieListener = (changeInfo) => {

if (removed) {
AccessToken.destroy();
// try to refresh the token incase remove was caused by
// token expiring
AccessToken.refresh();
return;
}

@@ -69,6 +67,10 @@ const lookForAccessToken = async () => {
});
if (cookie) {
AccessToken.set(cookie.value);
} else {
// if token is not found on startup try to refresh
// as it can just be expired
AccessToken.refresh();
};
}

@@ -39,7 +39,7 @@ class TokenPool {
}

async generateTokens() {
const accessToken = await AccessToken.get();
const accessToken = AccessToken.get();
if (!accessToken) {
return;
}
@@ -53,17 +53,17 @@ class TokenPool {
pretokens.push({ token, blindFactor });
}

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);
}
const response = await fetch(`${API_BASE_URL}/tokens/new`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
blindTokens,
}),
});

if (response.ok) {
const { tokens } = await response.json();
const res = [];
@@ -86,17 +86,4 @@ class TokenPool {
this.tokens.push(...res);
}
}

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,
}),
});
}
}
ProTip! Use n and p to navigate between commits in a pull request.