From e1f06dbb2b743d13750ed87db8363fb2007a3b6c Mon Sep 17 00:00:00 2001 From: Preston Doman Date: Wed, 16 Jan 2019 22:59:51 -0800 Subject: [PATCH 1/2] Add login script to login page --- front/static/login.html | 4 ++-- front/static/login.js | 45 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 front/static/login.js diff --git a/front/static/login.html b/front/static/login.html index f9387dc..3784525 100644 --- a/front/static/login.html +++ b/front/static/login.html @@ -11,11 +11,11 @@

Login Page

-
+ username:
password:
- + diff --git a/front/static/login.js b/front/static/login.js new file mode 100644 index 0000000..20217d3 --- /dev/null +++ b/front/static/login.js @@ -0,0 +1,45 @@ +function displayErrorMessage(errorMessage) { + const errorReport = document.querySelector("#errorReport"); + errorReport.innerHTML = JSON.parse(errorMessage).error; +} + +function postToLoginEndpoint(event) { + event.preventDefault(); + + const credentials = { + "username" : this.elements.username.value, + "password" : this.elements.password.value + } + const url = "https://reqres.in/api/login" // mock api service + const xhr = new XMLHttpRequest(); + + console.log(`User credentials:\n${JSON.stringify(credentials)}`); + + xhr.open("POST", url, true); + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.onreadystatechange = function() { + if (this.readyState === 4) { + if (this.status === 200) { + console.log("LOGIN SUCCESS!"); + console.log(`Server response:\n${this.response}`); + token = JSON.parse(this.response).token; + localStorage.setItem("token", token); + window.location.replace("dashboard.html"); + } else { + console.log("LOGIN FAILURE!"); + console.log(`Server status: ${this.status}`); + console.log(`Server response:\n${this.response}`); + displayErrorMessage(this.response); + } + } + }; + + xhr.onerror = function() { + alert("Error connecting to the authentication server!"); + }; + + xhr.send(JSON.stringify(credentials)); +} + +const form = document.querySelector("form"); +form.addEventListener("submit", postToLoginEndpoint); From e0540739e7d43bb2c552528fa43f990d7c75e8e5 Mon Sep 17 00:00:00 2001 From: Preston Doman Date: Wed, 16 Jan 2019 23:55:23 -0800 Subject: [PATCH 2/2] Add missing errorReport tag to login.html --- front/static/login.html | 1 + 1 file changed, 1 insertion(+) diff --git a/front/static/login.html b/front/static/login.html index 3784525..40ceccf 100644 --- a/front/static/login.html +++ b/front/static/login.html @@ -16,6 +16,7 @@ password:
+