main.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #!/usr/bin/env python3
  2. '''This is a just 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. users = [('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'))) \
  18. .props('outline round icon=logout')
  19. @ui.page('/login')
  20. def login() -> None:
  21. def try_login() -> None: # local function to avoid passing username and password as arguments
  22. if (username.value, password.value) in users:
  23. app.storage.user.update({'username': username.value, 'authenticated': True})
  24. ui.open('/')
  25. else:
  26. ui.notify('Wrong username or password', color='negative')
  27. if app.storage.user.get('authenticated', False):
  28. return RedirectResponse('/')
  29. with ui.card().classes('absolute-center'):
  30. username = ui.input('Username').on('keydown.enter', try_login)
  31. password = ui.input('Password').props('type=password').on('keydown.enter', try_login)
  32. ui.button('Log in', on_click=try_login)
  33. ui.run()