From 1377d6334766304b0536a5fe6a11ba55b9013cab Mon Sep 17 00:00:00 2001 From: gourav Date: Sat, 15 Jun 2024 00:12:02 +0530 Subject: [PATCH] validate token on refresh Also added validatedtoken API --- frontend/src/App.vue | 53 ++++++++++++++++++++++++++++++++++++++++++-- main.py | 12 +++++++++- 2 files changed, 62 insertions(+), 3 deletions(-) diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 3fc761b..2077b27 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -28,7 +28,14 @@ import ListSecrets from "./components/ListSecrets.vue";
- + Show secrets Hide secrets @@ -46,11 +53,12 @@ export default { showSecrets: false, creationDialog: false, listUpdated: 1, + apiBaseUrl: "http://localhost:8000", }; }, methods: { logout() { - localStorage.removeItem("token"); + sessionStorage.removeItem("token"); this.loggedin = false; }, @@ -60,6 +68,47 @@ export default { this.listUpdated += 1; console.log("after update", this.listUpdated); }, + + async validateToken() { + const url = `${this.apiBaseUrl}/validate-token`; + const token = sessionStorage.getItem("token"); + const requestOptions = { + method: "GET", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + }, + }; + + const response = await fetch(url, requestOptions) + .then((response) => response.json()) + .catch((err) => { + console.log(err); + return false; + }); + + if (!response) { + return false; + } + if ("message" in response) { + if (response["message"] === "authenticated") { + console.log("token validated"); + return true; + } + } + return false; + }, + }, + + async mounted() { + if ("token" in sessionStorage) { + const tokenValid = await this.validateToken(); + + if (tokenValid) { + this.loggedin = true; + this.showSecrets = true; + } + } }, }; diff --git a/main.py b/main.py index 093b13f..9ed8413 100644 --- a/main.py +++ b/main.py @@ -167,4 +167,14 @@ async def list_secret(current_user: dict = Depends(get_current_user)): decrypted_data = fernet_decrypt(cur_data, encryption_key) secret['data'] = decrypted_data - return user_secrets \ No newline at end of file + return user_secrets + + +@app.get('/validate-token') +async def validate_token(current_user: dict = Depends(get_current_user)): + user_id = current_user['id'] + print("user_id: ", user_id) + if user_id is not None: + return {'message': 'authenticated'} + + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) \ No newline at end of file