auth.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. console.log(emailInput.value);
  18. console.log(passwordInput.value);
  19. const response = await fetchRegular(
  20. "/api/auth/" + type,
  21. {
  22. method: "POST",
  23. headers: {
  24. "Content-Type": "application/json", // Set the content type to JSON
  25. },
  26. body: JSON.stringify(
  27. {
  28. email: emailInput.value,
  29. password: passwordInput.value,
  30. }
  31. ),
  32. }
  33. )
  34. const response_json = await response.json();
  35. if (response.status === 200) {
  36. localStorage.setItem("token", response_json["token"]);
  37. window.location.replace("/html/appointments.html");
  38. } else {
  39. if (response_json["error"]) {
  40. errorMessageParagraph.innerText = response_json["error"];
  41. } else {
  42. errorMessageParagraph.innerText = response_json["message"];
  43. }
  44. }
  45. }
  46. async function login() {
  47. await sendAuthRequest("login");
  48. }
  49. async function register() {
  50. await sendAuthRequest("register");
  51. }