From 628311e960c0cdebbf3ae5ed3f9799fad554fa66 Mon Sep 17 00:00:00 2001 From: Michal Miszczyszyn Date: Sat, 21 Oct 2023 16:44:01 +0200 Subject: [PATCH] Make token grace period configurable --- src/SaleorAuthClient.ts | 15 ++++++++++++--- src/utils.ts | 7 ++----- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/SaleorAuthClient.ts b/src/SaleorAuthClient.ts index 8eb5ca8..64e7dd6 100644 --- a/src/SaleorAuthClient.ts +++ b/src/SaleorAuthClient.ts @@ -17,9 +17,14 @@ export interface SaleorAuthClientProps { onAuthRefresh?: (isAuthenticating: boolean) => void; saleorApiUrl: string; storage?: Storage; + tokenGracePeriod?: number; } export class SaleorAuthClient { + // we'll assume a generous time of 2 seconds for api to + // process our request + private tokenGracePeriod = 2000; + private accessToken: string | null = null; private tokenRefreshPromise: null | Promise = null; private onAuthRefresh?: (isAuthenticating: boolean) => void; @@ -37,7 +42,11 @@ export class SaleorAuthClient { * ``` */ - constructor({ saleorApiUrl, storage, onAuthRefresh }: SaleorAuthClientProps) { + constructor({ saleorApiUrl, storage, onAuthRefresh, tokenGracePeriod }: SaleorAuthClientProps) { + if (tokenGracePeriod) { + this.tokenGracePeriod = tokenGracePeriod; + } + const internalStorage = storage || (typeof window !== "undefined" ? window.localStorage : undefined); this.storageHandler = internalStorage ? new SaleorAuthStorageHandler(internalStorage, saleorApiUrl) @@ -104,7 +113,7 @@ export class SaleorAuthClient { invariant(refreshToken, "Missing refresh token in token refresh handler"); // the refresh already finished, proceed as normal - if (this.accessToken && !isExpiredToken(this.accessToken)) { + if (this.accessToken && !isExpiredToken(this.accessToken, this.tokenGracePeriod)) { return this.fetchWithAuth(input, init, additionalParams); } @@ -186,7 +195,7 @@ export class SaleorAuthClient { } // access token is fine, add it to the request and proceed - if (this.accessToken && !isExpiredToken(this.accessToken)) { + if (this.accessToken && !isExpiredToken(this.accessToken, this.tokenGracePeriod)) { return this.runAuthorizedRequest(input, init, additionalParams); } diff --git a/src/utils.ts b/src/utils.ts index 608a3ef..dd504d4 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,7 +1,6 @@ import { TypedDocumentString } from "./graphql"; const MILLI_MULTIPLYER = 1000; -const TOKEN_GRACE_PERIOD = 2000; interface TokenData { iat: number; @@ -34,10 +33,8 @@ export const getTokenIss = (token: string): string => { return parsedTokenData.iss; }; -export const isExpiredToken = (token: string) => { - // we'll assume a generous time of 2 seconds for api to - // process our request - return getTokenExpiry(token) - TOKEN_GRACE_PERIOD <= Date.now(); +export const isExpiredToken = (token: string, tokenGracePeriod: number) => { + return getTokenExpiry(token) - tokenGracePeriod <= Date.now(); }; // query here is document node but because of graphql-tag using