auth.js 1.1 KB

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