add basic auth
This commit is contained in:
24
app.py
24
app.py
@@ -1,6 +1,8 @@
|
||||
import os
|
||||
import logging
|
||||
from fastapi import FastAPI, Request, WebSocket
|
||||
from typing import Annotated
|
||||
from fastapi import FastAPI, Request, WebSocket, Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from main import generate
|
||||
@@ -17,6 +19,8 @@ logger = logging.getLogger(__name__)
|
||||
STATIC_DIR = "static"
|
||||
TEMPLATES_DIR = "templates"
|
||||
|
||||
security = HTTPBasic()
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
app.mount(f"/{STATIC_DIR}", StaticFiles(directory=STATIC_DIR), name="static")
|
||||
@@ -24,8 +28,24 @@ app.mount(f"/{STATIC_DIR}", StaticFiles(directory=STATIC_DIR), name="static")
|
||||
templates = Jinja2Templates(directory=os.path.join(STATIC_DIR, TEMPLATES_DIR))
|
||||
|
||||
|
||||
def verify_credentials(credentials: HTTPBasicCredentials = Depends(security)):
|
||||
correct_username = os.getenv("BASIC_AUTH_USERNAME")
|
||||
correct_password = os.getenv("BASIC_AUTH_PASSWORD")
|
||||
|
||||
if not (
|
||||
credentials.username == correct_username
|
||||
and credentials.password == correct_password
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": "Basic"},
|
||||
)
|
||||
return credentials.username
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def home(request: Request):
|
||||
async def home(request: Request, username: Annotated[str, Depends(verify_credentials)]):
|
||||
return templates.TemplateResponse("index.html", {"request": request})
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user