mirror of
https://github.com/lnbits/lnbits-legend.git
synced 2025-02-23 22:47:05 +01:00
feat: show content by accepted type
This commit is contained in:
parent
af212c820c
commit
1d0fcaa579
1 changed files with 32 additions and 11 deletions
|
@ -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.
|
||||
|
|
Loading…
Add table
Reference in a new issue