auth.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { beforeUnloadHandler } from "../app.js";
  2. import { showError } from "../utils/error.js";
  3. async function login(email, pin, table) {
  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()
  18. const data = errorData.error.message
  19. } else if (response.status == 401) {
  20. const errorData = await response.json()
  21. const data = errorData.error.message
  22. showError(`${data} Intentos restantes: ${errorData.error.attempts_remaining || 0}`);
  23. throw new Error(errorData.message);
  24. } else if (response.status == 429) {
  25. const errorData = await response.json()
  26. const data = errorData.error.message
  27. showError(`${data} Intenta más tarde.`);
  28. throw new Error(errorData.message);
  29. } else if (response.status != 200) {
  30. console.error(response.status, response.statusText);
  31. const errorData = await response.json()
  32. const data = errorData.error.message
  33. showError(`${data}`);
  34. throw new Error(data);
  35. }
  36. const JSONdata = await response.json();
  37. const data = JSONdata.data;
  38. const userData = data.data;
  39. console.log(userData);
  40. if (!userData || !userData.token) {
  41. showError("Error al iniciar sesión, Intenta mas tarde.");
  42. throw new Error("Error al iniciar sesión.");
  43. }
  44. return userData;
  45. }
  46. async function existsTable(table) {
  47. // Check if table exists
  48. const responseTableExists = await fetch(`/api/store/tables/exists?q=${table}`, {
  49. method: "GET",
  50. headers: {
  51. "Content-Type": "application/json"
  52. }
  53. });
  54. const data = (await responseTableExists.json()).data.exists;
  55. return data;
  56. }
  57. export { login, existsTable };