service.py 5.7 KB

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