# Imports from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException from functions import * # Create DB on startup # noinspection PyUnusedLocal @asynccontextmanager async def lifespan(app: FastAPI): create_db_and_tables() yield # Code before the yield will run on startup, code after yield won't run until the program is over # Define the app app = FastAPI(lifespan=lifespan) # Routes @app.post("/heroes/create", response_model=HeroPublic) def create_hero(hero: HeroCreate, session: SessionDep): existing_hero = session.query(Hero).filter(Hero.email == hero.email).first() if existing_hero: raise HTTPException(status_code=400, detail="Email already registered") db_hero = Hero.model_validate(hero) session.add(db_hero) session.commit() session.refresh(db_hero) return db_hero @app.get("/heroes/{id}", response_model=Hero) def get_hero(id: int, session: SessionDep): hero = session.get(Hero, id) if not hero: raise HTTPException(status_code=404, detail="User not found") return hero @app.patch("/heroes/update/{hero_id}", response_model=HeroPublic) def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): hero_db = session.get(Hero, hero_id) if not hero_db: raise HTTPException(status_code=404, detail="Hero not found") hero_data = hero.model_dump(exclude_unset=True) hero_db.sqlmodel_update(hero_data) session.add(hero_db) session.commit() session.refresh(hero_db) return hero_db @app.delete("/heroes/delete/{id}") def delete_hero(id: int, session: SessionDep): hero = session.get(Hero, id) if not hero: raise HTTPException(status_code=404, detail="Hero not found") session.delete(hero) session.commit() return {"message": "Delete successful", "continue": True} @app.post("/verify") def verify_user(email: str, password: str, session: SessionDep): user = get_hero_by_email(email, session) if not user: return {"message": "Authentication failed", "continue": False} # check if the password is correct authenticate_user = verify_password(password, user.hash, user.salt) if authenticate_user: return {"message": "Authentication successful", "continue": True} return {"message": "Authentication failed", "continue": False}