auth.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. /**
  9. * Add button event listeners, for login and register
  10. */
  11. window.addEventListener("load", function () {
  12. submitButtonLogin.addEventListener("click", async function () {
  13. await login();
  14. })
  15. submitButtonRegister.addEventListener("click", async function () {
  16. await register();
  17. })
  18. });
  19. /**
  20. * Function to handle sending authentication requests.
  21. *
  22. * @param {string} type - The type of request, either 'login' or 'register'.
  23. */
  24. async function sendAuthRequest(type) {
  25. const response = await fetchRegular(
  26. "/api/auth/" + type,
  27. {
  28. method: "POST",
  29. headers: {
  30. "Content-Type": "application/json", // Set the content type to JSON
  31. },
  32. body: JSON.stringify(
  33. {
  34. email: emailInput.value,
  35. password: passwordInput.value,
  36. }
  37. ),
  38. }
  39. )
  40. const response_json = await response.json();
  41. if (response.status === 200) {
  42. localStorage.setItem("token", response_json["token"]);
  43. window.location.replace("/html/appointments.html");
  44. } else {
  45. if (response_json["error"]) {
  46. errorMessageParagraph.innerText = response_json["error"];
  47. } else {
  48. errorMessageParagraph.innerText = response_json["message"];
  49. }
  50. }
  51. }
  52. /**
  53. * Function to handle user login.
  54. */
  55. async function login() {
  56. await sendAuthRequest("login");
  57. }
  58. /**
  59. * Function to handle user registration.
  60. */
  61. async function register() {
  62. await sendAuthRequest("register");
  63. }