main.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env python3
  2. '''This is only a very simple authentication example which stores session IDs in memory and does not do any password hashing.
  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 real authentication system.
  5. Here we just demonstrate the NiceGUI integration.
  6. '''
  7. import uuid
  8. from typing import Dict
  9. from fastapi import Request
  10. from fastapi.responses import RedirectResponse
  11. from starlette.middleware.sessions import SessionMiddleware
  12. from nicegui import app, ui
  13. app.add_middleware(SessionMiddleware, secret_key='some_random_string') # use your own secret key here
  14. # in reality users and session_info would be persistent (e.g. database, file, ...) and passwords obviously hashed
  15. users = [('user1', 'pass1'), ('user2', 'pass2')]
  16. session_info: Dict[str, Dict] = {}
  17. @ui.page('/')
  18. def main_page(request: Request) -> None:
  19. if is_authenticated(request):
  20. session = session_info[request.session['id']]
  21. with ui.row().classes('absolute-center'):
  22. ui.label(f'Hello {session["username"]}!').classes('text-2xl')
  23. else:
  24. return RedirectResponse('/login')
  25. @ui.page('/login')
  26. def login(request: Request) -> None:
  27. if is_authenticated(request):
  28. return RedirectResponse('/')
  29. request.session['id'] = str(uuid.uuid4()) # NOTE this stores a new session ID in the cookie of the client
  30. with ui.card().classes('absolute-center'):
  31. username = ui.input('Username')
  32. password = ui.input('Password').classes('w-full').props('type=password')
  33. ui.button('Log in', on_click=lambda: try_login(request.session['id'], username.value, password.value))
  34. def is_authenticated(request: Request) -> bool:
  35. return session_info.get(request.session.get('id'), {}).get('authenticated', False)
  36. def try_login(session_id: str, username: str, password: str) -> None:
  37. if (username, password) in users:
  38. session_info[session_id] = {'username': username, 'authenticated': True}
  39. ui.open('/')
  40. ui.run()