Skip to content

Commit

Permalink
WIP: always try to async renew token also when refresh token expires
Browse files Browse the repository at this point in the history
  • Loading branch information
hupf committed Oct 29, 2024
1 parent 9f536cd commit 9582452
Showing 1 changed file with 7 additions and 41 deletions.
48 changes: 7 additions & 41 deletions src/utils/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,7 @@ import {
storeInstance,
storeLoginState,
} from "./storage";
import {
getTokenPayload,
isTokenAlmostExpired,
isTokenExpired,
isValidToken,
} from "./token";
import { isTokenAlmostExpired, isValidToken } from "./token";
import {
clearTokenRenewalTimers,
initializeTokenRenewal,
Expand Down Expand Up @@ -72,10 +67,8 @@ export async function initAuthentication(
locale: string,
): Promise<void> {
initializeTokenRenewal({
renewRefreshToken: (scope, locale) =>
renewRefreshToken(client, scope, locale),
renewAccessToken: (scope, locale) =>
renewAccessToken(client, scope, locale),
renewRefreshToken: (scope, locale) => renewToken(client, scope, locale),
renewAccessToken: (scope, locale) => renewToken(client, scope, locale),
});

const loginState = consumeLoginState();
Expand Down Expand Up @@ -315,32 +308,6 @@ function handleSubstitutionResult(token: OAuth2Token): void {
}
}

/**
* Redirect to login when refresh token expired.
*/
function renewRefreshToken(
client: OAuth2Client,
scope: string,
locale: string,
): Promise<void> {
log(
`Renewing refresh token for scope "${scope}" and locale "${locale}" by redirecting to login`,
);
return login(client, scope, locale);
}

/**
* Renew access token when it expired.
*/
function renewAccessToken(
client: OAuth2Client,
scope: string,
locale: string,
): Promise<void> {
log(`Renewing access token for scope "${scope}" and locale "${locale}"`);
return renewToken(client, scope, locale);
}

/**
* Asynchronously renew an access/refresh token pair (the old
* access/refresh token will be revoked due to token rotation, tokens
Expand All @@ -353,17 +320,16 @@ export async function renewToken(
): Promise<void> {
const instance = getInstance();
const refreshToken = getRefreshToken(scope);
if (
!instance ||
!refreshToken ||
isTokenExpired(getTokenPayload(refreshToken))
) {
if (!instance || !refreshToken) {
log(
`Refresh token for scope "${scope}" not present or expired, redirect to login`,
);
return login(client, scope, locale);
}

log(
`Renewing refresh & access token for scope "${scope}" and locale "${locale}"`,
);
try {
const { refreshToken: newRefreshToken, accessToken: newAccessToken } =
await postTokenRefresh(client, instance, scope, locale, refreshToken);
Expand Down

0 comments on commit 9582452

Please sign in to comment.