Skip to content

Commit

Permalink
Merge pull request #1501 from zauberzeug/redirect_middleware
Browse files Browse the repository at this point in the history
adhere forwarded-prefix for redirects
  • Loading branch information
falkoschindler authored Aug 28, 2023
2 parents d7fe1c1 + 433f0f2 commit 040f531
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
14 changes: 14 additions & 0 deletions nicegui/middlewares.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response


class RedirectWithPrefixMiddleware(BaseHTTPMiddleware):

async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
prefix = request.headers.get('X-Forwarded-Prefix', '')
response = await call_next(request)
if 'Location' in response.headers:
new_location = prefix + response.headers['Location']
response.headers['Location'] = new_location
return response
10 changes: 5 additions & 5 deletions nicegui/nicegui.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,16 @@
from fastapi.staticfiles import StaticFiles
from fastapi_socketio import SocketManager

from nicegui import json
from nicegui.json import NiceGUIJSONResponse

from . import (__version__, background_tasks, binding, favicon, globals, outbox, # pylint: disable=redefined-builtin
welcome)
from . import (__version__, background_tasks, binding, favicon, globals, json, # pylint: disable=redefined-builtin
outbox, welcome)
from .app import App
from .client import Client
from .dependencies import js_components, libraries
from .element import Element
from .error import error_content
from .helpers import is_file, safe_invoke
from .json import NiceGUIJSONResponse
from .middlewares import RedirectWithPrefixMiddleware
from .page import page

globals.app = app = App(default_response_class=NiceGUIJSONResponse)
Expand All @@ -29,6 +28,7 @@
globals.sio = sio = socket_manager._sio # pylint: disable=protected-access

app.add_middleware(GZipMiddleware)
app.add_middleware(RedirectWithPrefixMiddleware)
static_files = StaticFiles(
directory=(Path(__file__).parent / 'static').resolve(),
follow_symlink=True,
Expand Down
2 changes: 1 addition & 1 deletion nicegui/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from typing import Any, Dict, Iterator, Optional, Union

import aiofiles
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response

from . import background_tasks, globals, observables # pylint: disable=redefined-builtin
Expand Down

0 comments on commit 040f531

Please sign in to comment.