main.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env python3
  2. """This is just a very 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 fastapi.responses import RedirectResponse
  8. from nicegui import app, ui
  9. # in reality users passwords would obviously need to be hashed
  10. passwords = {'user1': 'pass1', 'user2': 'pass2'}
  11. @ui.page('/')
  12. def main_page() -> None:
  13. if not app.storage.user.get('authenticated', False):
  14. return RedirectResponse('/login')
  15. with ui.column().classes('absolute-center items-center'):
  16. ui.label(f'Hello {app.storage.user["username"]}!').classes('text-2xl')
  17. ui.button(on_click=lambda: (app.storage.user.clear(), ui.open('/login'))).props('outline round icon=logout')
  18. @ui.page('/login')
  19. def login() -> None:
  20. def try_login() -> None: # local function to avoid passing username and password as arguments
  21. if passwords.get(username.value) == password.value:
  22. app.storage.user.update({'username': username.value, 'authenticated': True})
  23. ui.open('/')
  24. else:
  25. ui.notify('Wrong username or password', color='negative')
  26. if app.storage.user.get('authenticated', False):
  27. return RedirectResponse('/')
  28. with ui.card().classes('absolute-center'):
  29. username = ui.input('Username').on('keydown.enter', try_login)
  30. password = ui.input('Password').on('keydown.enter', try_login).props('type=password')
  31. ui.button('Log in', on_click=try_login)
  32. ui.run(storage_secret='THIS_NEEDS_TO_BE_CHANGED')