From 1d0fcaa5790ccc86934c423150f86e39cb112375 Mon Sep 17 00:00:00 2001 From: Vlad Stan Date: Wed, 5 Apr 2023 18:54:54 +0300 Subject: [PATCH] feat: show content by accepted type --- lnbits/middleware.py | 43 ++++++++++++++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/lnbits/middleware.py b/lnbits/middleware.py index 17da5ecf6..dc4a8875e 100644 --- a/lnbits/middleware.py +++ b/lnbits/middleware.py @@ -1,5 +1,5 @@ from http import HTTPStatus -from typing import List, Tuple +from typing import Any, List, Tuple, Union from urllib.parse import parse_qs from fastapi.responses import HTMLResponse, JSONResponse @@ -29,23 +29,19 @@ class InstalledExtensionMiddleware: _, path_name = path_elements path_type = None + headers = scope.get("headers", []) + # block path for all users if the extension is disabled if path_name in settings.lnbits_deactivated_extensions: - response = JSONResponse( - status_code=HTTPStatus.NOT_FOUND, - content={"detail": f"Extension '{path_name}' disabled"}, + response = self._response_by_accepted_type( + headers, f"Extension '{path_name}' disabled", HTTPStatus.NOT_FOUND ) await response(scope, receive, send) return if not self._user_allowed_to_extension(path_name, scope): - response = HTMLResponse( - status_code=HTTPStatus.FORBIDDEN, - content=template_renderer() - .TemplateResponse( - "error.html", {"request": {}, "err": "User not authorized."} - ) - .body, + response = self._response_by_accepted_type( + headers, "User not authorized.", HTTPStatus.FORBIDDEN ) await response(scope, receive, send) return @@ -81,6 +77,31 @@ class InstalledExtensionMiddleware: return False + def _response_by_accepted_type( + self, headers: List[Any], msg: str, status_code: HTTPStatus + ) -> Union[HTMLResponse, JSONResponse]: + accept_header: str = next( + ( + h[1].decode("UTF-8") + for h in headers + if len(h) >= 2 and h[0].decode("UTF-8") == "accept" + ), + "", + ) + + if "text/html" in [a for a in accept_header.split(",")]: + return HTMLResponse( + status_code=status_code, + content=template_renderer() + .TemplateResponse("error.html", {"request": {}, "err": msg}) + .body, + ) + + return JSONResponse( + status_code=status_code, + content={"detail": msg}, + ) + class ExtensionsRedirectMiddleware: # Extensions are allowed to specify redirect paths.