From b3e1a4544c4d974ccfbcd74edc76a220199b28c5 Mon Sep 17 00:00:00 2001 From: Pierre Hubert Date: Tue, 13 Jun 2023 15:29:15 +0200 Subject: [PATCH] Handle invalid tokens --- geneit_app/src/api/ApiClient.ts | 7 +++++++ geneit_app/src/api/AuthApi.ts | 17 ++++++++++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/geneit_app/src/api/ApiClient.ts b/geneit_app/src/api/ApiClient.ts index 21637cf..4975624 100644 --- a/geneit_app/src/api/ApiClient.ts +++ b/geneit_app/src/api/ApiClient.ts @@ -44,6 +44,13 @@ export class APIClient { data = await res.json(); else data = await res.blob(); + // Handle expired tokens + if (res.status === 412) { + AuthApi.RemoveAuthToken(); + // eslint-disable-next-line no-self-assign + window.location.href = window.location.href; + } + if (!args.allowFail && !res.ok) throw new ApiError("Request failed!", res.status, data); diff --git a/geneit_app/src/api/AuthApi.ts b/geneit_app/src/api/AuthApi.ts index 39debf2..ce24e40 100644 --- a/geneit_app/src/api/AuthApi.ts +++ b/geneit_app/src/api/AuthApi.ts @@ -27,7 +27,7 @@ export class AuthApi { * Check out whether user is signed in or not */ static get SignedIn(): boolean { - return sessionStorage.getItem(TokenStateKey) !== null; + return localStorage.getItem(TokenStateKey) !== null; } static authStatus = atom(this.SignedIn); @@ -37,7 +37,7 @@ export class AuthApi { */ static get AuthToken(): string { if (!this.SignedIn) throw new Error("User is not authenticated!"); - return sessionStorage.getItem(TokenStateKey)!; + return localStorage.getItem(TokenStateKey)!; } /** @@ -99,7 +99,7 @@ export class AuthApi { return PasswordLoginResult.InvalidCredentials; case 200: case 201: - sessionStorage.setItem(TokenStateKey, res.data.token); + localStorage.setItem(TokenStateKey, res.data.token); return PasswordLoginResult.Success; default: return PasswordLoginResult.Error; @@ -133,7 +133,7 @@ export class AuthApi { }) ).data; - sessionStorage.setItem(TokenStateKey, res.token); + localStorage.setItem(TokenStateKey, res.token); } /** @@ -145,7 +145,14 @@ export class AuthApi { method: "GET", }); - sessionStorage.removeItem(TokenStateKey); + this.RemoveAuthToken(); + } + + /** + * Remove auth token from storage + */ + static RemoveAuthToken() { + localStorage.removeItem(TokenStateKey); } /**