Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

using fastapi's security to use api key authentication #4

Merged
merged 1 commit into from
Jun 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 22 additions & 16 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
import uvicorn
from pathlib import Path
import logging
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi import FastAPI, Depends, Security, status, HTTPException
from fastapi.security import (
HTTPBearer,
APIKeyHeader,
)
from celery import Celery
from starlette.middleware.base import BaseHTTPMiddleware
from logging.config import dictConfig
from dotenv import load_dotenv

Expand Down Expand Up @@ -62,33 +64,37 @@ def format(self, record):
)


class CustomAuthMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
# Add your custom logic here
if request.headers.get("authorization") != os.getenv("API_KEY"):
logging.info("hi there")
return JSONResponse(status_code=401, content={"message": "Unauthorized"})
return await call_next(request)
app = FastAPI()

security = HTTPBearer()

api_key_header = APIKeyHeader(name="Authorization")


async def authenticate_user(api_key_header: str = Security(api_key_header)):
if api_key_header != os.getenv("API_KEY"):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized"
)
return {}

app = FastAPI()

# celery
celery = Celery(
"t4d-ai-llm",
)
celery.config_from_object(CeleryConfig, namespace="CELERY")

# middleware
app.add_middleware(CustomAuthMiddleware)

# routes
app.include_router(text_summarization_router, prefix="/api")
app.include_router(
text_summarization_router, prefix="/api", dependencies=[Depends(authenticate_user)]
)


# home route
@app.get("/api")
async def home():
async def home(auth_user: dict = Depends(authenticate_user)):
print("here")
return {"message": "Welcome to the T4D's AI/LLM service"}


Expand Down