pilotwings/backend/http.py

45 lines
1.2 KiB
Python
Raw Normal View History

2024-11-02 17:35:12 +00:00
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPBasic, HTTPBasicCredentials
2024-11-02 18:16:32 +00:00
from fastapi.staticfiles import StaticFiles
2024-11-02 17:35:12 +00:00
from sqlmodel import Session, and_, select
from starlette.status import HTTP_403_FORBIDDEN
from .db import User, create_db_and_tables, engine, get_session
security = HTTPBasic()
def check_auth(credentials: Annotated[HTTPBasicCredentials, Depends(security)]) -> User:
with Session(engine) as session:
statement = select(User).where(
and_(
User.username == credentials.username,
User.password == credentials.password,
)
)
user = session.exec(statement).first()
if not user:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Invalid authentication credentials",
)
return user
app = FastAPI(dependencies=[Depends(get_session), Depends(check_auth)])
2024-11-02 18:16:32 +00:00
app.mount("/", StaticFiles(directory="dist", html=True), name="static")
2024-11-02 17:35:12 +00:00
@app.on_event("startup")
def on_startup() -> None:
create_db_and_tables()
@app.get("/")
def hello_world() -> str:
return "<p>Hello, World!</p>"