Skip to content

Commit

Permalink
ensure restrictions are only applied to pages
Browse files Browse the repository at this point in the history
  • Loading branch information
rodja committed Sep 17, 2023
1 parent e7f9b47 commit 3c33070
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions examples/authentication/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down

0 comments on commit 3c33070

Please sign in to comment.