Skip to content
This repository has been archived by the owner on Apr 6, 2024. It is now read-only.

ajout expiration sur JWT #39

Merged
merged 2 commits into from
Mar 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions src/services/ApiService.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand All @@ -45,6 +70,9 @@ class ApiService {
return false;
}

// Update token expiry
this.saveToken(token);

return true;
}

Expand Down
Loading