auth.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { beforeUnloadHandler } from "../app.js";
  2. import { showError } from "../utils/error.js";
  3. async function login(email,pin){
  4. const response = await fetch("/api/users/login", {
  5. method: "POST",
  6. headers: {
  7. "Content-Type": "application/json"
  8. },
  9. body: JSON.stringify({ email, pin })
  10. }
  11. );
  12. if (response.status == 420) {
  13. window.removeEventListener("beforeunload", beforeUnloadHandler);
  14. window.location.replace("/");
  15. }
  16. if (response.status == 404) {
  17. const errorData = await response.json().catch(() => ({ message: "El usuario no fue encontrado." }));
  18. throw new Error(errorData.message);
  19. }else if (response.status == 401) {
  20. const errorData = await response.json().catch(() => ({ message: "Credenciales incorrectas.", attempts: 0 }));
  21. showError(`${errorData.message} Intentos restantes: ${errorData.attempts_remaining || 0}`);
  22. throw new Error(errorData.message);
  23. } else if (response.status == 429) {
  24. const errorData = await response.json().catch(() => ({ message: "Demasiados intentos de inicio de sesión." }));
  25. showError(`${errorData.message} Intenta más tarde.`);
  26. throw new Error(errorData.message);
  27. }else if (response.status != 200) {
  28. console.error(response.status, response.statusText);
  29. const errorData = await response.json().catch(() => ({ message: "Error al iniciar sesión." }));
  30. showError(`${errorData.message}`);
  31. throw new Error(errorData.message);
  32. }
  33. const data = await response.json();
  34. if (!data || !data.data.token) {
  35. showError("Error al iniciar sesión, Intenta mas tarde.");
  36. throw new Error("Error al iniciar sesión.");
  37. }
  38. return {data: data.data};
  39. }
  40. export { login };