Skip to content

Commit

Permalink
Merge pull request #1 from walison17/init
Browse files Browse the repository at this point in the history
Start
  • Loading branch information
vmesel authored Feb 26, 2024
2 parents 906699d + 3dc41fb commit 0563765
Show file tree
Hide file tree
Showing 6 changed files with 500 additions and 0 deletions.
Empty file added dialog_api_key/__init__.py
Empty file.
44 changes: 44 additions & 0 deletions dialog_api_key/plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from http import HTTPStatus

from decouple import Csv, config
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse


class Settings:
@property
def header(self):
return config("DIALOG_API_KEY_HEADER", default="X-Api-Key")

@property
def allowed_api_keys(self):
return config("DIALOG_API_KEYS", cast=Csv(post_process=set))

@property
def except_paths(self):
return config(
"DIALOG_API_KEY_IGNORE_PATHS",
cast=Csv(post_process=set),
default="/docs,/openapi.json",
)


settings = Settings()


async def api_key_middleware(request: Request, call_next):
if request.url.path in settings.except_paths:
return await call_next(request)

api_key = request.headers.get(settings.header)
if not api_key or api_key not in settings.allowed_api_keys:
return JSONResponse(
{"detail": "Invalid API Key."},
status_code=HTTPStatus.UNAUTHORIZED,
)

return await call_next(request)


def register_plugin(app: FastAPI):
app.middleware("http")(api_key_middleware)
Loading

0 comments on commit 0563765

Please sign in to comment.