Skip to content

Commit

Permalink
feat: token based auth
Browse files Browse the repository at this point in the history
  • Loading branch information
Fedir Zadniprovskyi authored and fedirz committed Nov 1, 2024
1 parent a029b73 commit c6b0d43
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
1 change: 1 addition & 0 deletions src/faster_whisper_server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ class Config(BaseSettings):

model_config = SettingsConfigDict(env_nested_delimiter="__")

api_key: str | None = None
log_level: str = "debug"
host: str = Field(alias="UVICORN_HOST", default="0.0.0.0")
port: int = Field(alias="UVICORN_PORT", default=8000)
Expand Down
16 changes: 15 additions & 1 deletion src/faster_whisper_server/dependencies.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from functools import lru_cache
from typing import Annotated

from fastapi import Depends
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

from faster_whisper_server.config import Config
from faster_whisper_server.model_manager import PiperModelManager, WhisperModelManager
Expand Down Expand Up @@ -31,3 +32,16 @@ def get_piper_model_manager() -> PiperModelManager:


PiperModelManagerDependency = Annotated[PiperModelManager, Depends(get_piper_model_manager)]


security = HTTPBearer()


async def verify_api_key(
config: ConfigDependency, credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
) -> None:
if credentials.credentials != config.api_key:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)


ApiKeyDependency = Depends(verify_api_key)
8 changes: 6 additions & 2 deletions src/faster_whisper_server/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
)
from fastapi.middleware.cors import CORSMiddleware

from faster_whisper_server.dependencies import get_config, get_model_manager
from faster_whisper_server.dependencies import get_config, get_model_manager, verify_api_key
from faster_whisper_server.logger import setup_logger
from faster_whisper_server.routers.list_models import (
router as list_models_router,
Expand Down Expand Up @@ -50,7 +50,11 @@ async def lifespan(_app: FastAPI) -> AsyncGenerator[None, None]:
model_manager.load_model(model_name)
yield

app = FastAPI(lifespan=lifespan)
dependencies = []
if config.api_key is not None:
dependencies.append(verify_api_key)

app = FastAPI(lifespan=lifespan, dependencies=dependencies)

app.include_router(stt_router)
app.include_router(list_models_router)
Expand Down

0 comments on commit c6b0d43

Please sign in to comment.