Backend totalmente hecho con mongodb, añadida la funcionalidad de usuarios con historial
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from api.database.mongodb import users_collection
|
||||
from api.models.user_models import UserCreate, UserLogin
|
||||
from api.utils.security import hash_password, verify_password, generate_token
|
||||
from bson import ObjectId
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("/register")
|
||||
async def register_user(user: UserCreate):
|
||||
existing_username = await users_collection.find_one({"username": user.username})
|
||||
if existing_username:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="El nombre de usuario ya está en uso",
|
||||
)
|
||||
|
||||
existing_email = await users_collection.find_one({"email": user.email})
|
||||
if existing_email:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="El email ya está registrado",
|
||||
)
|
||||
|
||||
token = generate_token()
|
||||
|
||||
user_doc = {
|
||||
"username": user.username,
|
||||
"email": user.email,
|
||||
"password_hash": hash_password(user.password),
|
||||
"token": token,
|
||||
"history": [],
|
||||
}
|
||||
|
||||
result = await users_collection.insert_one(user_doc)
|
||||
|
||||
return {
|
||||
"message": "Usuario registrado correctamente",
|
||||
"user_id": str(result.inserted_id),
|
||||
"token": token,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def login_user(credentials: UserLogin):
|
||||
user = await users_collection.find_one({"email": credentials.email})
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Credenciales inválidas",
|
||||
)
|
||||
|
||||
if not verify_password(credentials.password, user["password_hash"]):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Credenciales inválidas",
|
||||
)
|
||||
|
||||
new_token = generate_token()
|
||||
|
||||
await users_collection.update_one(
|
||||
{"_id": user["_id"]},
|
||||
{"$set": {"token": new_token}}
|
||||
)
|
||||
|
||||
return {
|
||||
"message": "Login correcto",
|
||||
"user_id": str(user["_id"]),
|
||||
"username": user["username"],
|
||||
"token": new_token,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/logout/{user_id}")
|
||||
async def logout_user(user_id: str):
|
||||
user = await users_collection.find_one({"_id": ObjectId(user_id)})
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Usuario no encontrado",
|
||||
)
|
||||
|
||||
await users_collection.update_one(
|
||||
{"_id": ObjectId(user_id)},
|
||||
{"$set": {"token": None}}
|
||||
)
|
||||
|
||||
return {"message": "Sesión cerrada correctamente"}
|
||||
@@ -0,0 +1,62 @@
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from typing import List
|
||||
from datetime import datetime
|
||||
from bson import ObjectId
|
||||
|
||||
from api.database.mongodb import users_collection
|
||||
from api.models.user_models import FuzzyTerm, HistoryCreateRequest
|
||||
|
||||
router = APIRouter(prefix="/history", tags=["history"])
|
||||
|
||||
|
||||
@router.post("/{user_id}/add")
|
||||
async def add_history_item(user_id: str, data: HistoryCreateRequest):
|
||||
user = await users_collection.find_one({"_id": ObjectId(user_id)})
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Usuario no encontrado",
|
||||
)
|
||||
|
||||
history_item_id = ObjectId()
|
||||
|
||||
history_item = {
|
||||
"_id": history_item_id,
|
||||
"name": data.name, # ← nuevo campo
|
||||
"created_at": datetime.utcnow(),
|
||||
"results": [r.dict() for r in data.results],
|
||||
}
|
||||
|
||||
await users_collection.update_one(
|
||||
{"_id": ObjectId(user_id)},
|
||||
{"$push": {"history": history_item}},
|
||||
)
|
||||
|
||||
return {
|
||||
"message": "Elemento añadido al historial",
|
||||
"history_item_id": str(history_item_id),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@router.delete("/{user_id}/delete/{history_item_id}")
|
||||
async def delete_history_item(user_id: str, history_item_id: str):
|
||||
user = await users_collection.find_one({"_id": ObjectId(user_id)})
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Usuario no encontrado",
|
||||
)
|
||||
|
||||
result = await users_collection.update_one(
|
||||
{"_id": ObjectId(user_id)},
|
||||
{"$pull": {"history": {"_id": ObjectId(history_item_id)}}},
|
||||
)
|
||||
|
||||
if result.modified_count == 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Elemento de historial no encontrado",
|
||||
)
|
||||
|
||||
return {"message": "Elemento eliminado del historial"}
|
||||
@@ -1,13 +0,0 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import text
|
||||
from api.database.session import get_db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/test-db")
|
||||
def test_db_connection(db=Depends(get_db)):
|
||||
try:
|
||||
db.execute(text("SELECT 1"))
|
||||
return {"status": "ok", "message": "Conexión a MySQL correcta"}
|
||||
except Exception as e:
|
||||
return {"status": "error", "message": str(e)}
|
||||
@@ -0,0 +1,12 @@
|
||||
from fastapi import APIRouter
|
||||
from api.database.mongodb import db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/test-mongo")
|
||||
async def test_mongo():
|
||||
try:
|
||||
await db.command("ping")
|
||||
return {"status": "ok", "message": "Conexión a MongoDB correcta"}
|
||||
except Exception as e:
|
||||
return {"status": "error", "message": str(e)}
|
||||
Reference in New Issue
Block a user