auth.js 1.5 KB

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