main.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 urllib.parse import quote
  8. from fastapi import Request
  9. from fastapi.responses import RedirectResponse
  10. from starlette.middleware.base import BaseHTTPMiddleware
  11. from nicegui import app, ui
  12. # in reality users passwords would obviously need to be hashed
  13. passwords = {'user1': 'pass1', 'user2': 'pass2'}
  14. class AuthMiddleware(BaseHTTPMiddleware):
  15. """This middleware redirects the user to the login page if they are not authenticated."""
  16. async def dispatch(self, request: Request, call_next):
  17. if request.url.path not in ['/login'] and not app.storage.user.get('authenticated', False):
  18. return RedirectResponse(f'/login?referer_path={quote(request.url.path)}')
  19. return await call_next(request)
  20. app.add_middleware(AuthMiddleware)
  21. @ui.page('/')
  22. def main_page() -> None:
  23. with ui.column().classes('absolute-center items-center'):
  24. ui.label(f'Hello {app.storage.user["username"]}!').classes('text-2xl')
  25. ui.button(on_click=lambda: (app.storage.user.clear(), ui.open('/login')), icon='logout').props('outline round')
  26. @ui.page('/subpage')
  27. def test_page() -> None:
  28. ui.label('This is a subpage page.')
  29. @ui.page('/login')
  30. def login(referer_path: str = '') -> None:
  31. def try_login() -> None: # local function to avoid passing username and password as arguments
  32. if passwords.get(username.value) == password.value:
  33. app.storage.user.update({'username': username.value, 'authenticated': True})
  34. ui.open(referer_path or '/')
  35. else:
  36. ui.notify('Wrong username or password', color='negative')
  37. if app.storage.user.get('authenticated', False):
  38. return RedirectResponse('/')
  39. with ui.card().classes('absolute-center'):
  40. username = ui.input('Username').on('keydown.enter', try_login)
  41. password = ui.input('Password', password=True, password_toggle_button=True).on('keydown.enter', try_login)
  42. ui.button('Log in', on_click=try_login)
  43. ui.run(storage_secret='THIS_NEEDS_TO_BE_CHANGED')