main.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python3
  2. from typing import Dict
  3. from starlette.requests import Request
  4. from starlette.websockets import WebSocket
  5. from nicegui import ui
  6. # in reality we would load/save session info to DB
  7. session_info: Dict[str, Dict] = {}
  8. def build_content(username: str) -> None:
  9. with ui.row().classes('flex justify-center w-full mt-20'):
  10. ui.label(f'Hello {username}!').classes('text-2xl')
  11. def build_login_form() -> None:
  12. def on_login(username: str, password: str, socket: WebSocket) -> None:
  13. session_id = socket.cookies['jp_token'].split('.')[0]
  14. if (username == 'user1' and password == 'pass1') or (username == 'user2' and password == 'pass2'):
  15. session_info[session_id] = {'authenticated': True, 'user': username}
  16. ui.open('/', socket)
  17. with ui.row().classes('flex justify-center w-full mt-20'):
  18. with ui.card():
  19. username = ui.input('User Name')
  20. password = ui.input('Password').classes('w-full').props('type=password')
  21. ui.button('Log in', on_click=lambda e: on_login(username.value, password.value, e.socket))
  22. @ui.page('/')
  23. def main_page(request: Request) -> None:
  24. if session_info.get(request.session_id, {}).get('authenticated', False):
  25. build_content(session_info[request.session_id]['user'])
  26. else:
  27. build_login_form()
  28. ui.run()