service.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. # (c) Nelen & Schuurmans
  2. from typing import Any
  3. from typing import Callable
  4. from typing import Dict
  5. from typing import List
  6. from typing import Optional
  7. from typing import Set
  8. from fastapi import Depends
  9. from fastapi import FastAPI
  10. from fastapi import Request
  11. from fastapi.exceptions import RequestValidationError
  12. from starlette.types import ASGIApp
  13. from clean_python import BadRequest
  14. from clean_python import Conflict
  15. from clean_python import ctx
  16. from clean_python import DoesNotExist
  17. from clean_python import Gateway
  18. from clean_python import PermissionDenied
  19. from clean_python import Unauthorized
  20. from clean_python.oauth2 import OAuth2SPAClientSettings
  21. from clean_python.oauth2 import Token
  22. from clean_python.oauth2 import TokenVerifierSettings
  23. from .error_responses import conflict_handler
  24. from .error_responses import DefaultErrorResponse
  25. from .error_responses import not_found_handler
  26. from .error_responses import permission_denied_handler
  27. from .error_responses import unauthorized_handler
  28. from .error_responses import validation_error_handler
  29. from .error_responses import ValidationErrorResponse
  30. from .fastapi_access_logger import FastAPIAccessLogger
  31. from .fastapi_access_logger import get_correlation_id
  32. from .resource import APIVersion
  33. from .resource import clean_resources
  34. from .resource import Resource
  35. from .security import get_token
  36. from .security import JWTBearerTokenSchema
  37. from .security import OAuth2SPAClientSchema
  38. from .security import set_verifier
  39. __all__ = ["Service"]
  40. def get_auth_kwargs(auth_client: Optional[OAuth2SPAClientSettings]) -> Dict[str, Any]:
  41. if auth_client is None:
  42. return {
  43. "dependencies": [Depends(JWTBearerTokenSchema()), Depends(set_context)],
  44. }
  45. else:
  46. return {
  47. "dependencies": [
  48. Depends(OAuth2SPAClientSchema(client=auth_client)),
  49. Depends(set_context),
  50. ],
  51. "swagger_ui_init_oauth": {
  52. "clientId": auth_client.client_id,
  53. "usePkceWithAuthorizationCodeGrant": True,
  54. },
  55. }
  56. async def set_context(
  57. request: Request,
  58. token: Token = Depends(get_token),
  59. ) -> None:
  60. ctx.path = request.url
  61. ctx.user = token.user
  62. ctx.tenant = token.tenant
  63. ctx.correlation_id = get_correlation_id(request)
  64. async def health_check():
  65. """Simple health check route"""
  66. return {"health": "OK"}
  67. class Service:
  68. resources: List[Resource]
  69. def __init__(self, *args: Resource):
  70. self.resources = clean_resources(args)
  71. @property
  72. def versions(self) -> Set[APIVersion]:
  73. return set([x.version for x in self.resources])
  74. def _create_root_app(
  75. self,
  76. title: str,
  77. description: str,
  78. hostname: str,
  79. on_startup: Optional[List[Callable[[], Any]]] = None,
  80. access_logger_gateway: Optional[Gateway] = None,
  81. ) -> FastAPI:
  82. app = FastAPI(
  83. title=title,
  84. description=description,
  85. on_startup=on_startup,
  86. servers=[
  87. {"url": f"{x.prefix}", "description": x.description}
  88. for x in self.versions
  89. ],
  90. root_path_in_servers=False,
  91. )
  92. app.middleware("http")(
  93. FastAPIAccessLogger(
  94. hostname=hostname, gateway_override=access_logger_gateway
  95. )
  96. )
  97. app.get("/health", include_in_schema=False)(health_check)
  98. return app
  99. def _create_versioned_app(self, version: APIVersion, **kwargs) -> FastAPI:
  100. resources = [x for x in self.resources if x.version == version]
  101. app = FastAPI(
  102. version=version.prefix,
  103. tags=sorted(
  104. [x.get_openapi_tag().model_dump() for x in resources],
  105. key=lambda x: x["name"],
  106. ),
  107. **kwargs,
  108. )
  109. for resource in resources:
  110. app.include_router(
  111. resource.get_router(
  112. version,
  113. responses={
  114. "400": {"model": ValidationErrorResponse},
  115. "default": {"model": DefaultErrorResponse},
  116. },
  117. )
  118. )
  119. app.add_exception_handler(DoesNotExist, not_found_handler)
  120. app.add_exception_handler(Conflict, conflict_handler)
  121. app.add_exception_handler(RequestValidationError, validation_error_handler)
  122. app.add_exception_handler(BadRequest, validation_error_handler)
  123. app.add_exception_handler(PermissionDenied, permission_denied_handler)
  124. app.add_exception_handler(Unauthorized, unauthorized_handler)
  125. return app
  126. def create_app(
  127. self,
  128. title: str,
  129. description: str,
  130. hostname: str,
  131. auth: Optional[TokenVerifierSettings] = None,
  132. auth_client: Optional[OAuth2SPAClientSettings] = None,
  133. on_startup: Optional[List[Callable[[], Any]]] = None,
  134. access_logger_gateway: Optional[Gateway] = None,
  135. ) -> ASGIApp:
  136. set_verifier(auth)
  137. app = self._create_root_app(
  138. title=title,
  139. description=description,
  140. hostname=hostname,
  141. on_startup=on_startup,
  142. access_logger_gateway=access_logger_gateway,
  143. )
  144. kwargs = {
  145. "title": title,
  146. "description": description,
  147. **get_auth_kwargs(auth_client),
  148. }
  149. versioned_apps = {
  150. v: self._create_versioned_app(v, **kwargs) for v in self.versions
  151. }
  152. for v, versioned_app in versioned_apps.items():
  153. app.mount("/" + v.prefix, versioned_app)
  154. return app