Skip to content

Commit

Permalink
fix: store latest valid id token on client
Browse files Browse the repository at this point in the history
  • Loading branch information
awinogrodzki committed Jun 15, 2024
1 parent 580bb2a commit 5764a33
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/next/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,27 @@ export interface GetValidIdTokenOptions {
checkRevoked?: boolean;
}

let serverIdTokenCacheMap: Record<string, string> = {};

function getLatestIdToken(serverIdToken: string) {
if (!serverIdTokenCacheMap[serverIdToken]) {
return serverIdToken;
}

return serverIdTokenCacheMap[serverIdToken];
}

function saveLatestIdToken(serverIdToken: string, idToken: string) {
serverIdTokenCacheMap = {[serverIdToken]: idToken};
}

export async function getValidIdToken({
serverIdToken,
refreshTokenUrl,
checkRevoked
}: GetValidIdTokenOptions): Promise<string | null> {
const payload = decodeJwt(serverIdToken);
const token = getLatestIdToken(serverIdToken);
const payload = decodeJwt(token);
const exp = payload?.exp ?? 0;

if (!checkRevoked && exp > Date.now() / 1000) {
Expand All @@ -28,6 +43,8 @@ export async function getValidIdToken({
);
}

saveLatestIdToken(serverIdToken, response.idToken);

return response.idToken;
}

Expand Down

0 comments on commit 5764a33

Please sign in to comment.