Check in backend in working state
This commit is contained in:
@ -0,0 +1,67 @@
|
||||
"""Backend API."""
|
||||
|
||||
import logging
|
||||
from typing import Annotated
|
||||
|
||||
import bcrypt
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from .api import get_audit_api, get_clients_api, get_policy_api, get_secrets_api
|
||||
from .models import (
|
||||
APIClient,
|
||||
)
|
||||
from .types import DBSessionDep
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
API_VERSION = "v1"
|
||||
|
||||
|
||||
def verify_token(token: str, stored_hash: str) -> bool:
|
||||
"""Verify token."""
|
||||
token_bytes = token.encode("utf-8")
|
||||
stored_bytes = stored_hash.encode("utf-8")
|
||||
return bcrypt.checkpw(token_bytes, stored_bytes)
|
||||
|
||||
|
||||
def get_backend_api(
|
||||
get_db_session: DBSessionDep,
|
||||
) -> APIRouter:
|
||||
"""Construct backend API."""
|
||||
|
||||
async def validate_token(
|
||||
x_api_token: Annotated[str, Header()],
|
||||
session: Annotated[Session, Depends(get_db_session)],
|
||||
) -> str:
|
||||
"""Validate token."""
|
||||
LOG.debug("Validating token %s", x_api_token)
|
||||
statement = select(APIClient)
|
||||
results = session.exec(statement)
|
||||
valid = False
|
||||
for result in results:
|
||||
if verify_token(x_api_token, result.token):
|
||||
valid = True
|
||||
LOG.debug("Token is valid")
|
||||
break
|
||||
|
||||
if not valid:
|
||||
LOG.debug("Token is not valid.")
|
||||
raise HTTPException(
|
||||
status_code=401, detail="unauthorized. invalid api token."
|
||||
)
|
||||
return x_api_token
|
||||
|
||||
LOG.info("Initializing app.")
|
||||
|
||||
backend_api = APIRouter(
|
||||
prefix=f"/api/{API_VERSION}",
|
||||
dependencies=[Depends(validate_token)],
|
||||
)
|
||||
|
||||
backend_api.include_router(get_audit_api(get_db_session))
|
||||
backend_api.include_router(get_clients_api(get_db_session))
|
||||
backend_api.include_router(get_policy_api(get_db_session))
|
||||
backend_api.include_router(get_secrets_api(get_db_session))
|
||||
|
||||
return backend_api
|
||||
Reference in New Issue
Block a user