From 9d7d41764819a68e1071d5caeca7eedd94db56aa Mon Sep 17 00:00:00 2001 From: tmeftah Date: Sun, 25 Aug 2024 19:31:45 +0200 Subject: [PATCH] =?UTF-8?q?feat=20=E2=9C=A8:=20User=20authentication=20tok?= =?UTF-8?q?en=20clearing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Functionality for clearing the user's authentication token has been added. - The code implements a mechanism to handle unauthorized access attempts and redirect the user to the login page. --- frontend/src/stores/auth.js | 5 +++++ frontend/src/stores/main-store.js | 26 +++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/frontend/src/stores/auth.js b/frontend/src/stores/auth.js index 1149455..cd23523 100644 --- a/frontend/src/stores/auth.js +++ b/frontend/src/stores/auth.js @@ -17,6 +17,11 @@ export const useAuthStore = defineStore("auth", { }, actions: { + clearToken() { + this.token = null; + localStorage.removeItem("token"); // Remove token from storage + }, + async login(email, password) { const formData = new URLSearchParams(); formData.append("grant_type", "password"); diff --git a/frontend/src/stores/main-store.js b/frontend/src/stores/main-store.js index 5ccfc90..3a1f3da 100644 --- a/frontend/src/stores/main-store.js +++ b/frontend/src/stores/main-store.js @@ -29,6 +29,12 @@ export const useMainStore = defineStore("main", { }, }); + if (response.status === 401) { + authStore.clearToken(); + window.location.href = "/login"; // Or use Vue Router + return; + } + if (!response.ok) { // Extract error message if available const errorData = await response.json().catch(() => ({})); // Parsing might fail, default to empty object @@ -115,6 +121,14 @@ export const useMainStore = defineStore("main", { readChunk(reader, this.solution); }) .catch((error) => { + // + if (error.status === 401) { + authStore.clearToken(); + window.location.href = "/login"; // Or use Vue Router + return; + } + + // this.loading = false; console.error("Error fetching the data:", error); }); @@ -132,6 +146,12 @@ export const useMainStore = defineStore("main", { }, }); + if (response.status === 401) { + authStore.clearToken(); + window.location.href = "/login"; // Or use Vue Router + return; + } + if (!response.ok) { // Extract error message if available const errorData = await response.json().catch(() => ({})); // Parsing might fail, default to empty object @@ -180,7 +200,10 @@ export const useMainStore = defineStore("main", { url: `${baseUrl}/documents/upload`, method: "POST", headers: [ - { name: "Authorization", value: `Bearer ${authStore.token}` }, + { + name: "Authorization", + value: `Bearer ${authStore.token}`, + }, ], }); }, 2000); @@ -203,6 +226,7 @@ export const useMainStore = defineStore("main", { }, async upload_failed() { + // FIXME: chech if token is not valid anymore Notify.create({ color: "negative", position: "bottom",