initial commit 2
This commit is contained in:
4
backend/.env
Normal file
4
backend/.env
Normal file
@@ -0,0 +1,4 @@
|
||||
DATABASE_URL=postgresql+psycopg://postgres:password@127.0.0.1:5432/hackaton
|
||||
SECRET_KEY=change-this-in-production
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=10080
|
||||
CORS_ORIGINS=http://localhost:3000,http://10.0.2.2:3000
|
||||
5
backend/.env.copy-paste.example
Normal file
5
backend/.env.copy-paste.example
Normal file
@@ -0,0 +1,5 @@
|
||||
# Copia este contenido a backend/.env y reemplaza los valores entre < >
|
||||
DATABASE_URL=postgresql+psycopg://<usuario>:<contraseña>@<IP_DE_TU_POSTGRESQL>:5432/<nombre_base_datos>
|
||||
SECRET_KEY=<cadena_larga_secreta>
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=10080
|
||||
CORS_ORIGINS=http://localhost:3000,http://10.0.2.2:3000,http://<IP_DE_TU_FLUTTER>:8000
|
||||
4
backend/.env.example
Normal file
4
backend/.env.example
Normal file
@@ -0,0 +1,4 @@
|
||||
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
|
||||
128
backend/README.md
Normal file
128
backend/README.md
Normal file
@@ -0,0 +1,128 @@
|
||||
# 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.
|
||||
0
backend/app/__init__.py
Normal file
0
backend/app/__init__.py
Normal file
22
backend/app/auth.py
Normal file
22
backend/app/auth.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from jose import jwt
|
||||
from passlib.context import CryptContext
|
||||
|
||||
from .core.config import settings
|
||||
|
||||
pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto')
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
|
||||
def create_access_token(*, user_id: int, email: str) -> str:
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
|
||||
payload = {'sub': str(user_id), 'email': email, 'exp': expire}
|
||||
return jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm)
|
||||
0
backend/app/core/__init__.py
Normal file
0
backend/app/core/__init__.py
Normal file
25
backend/app/core/config.py
Normal file
25
backend/app/core/config.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from functools import lru_cache
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8', extra='ignore')
|
||||
|
||||
database_url: str = 'postgresql+psycopg://postgres:password@127.0.0.1:5432/hackaton'
|
||||
secret_key: str = 'change-this-in-production'
|
||||
algorithm: str = 'HS256'
|
||||
access_token_expire_minutes: int = 60 * 24 * 7
|
||||
cors_origins: str = 'http://localhost:3000,http://10.0.2.2:3000'
|
||||
|
||||
@property
|
||||
def cors_origin_list(self) -> list[str]:
|
||||
return [origin.strip() for origin in self.cors_origins.split(',') if origin.strip()]
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
56
backend/app/crud.py
Normal file
56
backend/app/crud.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .auth import hash_password, verify_password
|
||||
from .models import Address, User
|
||||
from .schemas import AddressCreate, UserCreate
|
||||
|
||||
|
||||
def get_user_by_id(db: Session, user_id: int) -> User | None:
|
||||
return db.get(User, user_id)
|
||||
|
||||
|
||||
def get_user_by_email(db: Session, email: str) -> User | None:
|
||||
statement = select(User).where(User.email == email)
|
||||
return db.scalar(statement)
|
||||
|
||||
|
||||
def create_user(db: Session, user_in: UserCreate) -> User:
|
||||
user = User(
|
||||
name=user_in.name,
|
||||
email=user_in.email,
|
||||
password_hash=hash_password(user_in.password),
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def authenticate_user(db: Session, email: str, password: str) -> User | None:
|
||||
user = get_user_by_email(db, email)
|
||||
if user is None:
|
||||
return None
|
||||
if not verify_password(password, user.password_hash):
|
||||
return None
|
||||
|
||||
user.last_login_at = datetime.now(timezone.utc)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def create_address(db: Session, user: User, address_in: AddressCreate) -> Address:
|
||||
address = Address(
|
||||
user_id=user.id,
|
||||
house_number=address_in.house_number,
|
||||
colonia=address_in.colonia,
|
||||
street=address_in.street,
|
||||
)
|
||||
db.add(address)
|
||||
db.commit()
|
||||
db.refresh(address)
|
||||
return address
|
||||
0
backend/app/db/__init__.py
Normal file
0
backend/app/db/__init__.py
Normal file
22
backend/app/db/session.py
Normal file
22
backend/app/db/session.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from collections.abc import Generator
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
|
||||
|
||||
from ..core.config import settings
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
engine = create_engine(settings.database_url, pool_pre_ping=True)
|
||||
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
31
backend/app/dependencies.py
Normal file
31
backend/app/dependencies.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from jose import JWTError, jwt
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .core.config import settings
|
||||
from .crud import get_user_by_id
|
||||
from .db.session import get_db
|
||||
from .models import User
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='/auth/login')
|
||||
|
||||
|
||||
def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User:
|
||||
credentials_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail='Token inválido o expirado',
|
||||
headers={'WWW-Authenticate': 'Bearer'},
|
||||
)
|
||||
try:
|
||||
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
||||
user_id = payload.get('sub')
|
||||
if user_id is None:
|
||||
raise credentials_exception
|
||||
except JWTError as exc:
|
||||
raise credentials_exception from exc
|
||||
|
||||
user = get_user_by_id(db, int(user_id))
|
||||
if user is None:
|
||||
raise credentials_exception
|
||||
return user
|
||||
79
backend/app/main.py
Normal file
79
backend/app/main.py
Normal file
@@ -0,0 +1,79 @@
|
||||
from fastapi import Depends, FastAPI, HTTPException, status
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .auth import create_access_token
|
||||
from .core.config import settings
|
||||
from .crud import authenticate_user, create_address, create_user, get_user_by_email
|
||||
from .db.session import Base, engine, get_db
|
||||
from .dependencies import get_current_user
|
||||
from .models import Address, User
|
||||
from .schemas import AddressCreate, AddressRead, TokenResponse, UserCreate, UserLogin, UserRead
|
||||
|
||||
app = FastAPI(title='Flutter Auth API', version='1.0.0')
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.cors_origin_list,
|
||||
allow_credentials=True,
|
||||
allow_methods=['*'],
|
||||
allow_headers=['*'],
|
||||
)
|
||||
|
||||
|
||||
@app.on_event('startup')
|
||||
def on_startup() -> None:
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
|
||||
@app.get('/health')
|
||||
def health_check() -> dict[str, str]:
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
@app.post('/auth/register', response_model=TokenResponse, status_code=status.HTTP_201_CREATED)
|
||||
def register(payload: UserCreate, db: Session = Depends(get_db)) -> TokenResponse:
|
||||
existing_user = get_user_by_email(db, payload.email)
|
||||
if existing_user is not None:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Ya existe un usuario con ese correo')
|
||||
|
||||
user = create_user(db, payload)
|
||||
token = create_access_token(user_id=user.id, email=user.email)
|
||||
return TokenResponse(token=token, user=UserRead.model_validate(user))
|
||||
|
||||
|
||||
@app.post('/auth/login', response_model=TokenResponse)
|
||||
def login(payload: UserLogin, db: Session = Depends(get_db)) -> TokenResponse:
|
||||
user = authenticate_user(db, payload.email, payload.password)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Correo o contraseña inválidos')
|
||||
|
||||
token = create_access_token(user_id=user.id, email=user.email)
|
||||
return TokenResponse(token=token, user=UserRead.model_validate(user))
|
||||
|
||||
|
||||
@app.get('/me', response_model=UserRead)
|
||||
def read_me(current_user: User = Depends(get_current_user)) -> UserRead:
|
||||
return UserRead.model_validate(current_user)
|
||||
|
||||
|
||||
@app.post('/addresses', response_model=AddressRead, status_code=status.HTTP_201_CREATED)
|
||||
def save_address(
|
||||
payload: AddressCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
) -> AddressRead:
|
||||
if payload.email is not None and payload.email != current_user.email:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='El correo no coincide con el usuario autenticado')
|
||||
|
||||
address = create_address(db, current_user, payload)
|
||||
return AddressRead.model_validate(address)
|
||||
|
||||
|
||||
@app.get('/addresses/me', response_model=list[AddressRead])
|
||||
def read_my_addresses(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
) -> list[AddressRead]:
|
||||
addresses = sorted(current_user.addresses, key=lambda address: address.created_at, reverse=True)
|
||||
return [AddressRead.model_validate(address) for address in addresses]
|
||||
32
backend/app/models.py
Normal file
32
backend/app/models.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Integer, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from .db.session import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = 'users'
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
|
||||
name: Mapped[str] = mapped_column(String(120), nullable=False)
|
||||
email: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False)
|
||||
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
|
||||
addresses: Mapped[list['Address']] = relationship(back_populates='user', cascade='all, delete-orphan')
|
||||
|
||||
|
||||
class Address(Base):
|
||||
__tablename__ = 'addresses'
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id', ondelete='CASCADE'), index=True, nullable=False)
|
||||
house_number: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
colonia: Mapped[str] = mapped_column(String(120), nullable=False)
|
||||
street: Mapped[str] = mapped_column(String(160), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
|
||||
user: Mapped['User'] = relationship(back_populates='addresses')
|
||||
50
backend/app/schemas.py
Normal file
50
backend/app/schemas.py
Normal file
@@ -0,0 +1,50 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, EmailStr, Field
|
||||
|
||||
|
||||
class UserBase(BaseModel):
|
||||
name: str
|
||||
email: EmailStr
|
||||
|
||||
|
||||
class UserCreate(UserBase):
|
||||
password: str
|
||||
|
||||
|
||||
class UserLogin(BaseModel):
|
||||
email: EmailStr
|
||||
password: str
|
||||
|
||||
|
||||
class UserRead(UserBase):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
last_login_at: datetime | None = None
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
token: str
|
||||
user: UserRead
|
||||
|
||||
|
||||
class AddressCreate(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
house_number: str = Field(alias='houseNumber')
|
||||
colonia: str
|
||||
street: str
|
||||
email: EmailStr | None = None
|
||||
|
||||
|
||||
class AddressRead(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
house_number: str
|
||||
colonia: str
|
||||
street: str
|
||||
user_id: int
|
||||
created_at: datetime
|
||||
9
backend/requirements.txt
Normal file
9
backend/requirements.txt
Normal file
@@ -0,0 +1,9 @@
|
||||
fastapi==0.115.0
|
||||
uvicorn[standard]==0.32.0
|
||||
SQLAlchemy==2.0.36
|
||||
psycopg[binary]==3.2.3
|
||||
pydantic-settings==2.6.0
|
||||
python-jose[cryptography]==3.3.0
|
||||
passlib[bcrypt]==1.7.4
|
||||
python-multipart==0.0.12
|
||||
email-validator==2.2.0
|
||||
Reference in New Issue
Block a user