Version 0.2.0
All checks were successful
Run linters on applied template / Python 3.13 lint and build (push) Successful in 54s
All checks were successful
Run linters on applied template / Python 3.13 lint and build (push) Successful in 54s
Changes: - add metrics dispencer - add basic authentication dependency - enable GZIP middleware - add !env() example to deploy section - update dependencies state attribute name
This commit is contained in:
34
{{project_slug}}/dependencies/auth_dep.py
Normal file
34
{{project_slug}}/dependencies/auth_dep.py
Normal file
@@ -0,0 +1,34 @@
|
||||
"""Authentication dependency function is defined here."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import jwt
|
||||
from fastapi import Request
|
||||
|
||||
from . import logger_dep
|
||||
|
||||
|
||||
@dataclass
|
||||
class AuthenticationData:
|
||||
api_key: str | None
|
||||
jwt_payload: dict | None
|
||||
jwt_original: str | None
|
||||
|
||||
|
||||
def obtain(request: Request) -> AuthenticationData:
|
||||
if hasattr(request.state, "auth_dep"):
|
||||
return request.state.auth_dep
|
||||
auth = AuthenticationData(None, None, None)
|
||||
if (value := request.headers.get("X-API-Key")) is not None:
|
||||
auth.api_key = value
|
||||
if (value := request.headers.get("Authorization")) is not None and value.startswith("Bearer "):
|
||||
value = value[7:]
|
||||
auth.jwt_original = value
|
||||
try:
|
||||
auth.jwt_payload = jwt.decode(value, algorithms=["HS256"], options={"verify_signature": False})
|
||||
except Exception: # pylint: disable=broad-except
|
||||
logger = logger_dep.obtain(request)
|
||||
logger.warning("failed to parse Authorization header as jwt", value=value)
|
||||
logger.debug("failed to parse Authorization header as jwt", exc_info=True)
|
||||
request.state.auth_dep = auth
|
||||
return auth
|
||||
Reference in New Issue
Block a user