Change how requests are sent in order to send auth token

This commit is contained in:
Reimar 2025-03-27 09:03:34 +01:00
parent bce48fe8d1
commit 0f1b10d2d7
Signed by: Reimar
GPG Key ID: 93549FA07F0AE268
7 changed files with 148 additions and 168 deletions

View File

@ -6,7 +6,7 @@
<title>Temperature-Alarm-Web</title> <title>Temperature-Alarm-Web</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<link rel="stylesheet" href="/styles/home.css" /> <link rel="stylesheet" href="/styles/home.css" />
<script type="module" src="/scripts/home.js"></script> <script defer type="module" src="/scripts/home.js"></script>
</head> </head>
<body> <body>
@ -34,3 +34,4 @@
</div> </div>
</body> </body>
</html> </html>

View File

@ -1,11 +1,15 @@
import { mockTemperatureLogs } from "../mockdata/temperature-logs.mockdata.js"; // Import data import { mockTemperatureLogs } from "../mockdata/temperature-logs.mockdata.js"; // Import data
import { getLogsOnDeviceId } from "./services/devices.service.js";
const xValues = mockTemperatureLogs.map((log) => async function buildChart() {
const data = await getLogsOnDeviceId(1);
const xValues = mockTemperatureLogs.map((log) =>
new Date(log.date).toLocaleString() new Date(log.date).toLocaleString()
); // Full Date labels ); // Full Date labels
const yValues = mockTemperatureLogs.map((log) => log.temperature); // Temperature values const yValues = mockTemperatureLogs.map((log) => log.temperature); // Temperature values
buildTable(mockTemperatureLogs); buildTable(mockTemperatureLogs);
new Chart("myChart", { new Chart("myChart", {
type: "line", type: "line",
data: { data: {
labels: xValues, labels: xValues,
@ -31,7 +35,8 @@ new Chart("myChart", {
}, },
}, },
}, },
}); });
}
function buildTable(data) { function buildTable(data) {
var table = document.getElementById(`TemperatureTable`); var table = document.getElementById(`TemperatureTable`);
@ -63,22 +68,4 @@ function buildTable(data) {
}); });
} }
// Get the modal buildChart();
var modal = document.getElementById("chartModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function () {
modal.style.display = "block";
};
// When the user clicks on <span> (x), close the modal
span.onclick = function () {
modal.style.display = "none";
};
// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
};

View File

@ -10,13 +10,12 @@ document.getElementById("loginForm").addEventListener("submit", function(event)
login(emailOrUsername, password) login(emailOrUsername, password)
.then(response => { .then(response => {
if (response.error) {
document.getElementById("form-error").innerText = response.error;
document.getElementById("form-error").style.display = "block";
return;
}
location.href = "/home"; location.href = "/home";
})
.catch(error => {
console.log(error);
document.getElementById("form-error").innerText = error;
document.getElementById("form-error").style.display = "block";
}); });
}); });

View File

@ -14,13 +14,10 @@ document.getElementById("registerForm").addEventListener("submit", function(even
// Call function with form values // Call function with form values
create(email, username, password, repeatPassword) create(email, username, password, repeatPassword)
.then(response => { .then(response => {
if (response?.error) {
document.getElementById("form-error").innerText = response.error;
document.getElementById("form-error").style.display = "block";
return;
}
location.href = "/login"; location.href = "/login";
})
.catch(error => {
document.getElementById("form-error").innerText = error;
document.getElementById("form-error").style.display = "block";
}); });
}); });

View File

@ -1,4 +1,4 @@
import { address } from "../../shared/constants"; import { address } from "../../shared/constants.js";
export function getDevicesOnUserId(id) { export function getDevicesOnUserId(id) {
fetch(`${address}/get-on-user-id`, { fetch(`${address}/get-on-user-id`, {
@ -26,13 +26,12 @@ export function update(ids) {
.catch(error => console.error("Error:", error)); .catch(error => console.error("Error:", error));
} }
export function getLogsOnDeviceIds(id) { export function getLogsOnDeviceId(id) {
fetch(`${address}/get-on-device-ids`, { fetch(`${address}/device/logs/${id}`, {
method: "GET", method: "GET",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json"
}, },
body: JSON.stringify({ ids: id })
}) })
.then(response => response.json()) .then(response => response.json())
.then(data => console.log("Success:", data)) .then(data => console.log("Success:", data))

View File

@ -1,54 +1,32 @@
import { address } from "../../shared/constants.js"; import { request } from "../../shared/utils.js";
import { handleResponse } from "../../shared/utils.js";
export function login(usernameOrEmail, password) { export function login(usernameOrEmail, password) {
return fetch(`${address}/user/login`, { return request("POST", "/user/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
EmailOrUsrn: usernameOrEmail, EmailOrUsrn: usernameOrEmail,
Password: password, Password: password,
}), });
})
.then(handleResponse)
.catch(err => { error: err.message });
} }
export function create(email, username, password, repeatPassword){ export function create(email, username, password, repeatPassword){
return fetch(`${address}/user/create`, { return request("POST", "/user/create", {
method: "POST", email,
headers: { username,
"Content-Type": "application/json" password,
}, repeatPassword,
body: JSON.stringify({email: email, username: username, password: password, repeatPassword: repeatPassword}) });
})
.then(handleResponse)
.catch(err => { error: err.message });
} }
export function update(email, username){ export function update(email, username){
return fetch(`${address}/user/update`, { return request("PATCH", "/user/update", {
method: "PATCH", email,
headers: { username,
"Content-Type": "application/json" });
},
body: JSON.stringify({email: email, username: username})
})
.then(handleResponse)
.catch(err => { error: err.message });
} }
export function updatePassword(oldPassword, newPassword){ export function updatePassword(oldPassword, newPassword){
return fetch(`${address}/user/update-password`, { return request("PATCH", "/user/update-password", {
method: "PATCH", oldPassword,
headers: { newPassword,
"Content-Type": "application/json" });
},
body: JSON.stringify({oldPassword: oldPassword, newPassword: newPassword})
})
.then(handleResponse)
.catch(err => { error: err.message });
} }

View File

@ -1,12 +1,31 @@
export async function handleResponse(response) { import { address } from "./constants.js";
export async function request(method, path, body = null) {
const token = document.cookie.match(/\bauth-token=(\S+)/);
return new Promise((resolve, reject) => {
fetch(address + path, {
method,
headers: {
"Content-Type": body ? "application/json" : undefined,
"Authorization": token?.length > 1 ? `Bearer ${token[1]}` : undefined,
},
body: body ? JSON.stringify(body) : undefined,
})
.then(async response => {
const json = await response.json(); const json = await response.json();
if (response.ok || json.error) return json; if (response.ok) return resolve(json);
if (json.errors) { if (json.error) return reject(json.error);
return { error: Object.values(response.errors)[0][0] };
}
return { error: "Request failed with HTTP code " + response.status }; if (json.message) return reject(json.message);
if (json.errors) return reject(Object.values(response.errors)[0][0]);
reject("Request failed with HTTP code " + response.status);
})
.catch(err => reject(err.message));
});
} }