# Backend Python para Flutter Backend en Python con FastAPI para autenticar usuarios y guardar direcciones en PostgreSQL. No usa HTTPS; expone HTTP en el puerto 8000 por defecto. ## Qué debes cambiar ### 1. Configuración del backend Crea el archivo `backend/.env` copiando `backend/.env.example` y reemplaza estos valores: ```env DATABASE_URL=postgresql+psycopg://postgres:TU_PASSWORD@10.77.234.29:5432/hackaton SECRET_KEY=pon-una-clave-larga-y-segura-aqui ACCESS_TOKEN_EXPIRE_MINUTES=10080 CORS_ORIGINS=http://localhost:3000,http://10.0.2.2:3000,http://10.77.234.6:8000 ``` ### 2. Configuración de Flutter En Flutter, la URL base del backend está en [lib/app_config.dart](../lib/app_config.dart). Debe apuntar al backend HTTP, por ejemplo: ```dart static const String apiBaseUrl = String.fromEnvironment( 'API_BASE_URL', defaultValue: 'http://10.77.234.6:8000', ); ``` No pongas la cadena `postgresql://...` en Flutter. Esa cadena solo va en el backend. ## Variables que usa el backend - `DATABASE_URL`: conexión a PostgreSQL. - `SECRET_KEY`: clave para firmar el token JWT. - `ACCESS_TOKEN_EXPIRE_MINUTES`: tiempo de vida del token. - `CORS_ORIGINS`: orígenes permitidos para la app Flutter o pruebas web. ## Estructura de PostgreSQL El backend crea las tablas automáticamente al arrancar con `Base.metadata.create_all(...)`, pero si quieres crearlas manualmente, este es el esquema esperado. ### Tabla `users` ```sql CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name VARCHAR(120) NOT NULL, email VARCHAR(255) NOT NULL UNIQUE, password_hash VARCHAR(255) NOT NULL, last_login_at TIMESTAMPTZ NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); ``` ### Tabla `addresses` ```sql CREATE TABLE IF NOT EXISTS addresses ( id SERIAL PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, house_number VARCHAR(50) NOT NULL, colonia VARCHAR(120) NOT NULL, street VARCHAR(160) NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); ``` ## Datos que se envían desde Flutter ### Registro Se envía al endpoint `POST /auth/register`: ```json { "name": "Juan Perez", "email": "juan@mail.com", "password": "123456" } ``` ### Inicio de sesión Se envía al endpoint `POST /auth/login`: ```json { "email": "juan@mail.com", "password": "123456" } ``` ### Dirección Se envía al endpoint `POST /addresses` con token Bearer: ```json { "email": "juan@mail.com", "houseNumber": "12A", "colonia": "Centro", "street": "Reforma" } ``` ## Endpoints disponibles - `POST /auth/register` - `POST /auth/login` - `GET /me` - `POST /addresses` - `GET /health` ## Instalar y ejecutar ```bash cd backend python -m venv .venv .venv\Scripts\activate pip install -r requirements.txt uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 ``` ## Cómo funciona la conexión 1. Flutter llama a `http://IP_DEL_BACKEND:8000`. 2. El backend recibe login/registro y crea el token JWT. 3. El backend conecta a PostgreSQL usando `DATABASE_URL`. 4. Al guardar la dirección, el backend asocia la dirección al usuario autenticado. ## Nota importante Si pruebas desde un celular físico, `10.0.2.2` no sirve para la API. Debes usar la IP real de la computadora donde corre el backend.