This repository has been archived on 2026-10-28. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
karldns.de/karldns/dependencies.py
T

68 lines
2.1 KiB
Python
Raw Normal View History

2026-05-20 23:55:27 +02:00
from __future__ import annotations
import secrets
from typing import Annotated
2026-05-21 17:23:08 +02:00
from fastapi import Depends, Header, HTTPException, Request
2026-05-20 23:55:27 +02:00
from fastapi.responses import PlainTextResponse
2026-05-21 17:23:08 +02:00
from .dns import DnsProviderError
from .security import credentials_from_basic_auth
from .services.ddns import BadIpError, DdnsService, UpdateIpParams
2026-05-21 17:23:08 +02:00
from .settings import DdnsSettings
from .store import DdnsStore
2026-05-20 23:55:27 +02:00
def get_settings(request: Request) -> DdnsSettings:
return request.app.state.settings
def get_store(request: Request) -> DdnsStore:
return request.app.state.store
def get_service(request: Request) -> DdnsService:
return request.app.state.service
SettingsDep = Annotated[DdnsSettings, Depends(get_settings)]
StoreDep = Annotated[DdnsStore, Depends(get_store)]
ServiceDep = Annotated[DdnsService, Depends(get_service)]
def authenticate_admin(
request: Request,
authorization: Annotated[str | None, Header()] = None,
) -> None:
settings = get_settings(request)
if not settings.admin_password:
raise HTTPException(status_code=500, detail="DDNS_ADMIN_PASSWORD is required")
supplied = _basic_auth_password(authorization)
if supplied is None or not secrets.compare_digest(supplied, settings.admin_password):
2026-05-20 23:55:27 +02:00
raise HTTPException(
status_code=401,
detail="admin authentication required",
headers={"WWW-Authenticate": 'Basic realm="karldns"'},
)
def _basic_auth_password(authorization: str | None) -> str | None:
if authorization is None or not authorization.lower().startswith("basic "):
return None
_, password = credentials_from_basic_auth(authorization)
return password
2026-05-20 23:55:27 +02:00
def apply_update_response(
service: DdnsService,
request: Request,
hostname: str,
ip_params: UpdateIpParams,
2026-05-20 23:55:27 +02:00
) -> str | PlainTextResponse:
try:
return service.apply_update(request, hostname, ip_params).result.dyndns_response
2026-05-20 23:55:27 +02:00
except BadIpError:
return PlainTextResponse("badip", status_code=400)
except DnsProviderError:
return PlainTextResponse("911 dns publish failed", status_code=500)