lilachat-frontend/logout.js

49 lines
1.2 KiB
JavaScript
Raw Normal View History

2021-07-23 14:30:24 +00:00
//VARIBLES
2021-07-24 18:27:09 +00:00
myStorage = window.localStorage;
// //IF NOT LOGGED IN DON'T SHOW LOGOUT BUTTON
while (username === null) {
document.getElementById("logoutbutton").style.display = "none";
}
2021-07-23 14:30:24 +00:00
//LOGOUT FETCH FUNCTION
async function logout() {
2021-07-24 14:10:41 +00:00
let sendLogoutInfo = { "name": username }
fetch('/api/logout/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
2021-07-23 14:30:24 +00:00
},
2021-07-24 14:10:41 +00:00
body: JSON.stringify(sendLogoutInfo),
});
document.querySelector("#errormessage").innerHTML = 'Logged out.'
localStorage.removeItem('username')
username = null;
loggedIn()
2021-07-23 19:41:55 +00:00
}
2021-07-24 18:27:09 +00:00
//CHECKS TO SEE IF USERNAME MATCHES TOKEN
let tokenUpdate = window.setInterval(checkToken, 1000);
async function checkToken() {
const response = await fetch(`api/token/${username}/`);
const matches = await response.json();
//YES THIS IS CONFUSING I KNOW.
if (matches.status === "fail") {
loggedOut()
}
// IF NO USERNAME BUT HAS A TOKEN THEN LOGOUT
if (matches.status === "ok" && myStorage.length === 0) {
logout()
}
}
//AND IF THEY DON'T HAVE A TOKEN CLEARS THE LOCAL STORED USERNAME
function loggedOut() {
localStorage.removeItem('username')
document.querySelector("#loggeduser").innerHTML = 'You are not logged in'
}