|
| 1 | +""" |
| 2 | +In order to allow customization fo the Swagger UI's OAuth2 configuration, we support |
| 3 | +overriding the default handler. This is useful for adding custom parameters such as |
| 4 | +`usePkceWithAuthorizationCodeGrant` or `clientId`. |
| 5 | +
|
| 6 | +See: |
| 7 | +- https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/ |
| 8 | +""" |
| 9 | + |
| 10 | +from dataclasses import dataclass, field |
| 11 | +from typing import Optional |
| 12 | + |
| 13 | +from fastapi.openapi.docs import get_swagger_ui_html |
| 14 | +from starlette.requests import Request |
| 15 | +from starlette.responses import HTMLResponse |
| 16 | + |
| 17 | + |
| 18 | +@dataclass |
| 19 | +class SwaggerUI: |
| 20 | + """Swagger UI handler.""" |
| 21 | + |
| 22 | + openapi_url: str |
| 23 | + title: Optional[str] = "STAC API" |
| 24 | + init_oauth: dict = field(default_factory=dict) |
| 25 | + parameters: dict = field(default_factory=dict) |
| 26 | + oauth2_redirect_url: str = "/docs/oauth2-redirect" |
| 27 | + |
| 28 | + async def route(self, req: Request) -> HTMLResponse: |
| 29 | + """Route handler.""" |
| 30 | + root_path = req.scope.get("root_path", "").rstrip("/") |
| 31 | + openapi_url = root_path + self.openapi_url |
| 32 | + oauth2_redirect_url = self.oauth2_redirect_url |
| 33 | + if oauth2_redirect_url: |
| 34 | + oauth2_redirect_url = root_path + oauth2_redirect_url |
| 35 | + return get_swagger_ui_html( |
| 36 | + openapi_url=openapi_url, |
| 37 | + title=f"{self.title} - Swagger UI", |
| 38 | + oauth2_redirect_url=oauth2_redirect_url, |
| 39 | + init_oauth=self.init_oauth, |
| 40 | + swagger_ui_parameters=self.parameters, |
| 41 | + ) |
0 commit comments