30 lines
775 B
Python
30 lines
775 B
Python
from fastapi import Request
|
|
from fastapi.responses import RedirectResponse
|
|
from nicegui import app
|
|
from starlette.middleware.base import BaseHTTPMiddleware
|
|
|
|
|
|
unrestricted_page_routes = {"/favicon.ico", "/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")
|
|
or path in unrestricted_page_routes
|
|
or path.startswith("/_nicegui")
|
|
):
|
|
return await call_next(request)
|
|
|
|
return RedirectResponse(f"/login?redirect_to={path}")
|
|
|
|
|
|
|