Files
stand/auth/mw.py
T

30 lines
766 B
Python

from fastapi import Request
from fastapi.responses import RedirectResponse
from nicegui import app
from starlette.middleware.base import BaseHTTPMiddleware
unrestricted_page_routes = {"/login"}
class AuthMiddleware(BaseHTTPMiddleware):
"""
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):
path = request.url.path
if (
app.storage.user.get("authenticated", False)
or path in unrestricted_page_routes
or path.startswith("/_nicegui")
):
return await call_next(request)
return RedirectResponse(f"/login?redirect_to={path}")