Skip to content

Commit

Permalink
♻️ Unsplit refreshToken function
Browse files Browse the repository at this point in the history
  • Loading branch information
JulienPavon committed Feb 20, 2025
1 parent 1e71285 commit 6c0eb6d
Showing 1 changed file with 8 additions and 15 deletions.
23 changes: 8 additions & 15 deletions packages/applications/request-context/src/refreshToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,20 @@ export async function refreshToken(token: JWT): Promise<JWT> {
}

try {
const { expiresAt, refreshToken } = await refreshAccessToken(token.refreshToken, provider);
const { refreshToken } = token;
const client = await getOpenIdClient(provider);
const refreshedTokens = await client.refresh(refreshToken);
if (!refreshedTokens.access_token || !refreshedTokens.expires_in) {
throw new RefreshTokenError();
}

const expiresAt = Date.now() + refreshedTokens.expires_in * 1000;
logger.debug(`Token refreshed`, { sub, expiresAt: new Date(expiresAt) });

return {
...token,
expiresAt,
refreshToken,
refreshToken: refreshedTokens.refresh_token ?? refreshToken,
};
} catch (e) {
const err = e as { error?: string; error_description?: string };
Expand All @@ -47,19 +53,6 @@ function isTokenUpToDate(expiresAt: number) {
return expiresAt > Date.now();
}

async function refreshAccessToken(refreshToken: string, provider: string) {
const client = await getOpenIdClient(provider);
const refreshedTokens = await client.refresh(refreshToken);
if (!refreshedTokens.access_token || !refreshedTokens.expires_in) {
throw new RefreshTokenError();
}
return {
accessToken: refreshedTokens.access_token,
expiresAt: Date.now() + refreshedTokens.expires_in * 1000,
refreshToken: refreshedTokens.refresh_token ?? refreshToken,
};
}

class RefreshTokenError extends InvalidOperationError {
constructor() {
super('Refreshing the token failed');
Expand Down

0 comments on commit 6c0eb6d

Please sign in to comment.