From 3c3307089cb700de3acf3d85b191d940f46d9f57 Mon Sep 17 00:00:00 2001 From: Rodja Trappe Date: Sun, 17 Sep 2023 05:47:45 +0200 Subject: [PATCH] ensure restrictions are only applied to pages --- examples/authentication/main.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/examples/authentication/main.py b/examples/authentication/main.py index 9161c66e7..eb9e6078a 100755 --- a/examples/authentication/main.py +++ b/examples/authentication/main.py @@ -12,18 +12,23 @@ from fastapi.responses import RedirectResponse from starlette.middleware.base import BaseHTTPMiddleware +import nicegui.globals from nicegui import app, ui # in reality users passwords would obviously need to be hashed passwords = {'user1': 'pass1', 'user2': 'pass2'} +unrestricted_page_routes = ['/login'] + class AuthMiddleware(BaseHTTPMiddleware): - """This middleware redirects the user to the login page if they are not authenticated.""" + """This middleware restricts access to all NiceGUI pages. + It redirects the user to the login page if they are not authenticated.""" async def dispatch(self, request: Request, call_next): - if request.url.path not in ['/login'] and not app.storage.user.get('authenticated', False): - return RedirectResponse(f'/login?referrer_path={quote(request.url.path)}') + if not app.storage.user.get('authenticated', False): + if request.url.path in nicegui.globals.page_routes.values() and request.url.path not in unrestricted_page_routes: + return RedirectResponse(f'/login?referrer_path={quote(request.url.path)}') return await call_next(request)