Skip to content

Commit

Permalink
feat: referer update
Browse files Browse the repository at this point in the history
feat: referer update
  • Loading branch information
cofin authored Jul 22, 2024
2 parents 9f3a6cf + 23e7d67 commit edae468
Show file tree
Hide file tree
Showing 6 changed files with 20 additions and 13 deletions.
1 change: 1 addition & 0 deletions litestar_vite/inertia/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class InertiaHeaders(str, Enum):
PARTIAL_DATA = "X-Inertia-Partial-Data"
PARTIAL_COMPONENT = "X-Inertia-Partial-Component"
LOCATION = "X-Inertia-Location"
REFERER = "Referer"


def get_enabled_header(enabled: bool = True) -> dict[str, Any]:
Expand Down
12 changes: 6 additions & 6 deletions litestar_vite/inertia/exception_handler.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import contextlib
import re
from typing import TYPE_CHECKING, Any, cast

Expand Down Expand Up @@ -28,7 +29,6 @@
HTTP_422_UNPROCESSABLE_ENTITY,
HTTP_500_INTERNAL_SERVER_ERROR,
)
from litestar.types import Empty

from litestar_vite.inertia.response import InertiaBack, InertiaRedirect, InertiaResponse, error

Expand All @@ -44,7 +44,7 @@ class _HTTPConflictException(HTTPException):
status_code = HTTP_409_CONFLICT


def exception_to_http_response(request: Request[UserT, AuthT, StateT], exc: Exception) -> Response[Any]:
def exception_to_http_response(request: Request[UserT, AuthT, StateT], exc: Exception) -> Response[Any]: # noqa: PLR0911
"""Handler for all exceptions subclassed from HTTPException."""
inertia_enabled = getattr(request, "inertia_enabled", False) or getattr(request, "is_inertia", False)
if isinstance(exc, NotFoundError):
Expand All @@ -57,7 +57,6 @@ def exception_to_http_response(request: Request[UserT, AuthT, StateT], exc: Exce
if request.app.debug and http_exc not in (PermissionDeniedException, NotFoundError):
return cast("Response[Any]", create_debug_response(request, exc))
return cast("Response[Any]", create_exception_response(request, http_exc(detail=str(exc.__cause__))))
has_active_session = not (not request.session or request.scope["session"] is Empty)
is_inertia = getattr(request, "is_inertia", False)
status_code = getattr(exc, "status_code", HTTP_500_INTERNAL_SERVER_ERROR)
preferred_type = MediaType.HTML if inertia_enabled and not is_inertia else MediaType.JSON
Expand All @@ -67,16 +66,17 @@ def exception_to_http_response(request: Request[UserT, AuthT, StateT], exc: Exce
inertia_plugin = cast("InertiaPlugin", request.app.plugins.get("InertiaPlugin"))
if extras:
content.update({"extra": extras})
if has_active_session:
with contextlib.suppress(Exception):
flash(request, detail, category="error")
if extras and len(extras) >= 1:
message = extras[0]
default_field = f"root.{message.get('key')}" if message.get("key", None) is not None else "root" # type: ignore
error_detail = cast("str", message.get("message", detail)) # type: ignore[union-attr] # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
match = FIELD_ERR_RE.search(error_detail)
field = match.group(1) if match else default_field
if isinstance(message, dict) and has_active_session:
error(request, field, error_detail)
if isinstance(message, dict):
with contextlib.suppress(Exception):
error(request, field, error_detail)
if status_code in {HTTP_422_UNPROCESSABLE_ENTITY, HTTP_400_BAD_REQUEST} or isinstance(
exc,
PermissionDeniedException,
Expand Down
6 changes: 1 addition & 5 deletions litestar_vite/inertia/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
StateT,
UserT,
)
from litestar.types import ASGIApp
from litestar.types import ASGIApp, Receive, Scope, Send


async def redirect_on_asset_version_mismatch(request: Request[UserT, AuthT, StateT]) -> InertiaRedirect | None:
Expand All @@ -32,10 +32,6 @@ async def redirect_on_asset_version_mismatch(request: Request[UserT, AuthT, Stat
return InertiaRedirect(request, redirect_to=str(request.url))


if TYPE_CHECKING:
from litestar.types import Receive, Scope, Send


class InertiaMiddleware(AbstractMiddleware):
def __init__(self, app: ASGIApp) -> None:
super().__init__(app)
Expand Down
5 changes: 5 additions & 0 deletions litestar_vite/inertia/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ def partial_data(self) -> str | None:
"""Partial Data Reload."""
return self._get_header_value(InertiaHeaders.PARTIAL_DATA)

@cached_property
def referer(self) -> str | None:
"""Partial Data Reload."""
return self._get_header_value(InertiaHeaders.REFERER)

@cached_property
def is_partial_render(self) -> bool:
"""Is Partial Data Reload."""
Expand Down
7 changes: 6 additions & 1 deletion litestar_vite/inertia/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from litestar.connection.base import AuthT, StateT, UserT
from litestar.types import ResponseCookies, ResponseHeaders, TypeEncodersMap

from litestar_vite.inertia.request import InertiaRequest
from litestar_vite.inertia.routes import Routes

from .plugin import InertiaPlugin
Expand Down Expand Up @@ -339,8 +340,12 @@ def __init__(
"""Initialize external redirect, Set status code to 409 (required by Inertia),
and pass redirect url.
"""
referer = request.headers.get("referer", str(request.base_url))
inertia_enabled = getattr(request, "inertia_enabled", False) or getattr(request, "is_inertia", False)
if inertia_enabled:
referer = cast("InertiaRequest[Any, Any, Any]", request).inertia.referer or referer
super().__init__(
path=request.headers.get("referrer", str(request.base_url)),
path=request.headers.get("referer", str(request.base_url)),
status_code=HTTP_307_TEMPORARY_REDIRECT if request.method == "GET" else HTTP_303_SEE_OTHER,
cookies=request.cookies,
**kwargs,
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ license = { text = "MIT" }
name = "litestar-vite"
readme = "README.md"
requires-python = ">=3.8"
version = "0.2.1"
version = "0.2.2"

[project.urls]
Changelog = "https://cofin.github.io/litestar-vite/latest/changelog"
Expand Down

0 comments on commit edae468

Please sign in to comment.