diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000000..0e04844159 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Single-database configuration for Flask. diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 0000000000..ec9d45c26a --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,50 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic,flask_migrate + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[logger_flask_migrate] +level = INFO +handlers = +qualname = flask_migrate + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000000..4c9709271b --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,113 @@ +import logging +from logging.config import fileConfig + +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + + +def get_engine(): + try: + # this works with Flask-SQLAlchemy<3 and Alchemical + return current_app.extensions['migrate'].db.get_engine() + except (TypeError, AttributeError): + # this works with Flask-SQLAlchemy>=3 + return current_app.extensions['migrate'].db.engine + + +def get_engine_url(): + try: + return get_engine().url.render_as_string(hide_password=False).replace( + '%', '%%') + except AttributeError: + return str(get_engine().url).replace('%', '%%') + + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option('sqlalchemy.url', get_engine_url()) +target_db = current_app.extensions['migrate'].db + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def get_metadata(): + if hasattr(target_db, 'metadatas'): + return target_db.metadatas[None] + return target_db.metadata + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=get_metadata(), literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + conf_args = current_app.extensions['migrate'].configure_args + if conf_args.get("process_revision_directives") is None: + conf_args["process_revision_directives"] = process_revision_directives + + connectable = get_engine() + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=get_metadata(), + **conf_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000000..2c0156303a --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/9434161174ef_.py b/migrations/versions/9434161174ef_.py new file mode 100644 index 0000000000..be0474bc02 --- /dev/null +++ b/migrations/versions/9434161174ef_.py @@ -0,0 +1,96 @@ +"""empty message + +Revision ID: 9434161174ef +Revises: +Create Date: 2025-03-18 18:14:38.632997 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '9434161174ef' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('accessories', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(length=100), nullable=False), + sa.Column('brand', sa.String(length=100), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('animal_type', sa.String(length=50), nullable=False), + sa.Column('pathologies', sa.Text(), nullable=True), + sa.Column('price', sa.Float(), nullable=False), + sa.Column('url', sa.String(length=255), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('foods', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(length=100), nullable=False), + sa.Column('brand', sa.String(length=100), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('ingredients', sa.Text(), nullable=False), + sa.Column('weight', sa.Float(), nullable=False), + sa.Column('price', sa.Float(), nullable=False), + sa.Column('age', sa.String(), nullable=False), + sa.Column('animal_type', sa.String(length=50), nullable=False), + sa.Column('size', sa.String(length=30), nullable=True), + sa.Column('pathologies', sa.Text(), nullable=True), + sa.Column('url', sa.String(length=255), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('password_reset', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('email', sa.String(length=120), nullable=False), + sa.Column('token', sa.String(length=255), nullable=False), + sa.Column('expires_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('token') + ) + op.create_table('user', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(length=80), nullable=False), + sa.Column('email', sa.String(length=120), nullable=False), + sa.Column('password', sa.String(length=80), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('email') + ) + op.create_table('order', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('ordered_food', sa.String(), nullable=True), + sa.Column('ordered_accessories', sa.String(), nullable=True), + sa.Column('status', sa.String(), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('pet', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(length=100), nullable=False), + sa.Column('size', sa.String(length=100), nullable=True), + sa.Column('breed', sa.String(length=100), nullable=True), + sa.Column('age', sa.String(), nullable=False), + sa.Column('animal_type', sa.String(), nullable=False), + sa.Column('pathologies', sa.Text(), nullable=True), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('url', sa.String(length=255), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('pet') + op.drop_table('order') + op.drop_table('user') + op.drop_table('password_reset') + op.drop_table('foods') + op.drop_table('accessories') + # ### end Alembic commands ### diff --git a/package-lock.json b/package-lock.json index 41585c59bb..3f471ab850 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "@fortawesome/free-brands-svg-icons": "^6.7.2", "@fortawesome/react-fontawesome": "^0.2.2", "bootstrap": "^5.3.3", + "jwt-decode": "^4.0.0", "lucide-react": "^0.479.0", "prop-types": "^15.6.1", "react": "^16.8.4", @@ -6371,6 +6372,15 @@ "node": ">=4.0" } }, + "node_modules/jwt-decode": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz", + "integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/kind-of": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", @@ -14400,6 +14410,11 @@ "object.assign": "^4.1.2" } }, + "jwt-decode": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz", + "integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==" + }, "kind-of": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", diff --git a/package.json b/package.json index 1261769d10..9567acc956 100755 --- a/package.json +++ b/package.json @@ -76,6 +76,7 @@ "@fortawesome/free-brands-svg-icons": "^6.7.2", "@fortawesome/react-fontawesome": "^0.2.2", "bootstrap": "^5.3.3", + "jwt-decode": "^4.0.0", "lucide-react": "^0.479.0", "prop-types": "^15.6.1", "react": "^16.8.4", diff --git a/src/front/js/layout.js b/src/front/js/layout.js index 06c510d3ef..fc4550eafc 100755 --- a/src/front/js/layout.js +++ b/src/front/js/layout.js @@ -1,7 +1,8 @@ -import React, { useState } from "react"; +import React, { useState, useEffect, useContext } from "react"; import { BrowserRouter, Route, Routes, useLocation } from "react-router-dom"; import ScrollToTop from "./component/scrollToTop"; import { BackendURL } from "./component/backendURL"; +import { Context } from "./store/appContext"; import { Home } from "./pages/home"; import { PerfilUsuario} from "./pages/perfilUsuario"; @@ -25,6 +26,31 @@ import { CarritoPago } from "./pages/CarritoPago"; const Layout = () => { const basename = process.env.BASENAME || ""; const [activeCategory, setActiveCategory] = useState(null); + const { actions } = useContext(Context); // Obtenemos acciones del contexto + + useEffect(() => { + actions.loadUserFromStorage(); + + // Detectar actividad del usuario y reiniciar el temporizador + const resetInactivityTimer = () => { + clearTimeout(window.inactivityTimer); + window.inactivityTimer = setTimeout(() => { + console.log("Usuario inactivo, cerrando sesi贸n..."); + actions.logout(); + }, 30 * 60 * 1000); // 馃敼 Cerrar sesi贸n tras 30 min de inactividad + }; + + document.addEventListener("mousemove", resetInactivityTimer); + document.addEventListener("keydown", resetInactivityTimer); + document.addEventListener("click", resetInactivityTimer); + + return () => { + document.removeEventListener("mousemove", resetInactivityTimer); + document.removeEventListener("keydown", resetInactivityTimer); + document.removeEventListener("click", resetInactivityTimer); + }; + }, []); + if (!process.env.BACKEND_URL || process.env.BACKEND_URL === "") return ; diff --git a/src/front/js/store/flux.js b/src/front/js/store/flux.js index b547140c77..eb8d87843b 100755 --- a/src/front/js/store/flux.js +++ b/src/front/js/store/flux.js @@ -1,9 +1,11 @@ +import { jwtDecode } from "jwt-decode"; const getState = ({ getStore, getActions, setStore }) => { return { store: { user: null, token: null, message: null, + refreshTimer: null, demo: [ { title: "FIRST", @@ -34,36 +36,32 @@ const getState = ({ getStore, getActions, setStore }) => { try { const resp = await fetch(`${process.env.BACKEND_URL}/api/login`, { method: "POST", - headers: { - "Content-Type": "application/json" - }, + headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password }) }); - - if (!resp.ok) { - throw new Error("Error al iniciar sesi贸n"); - } - + + if (!resp.ok) throw new Error("Error al iniciar sesi贸n"); + const data = await resp.json(); - console.log("Inicio de sesi贸n exitoso:", data); - - const token = data.token; - if (!token) { - throw new Error("No se recibi贸 el token"); - } - - localStorage.setItem("token", token); - localStorage.setItem("user", JSON.stringify(data.user)); // 馃敼 Guarda el usuario - setStore({ token }); - - const actions = getActions(); - actions.getUser(); + sessionStorage.setItem("token", data.token); + sessionStorage.setItem("user", JSON.stringify(data.user)); + + setStore({ token: data.token, user: data.user }); navigate("/"); + + // Programar la renovaci贸n del token + const decoded = jwtDecode(data.token); + const expirationTime = decoded.exp * 1000; + const currentTime = Date.now(); + getActions().scheduleTokenRefresh(expirationTime - currentTime - 60000); + } catch (error) { console.log("Error al iniciar sesi贸n", error); alert("Error al iniciar sesi贸n"); } }, + + signup: async (dataUser, navigate) => { try { const resp = await fetch(`${process.env.BACKEND_URL}/api/signup`, { @@ -99,35 +97,108 @@ const getState = ({ getStore, getActions, setStore }) => { try { const token = localStorage.getItem("token"); if (!token) throw new Error("No token found"); - + const resp = await fetch(`${process.env.BACKEND_URL}/api/user`, { headers: { "Authorization": `Bearer ${token}` } }); - - if (!resp.ok) throw new Error("Error al obtener el usuario"); - + + if (!resp.ok) { + throw new Error("Error al obtener el usuario"); + } + const data = await resp.json(); setStore({ user: data }); + + // Obtener las mascotas del usuario + getActions().getPets(data.id); + } catch (error) { - console.log("Error al obtener usuario", error); + console.error("Error al obtener usuario:", error); + getActions().logout(); // 馃敼 Si hay un error, cerrar sesi贸n autom谩ticamente } }, - logout: () => { - localStorage.removeItem("token"); - localStorage.removeItem("user"); // 馃敼 Eliminar usuario de localStorage - setStore({ token: null, user: null, pets: [] }); - }, - - loadUserFromStorage: () => { - const token = localStorage.getItem("token"); //Cargar usuario - const user = localStorage.getItem("user"); + + // Cerrar sesi贸n si el usuario est谩 inactivo + logout: () => { + console.log("Cerrando sesi贸n por inactividad o token expirado..."); + sessionStorage.removeItem("token"); + sessionStorage.removeItem("user"); + clearTimeout(getStore().refreshTimer); + setStore({ token: null, user: null, refreshTimer: null }); + window.location.href = "/"; + }, + + + loadUserFromStorage: async () => { + const token = sessionStorage.getItem("token"); // 馃敼 Recuperar desde sessionStorage + const user = sessionStorage.getItem("user"); + if (token && user) { - setStore({ token, user: JSON.parse(user) }); + try { + // Validar si el token sigue siendo v谩lido + const resp = await fetch(`${process.env.BACKEND_URL}/api/user`, { + headers: { + "Authorization": `Bearer ${token}` + } + }); + + if (!resp.ok) { + throw new Error("Token inv谩lido o expirado"); + } + + setStore({ token, user: JSON.parse(user) }); + } catch (error) { + console.error("Error validando el token:", error); + getActions().logout(); // Si el token no es v谩lido, cerrar sesi贸n + } + } else { + console.log("No hay usuario autenticado, pero no redirigimos a煤n."); } }, + + + // Programar la renovaci贸n del token + scheduleTokenRefresh: (timeUntilRefresh) => { + if (timeUntilRefresh > 0) { + console.log(`Renovaci贸n del token programada en ${timeUntilRefresh / 1000} segundos`); + const refreshTimer = setTimeout(() => { + console.log("Intentando renovar el token..."); + getActions().refreshToken(); + }, timeUntilRefresh); + + setStore({ refreshTimer }); + } + }, + + // Simular renovaci贸n del token + refreshToken: async () => { + const token = sessionStorage.getItem("token"); + if (!token) return getActions().logout(); + + try { + // Aqu铆 podr铆as hacer una solicitud al backend para renovar el token + // Pero en este caso, simplemente estamos extendiendo su validez en el frontend. + const newToken = token; // 馃敼 Aqu铆 normalmente pedir铆as uno nuevo al backend. + + sessionStorage.setItem("token", newToken); + setStore({ token: newToken }); + + // Volver a programar la renovaci贸n + const decoded = jwtDecode(newToken); + const expirationTime = decoded.exp * 1000; + const currentTime = Date.now(); + getActions().scheduleTokenRefresh(expirationTime - currentTime - 60000); + + } catch (error) { + console.error("Error renovando el token:", error); + getActions().logout(); + } + }, + + //TRAER ALIMENTO POR GRUPOS getDogFood: async () => { const myHeaders = new Headers();