main.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env python3
  2. """This is just a simple authentication example.
  3. Please see the `OAuth2 example at FastAPI <https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/>`_ or
  4. use the great `Authlib package <https://docs.authlib.org/en/v0.13/client/starlette.html#using-fastapi>`_ to implement a classing real authentication system.
  5. Here we just demonstrate the NiceGUI integration.
  6. """
  7. from typing import Optional
  8. from fastapi import Request
  9. from fastapi.responses import RedirectResponse
  10. from starlette.middleware.base import BaseHTTPMiddleware
  11. from nicegui import Client, app, ui
  12. # in reality users passwords would obviously need to be hashed
  13. passwords = {'user1': 'pass1', 'user2': 'pass2'}
  14. unrestricted_page_routes = {'/login'}
  15. class AuthMiddleware(BaseHTTPMiddleware):
  16. """This middleware restricts access to all NiceGUI pages.
  17. It redirects the user to the login page if they are not authenticated.
  18. """
  19. async def dispatch(self, request: Request, call_next):
  20. if not app.storage.user.get('authenticated', False):
  21. if request.url.path in Client.page_routes.values() and request.url.path not in unrestricted_page_routes:
  22. app.storage.user['referrer_path'] = request.url.path # remember where the user wanted to go
  23. return RedirectResponse('/login')
  24. return await call_next(request)
  25. app.add_middleware(AuthMiddleware)
  26. @ui.page('/')
  27. def main_page() -> None:
  28. with ui.column().classes('absolute-center items-center'):
  29. ui.label(f'Hello {app.storage.user["username"]}!').classes('text-2xl')
  30. ui.button(on_click=lambda: (app.storage.user.clear(), ui.open('/login')), icon='logout').props('outline round')
  31. @ui.page('/subpage')
  32. def test_page() -> None:
  33. ui.label('This is a sub page.')
  34. @ui.page('/login')
  35. def login() -> Optional[RedirectResponse]:
  36. def try_login() -> None: # local function to avoid passing username and password as arguments
  37. if passwords.get(username.value) == password.value:
  38. app.storage.user.update({'username': username.value, 'authenticated': True})
  39. ui.open(app.storage.user.get('referrer_path', '/')) # go back to where the user wanted to go
  40. else:
  41. ui.notify('Wrong username or password', color='negative')
  42. if app.storage.user.get('authenticated', False):
  43. return RedirectResponse('/')
  44. with ui.card().classes('absolute-center'):
  45. username = ui.input('Username').on('keydown.enter', try_login)
  46. password = ui.input('Password', password=True, password_toggle_button=True).on('keydown.enter', try_login)
  47. ui.button('Log in', on_click=try_login)
  48. return None
  49. ui.run(storage_secret='THIS_NEEDS_TO_BE_CHANGED')