auth.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.message
  19. } else if (response.status == 401) {
  20. const errorData = await response.json()
  21. const data = errorData.message
  22. showError(`${data} Intentos restantes: ${errorData.data.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.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.message
  33. showError(`${data}`);
  34. throw new Error(data);
  35. }
  36. const JSONdata = await response.json();
  37. const userData = JSONdata.data;
  38. console.log(userData);
  39. if (!userData || !userData.token) {
  40. showError("Error al iniciar sesión, Intenta mas tarde.");
  41. throw new Error("Error al iniciar sesión.");
  42. }
  43. return userData;
  44. }
  45. async function existsTable(table) {
  46. // Check if table exists
  47. const responseTableExists = await fetch(`/api/store/tables/exists?q=${table}`, {
  48. method: "GET",
  49. headers: {
  50. "Content-Type": "application/json"
  51. }
  52. });
  53. const data = (await responseTableExists.json()).data.exists;
  54. return data;
  55. }
  56. export { login, existsTable };