diff --git a/src/services/ApiService.tsx b/src/services/ApiService.tsx index 2bd33cf..f961fd6 100644 --- a/src/services/ApiService.tsx +++ b/src/services/ApiService.tsx @@ -6,9 +6,11 @@ import { FolderType } from '../Types/FolderType'; class ApiService { private BASE_URL: string; + private TTL: number; constructor() { this.BASE_URL = ENV_VARIABLES.VITE_BACKEND_URL; + this.TTL = 3600000; // 1h } private constructRequestUrl(endpoint: string): string { @@ -31,11 +33,34 @@ class ApiService { // Helpers private saveToken(token: string): void { - localStorage.setItem("jwt", token); + const now = new Date(); + + const object = { + token: token, + expiry: now.getTime()+this.TTL + } + + localStorage.setItem("jwt", JSON.stringify(object)); } private getToken(): string | null { - return localStorage.getItem("jwt"); + const objectStr = localStorage.getItem("jwt"); + + if (!objectStr) { + return null + } + + const object = JSON.parse(objectStr) + const now = new Date() + + if (now.getTime() > object.expiry) { + // If the item is expired, delete the item from storage + // and return null + this.logout(); + return null + } + + return object.token; } public isLogedIn(): boolean { @@ -45,6 +70,9 @@ class ApiService { return false; } + // Update token expiry + this.saveToken(token); + return true; }