validate token on refresh

Also added validatedtoken API
This commit is contained in:
Gourav Kumar 2024-06-15 00:12:02 +05:30
parent 956faf2e3c
commit 1377d63347
2 changed files with 62 additions and 3 deletions

View File

@ -28,7 +28,14 @@ import ListSecrets from "./components/ListSecrets.vue";
</el-dialog> </el-dialog>
<div class="container"> <div class="container">
<HomePage msg="You did it!" @loggedin="loggedin = true" v-if="!loggedin" /> <HomePage
msg="You did it!"
@loggedin="
loggedin = true;
showSecrets = true;
"
v-if="!loggedin"
/>
<el-button @click="showSecrets = true" v-if="loggedin"> Show secrets </el-button> <el-button @click="showSecrets = true" v-if="loggedin"> Show secrets </el-button>
<el-button @click="showSecrets = false" v-if="showSecrets && loggedin"> <el-button @click="showSecrets = false" v-if="showSecrets && loggedin">
Hide secrets Hide secrets
@ -46,11 +53,12 @@ export default {
showSecrets: false, showSecrets: false,
creationDialog: false, creationDialog: false,
listUpdated: 1, listUpdated: 1,
apiBaseUrl: "http://localhost:8000",
}; };
}, },
methods: { methods: {
logout() { logout() {
localStorage.removeItem("token"); sessionStorage.removeItem("token");
this.loggedin = false; this.loggedin = false;
}, },
@ -60,6 +68,47 @@ export default {
this.listUpdated += 1; this.listUpdated += 1;
console.log("after update", this.listUpdated); 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;
}
}
}, },
}; };
</script> </script>

12
main.py
View File

@ -167,4 +167,14 @@ async def list_secret(current_user: dict = Depends(get_current_user)):
decrypted_data = fernet_decrypt(cur_data, encryption_key) decrypted_data = fernet_decrypt(cur_data, encryption_key)
secret['data'] = decrypted_data secret['data'] = decrypted_data
return user_secrets 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)