auth.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. import {fetchRegular} from "./utils.js";
  3. const emailInput = document.getElementById("login-email");
  4. const passwordInput = document.getElementById("login-password");
  5. const errorMessageParagraph = document.getElementById("login-error");
  6. const submitButtonLogin = document.getElementById("btn-login");
  7. const submitButtonRegister = document.getElementById("btn-register");
  8. window.addEventListener("load", function () {
  9. submitButtonLogin.addEventListener("click", async function () {
  10. await login();
  11. })
  12. submitButtonRegister.addEventListener("click", async function () {
  13. await register();
  14. })
  15. });
  16. async function sendAuthRequest(type) {
  17. const response = await fetchRegular(
  18. "/api/auth/" + type,
  19. {
  20. method: "POST",
  21. headers: {
  22. "Content-Type": "application/json", // Set the content type to JSON
  23. },
  24. body: JSON.stringify(
  25. {
  26. email: emailInput.value,
  27. password: passwordInput.value,
  28. }
  29. ),
  30. }
  31. )
  32. const response_json = await response.json();
  33. if (response.status === 200) {
  34. console.log("success")
  35. localStorage.setItem("token", response_json["token"]);
  36. window.location.replace("/html/appointments.html");
  37. } else {
  38. if (response_json["error"]) {
  39. errorMessageParagraph.innerText = response_json["error"];
  40. } else {
  41. errorMessageParagraph.innerText = response_json["message"];
  42. }
  43. }
  44. }
  45. async function login() {
  46. await sendAuthRequest("login");
  47. }
  48. async function register() {
  49. await sendAuthRequest("register");
  50. }