pilotwings/backend/http.py

64 lines
1.7 KiB
Python
Raw Normal View History

2024-11-03 16:04:28 +00:00
from os import path
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
2024-11-03 16:04:28 +00:00
from starlette import status
2024-11-02 17:35:12 +00:00
from .db import User, create_db_and_tables, engine, get_session
2024-11-03 16:04:28 +00:00
from .docker import client
2024-11-02 17:35:12 +00:00
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(
2024-11-03 16:04:28 +00:00
status_code=status.HTTP_403_FORBIDDEN,
2024-11-02 17:35:12 +00:00
detail="Invalid authentication credentials",
)
return user
app = FastAPI(dependencies=[Depends(get_session), Depends(check_auth)])
@app.on_event("startup")
def on_startup() -> None:
create_db_and_tables()
2024-11-03 16:04:28 +00:00
@app.get("/api/containers")
def get_containers(
session: Annotated[Session, Depends(get_session)],
credentials: Annotated[HTTPBasicCredentials, Depends(security)],
):
if credentials.username == "admin":
return [container.name for container in client.containers.list()]
return [
container.name
for container in client.containers.list(
filters={"label": f"owner={credentials.username}"}
)
]
app.mount(
"/",
StaticFiles(directory=f"{path.dirname(path.realpath(__file__))}/dist", html=True),
name="static",
)