Add an endpoint for posting to Grafana

This commit is contained in:
2026-01-11 20:01:58 +01:00
parent fcbb0abd8f
commit 11e4587399
4 changed files with 89 additions and 11 deletions

View File

@@ -1,3 +1,4 @@
from enum import auto, Enum
from typing import Annotated, Generator, Sequence, cast
from fastapi import Depends, Request, HTTPException
@@ -27,10 +28,35 @@ def get_session(engine: EngineDep) -> Generator[Session]:
SessionDep = Annotated[Session, Depends(get_session)]
class TokenType(Enum):
"""
Types of authentication tokens.
"""
# Token is put into the X-Token header
X_TOKEN = auto()
# Token is put into the "Authorization" header with type "Bearer".
BEARER = auto()
def get_by_token(
cls: type[SQLModel], request: Request, session: SessionDep
cls: type[SQLModel],
request: Request,
session: SessionDep,
token_type: TokenType = TokenType.X_TOKEN,
) -> SQLModel:
token = request.headers.get("X-Token")
token: str | None = None
match token_type:
case TokenType.X_TOKEN:
token = request.headers.get("X-Token")
case TokenType.BEARER:
token = request.headers.get("Authorization")
if token is not None:
parts = token.split(" ")
if len(parts) == 2 and parts[0] == "Bearer":
token = parts[1]
if token is None:
raise HTTPException(
detail="No token provided",
@@ -47,19 +73,28 @@ def get_by_token(
def get_user(request: Request, session: SessionDep) -> User:
return cast(User, get_by_token(User, request, session))
return cast(
User, get_by_token(User, request, session, token_type=TokenType.X_TOKEN)
)
UserDep = Annotated[User, Depends(get_user)]
def get_bot(request: Request, session: SessionDep) -> Bot:
return cast(Bot, get_by_token(Bot, request, session))
return cast(Bot, get_by_token(Bot, request, session, token_type=TokenType.X_TOKEN))
BotDep = Annotated[Bot, Depends(get_bot)]
def get_authorization_bot(request: Request, session: SessionDep) -> Bot:
return cast(Bot, get_by_token(Bot, request, session, token_type=TokenType.BEARER))
AuthorizationBotDep = Annotated[Bot, Depends(get_authorization_bot)]
def get_bot_by_id(bot_id: str, user_id: str, session: SessionDep) -> Bot | None:
"""
Fetches the specified bot from the database.