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)