2021-07-22 14:01:28 +00:00
|
|
|
|
|
|
|
//SETTING VARIABLES. GRABBING CONTENTS FROM FORM.
|
|
|
|
|
|
|
|
let uname = document.querySelector('#uname').value;
|
|
|
|
let pin = document.querySelector('#pin').value;
|
|
|
|
const form = document.querySelector('form');
|
2021-07-23 19:41:55 +00:00
|
|
|
let username = localStorage.getItem('username');
|
2021-07-22 14:01:28 +00:00
|
|
|
|
|
|
|
// SUBMIT FORM FUNCTION. AND FETCH USERNAME AND PIN FROM API.
|
|
|
|
|
|
|
|
form.addEventListener("submit", async function (event) {
|
|
|
|
event.preventDefault();
|
|
|
|
const formData = new FormData(form);
|
|
|
|
|
|
|
|
uname = formData.get('uname');
|
|
|
|
pin = formData.get('pin');
|
|
|
|
|
2021-07-23 19:41:55 +00:00
|
|
|
try {
|
|
|
|
const loginInfo = await loginFetch();
|
2021-07-22 14:01:28 +00:00
|
|
|
|
2021-07-23 19:41:55 +00:00
|
|
|
console.log(loginInfo)
|
|
|
|
|
|
|
|
if (loginInfo.status === 200) {
|
|
|
|
login()
|
|
|
|
} else {
|
|
|
|
incorrectLogin()
|
|
|
|
}
|
|
|
|
} catch(e) {
|
|
|
|
console.log(e);
|
|
|
|
document.querySelector("#errormessage").innerHTML = 'An Error has Occurred. Try again later. ' + e.toString();
|
2021-07-22 14:01:28 +00:00
|
|
|
}
|
2021-07-17 22:50:58 +00:00
|
|
|
})
|
|
|
|
|
2021-07-22 14:01:28 +00:00
|
|
|
|
2021-07-23 19:41:55 +00:00
|
|
|
// LOGIN FETCH
|
|
|
|
|
|
|
|
async function loginFetch() {
|
|
|
|
let sendLoginInfo = { "name": uname, "pin": pin }
|
|
|
|
return await fetch('/api/login/', {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
|
|
|
body: JSON.stringify(sendLoginInfo),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2021-07-22 14:01:28 +00:00
|
|
|
// FUNCTIONS FOR WHETHER THE LOGIN WAS A SUCCESS OR FAILURE
|
|
|
|
|
2021-07-17 22:50:58 +00:00
|
|
|
function login() {
|
2021-07-23 19:41:55 +00:00
|
|
|
window.location.replace("/index.html")
|
2021-07-22 14:01:28 +00:00
|
|
|
document.querySelector("#errormessage").innerHTML = ''
|
2021-07-23 19:41:55 +00:00
|
|
|
localStorage.setItem('username', `${uname}`);
|
|
|
|
|
|
|
|
if (username != '') {
|
|
|
|
document.querySelector("#username").innerHTML = `Logged in as ${username}`
|
|
|
|
}
|
2021-07-17 22:50:58 +00:00
|
|
|
}
|
2021-07-22 14:01:28 +00:00
|
|
|
|
2021-07-17 22:50:58 +00:00
|
|
|
function incorrectLogin() {
|
2021-07-22 14:01:28 +00:00
|
|
|
console.log('Incorrect Login!')
|
|
|
|
document.querySelector("#errormessage").innerHTML = 'Incorrect Login.'
|
2021-07-22 20:09:02 +00:00
|
|
|
}
|