# Imports from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException from functions import * import random # 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): salt = random.randint(00000, 99999) existing_hero = session.query(Hero).filter(Hero.email == hero.email).first() if existing_hero: raise HTTPException(status_code=400, detail="Email already registered") hero.password = hash_password(hero.password, salt) hero.salt = salt 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=HeroPublic) 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(hero: VerifyHero, session: SessionDep): user = get_hero_by_email(hero.email, session) if not user: raise HTTPException(status_code=500, detail="Something went wrong.. Try again later") # check if the password is correct authenticate_user = verify_password(hero.password, user.password, user.salt) if authenticate_user: return {"message": "Authentication successful", "continue": True, "hero_id": user.id} raise HTTPException(status_code=500, detail="Something went wrong.. Try again later")