From a1e6ffd7fc1b0e4ca614e55812d086dfdf08a197 Mon Sep 17 00:00:00 2001 From: Sergio Rodriguez Seoane Date: Tue, 1 Jul 2025 16:07:51 +0200 Subject: [PATCH] Refresh token on expired --- src/api/yepcodeApi.ts | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/api/yepcodeApi.ts b/src/api/yepcodeApi.ts index 8288743..53da24f 100644 --- a/src/api/yepcodeApi.ts +++ b/src/api/yepcodeApi.ts @@ -164,6 +164,12 @@ export class YepCodeApi { } private async getAccessToken(): Promise { + if (!this.clientId || !this.clientSecret) { + throw new Error( + "AccessToken has expired. Provide a new one or enable automatic refreshing by providing an apiToken or clientId and clientSecret." + ); + } + try { const response = await fetch(this.authUrl, { method: "POST", @@ -190,6 +196,19 @@ export class YepCodeApi { } } + private isAccessTokenExpired(accessToken: string): boolean { + const tokenPayload = accessToken.split(".")[1]; + if (!tokenPayload) { + return true; + } + + const decodedPayload = JSON.parse( + Buffer.from(tokenPayload, "base64").toString() + ); + + return decodedPayload.exp < Date.now() / 1000; + } + private sanitizeDateParam(date?: Date | string): string | undefined { if (!date) { return undefined; @@ -213,7 +232,7 @@ export class YepCodeApi { endpoint: string, options: RequestOptions = {} ): Promise { - if (!this.accessToken) { + if (!this.accessToken || this.isAccessTokenExpired(this.accessToken)) { await this.getAccessToken(); }