main.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. def is_authenticated(request: Request) -> bool:
  18. return session_info.get(request.session.get('id'), {}).get('authenticated', False)
  19. @ui.page('/')
  20. def main_page(request: Request) -> None:
  21. if not is_authenticated(request):
  22. return RedirectResponse('/login')
  23. session = session_info[request.session['id']]
  24. with ui.column().classes('absolute-center items-center'):
  25. ui.label(f'Hello {session["username"]}!').classes('text-2xl')
  26. # NOTE we navigate to a new page here to be able to modify the session cookie (it is only editable while a request is en-route)
  27. # see https://github.com/zauberzeug/nicegui/issues/527 for more details
  28. ui.button('', on_click=lambda: ui.open('/logout')).props('outline round icon=logout')
  29. @ui.page('/login')
  30. def login(request: Request) -> None:
  31. def try_login() -> None: # local function to avoid passing username and password as arguments
  32. if (username.value, password.value) in users:
  33. session_info[request.session['id']] = {'username': username.value, 'authenticated': True}
  34. ui.open('/')
  35. else:
  36. ui.notify('Wrong username or password', color='negative')
  37. if is_authenticated(request):
  38. return RedirectResponse('/')
  39. request.session['id'] = str(uuid.uuid4()) # NOTE this stores a new session ID in the cookie of the client
  40. with ui.card().classes('absolute-center'):
  41. username = ui.input('Username').on('keydown.enter', try_login)
  42. password = ui.input('Password').props('type=password').on('keydown.enter', try_login)
  43. ui.button('Log in', on_click=try_login)
  44. @ui.page('/logout')
  45. def logout(request: Request) -> None:
  46. if is_authenticated(request):
  47. session_info.pop(request.session['id'])
  48. request.session['id'] = None
  49. return RedirectResponse('/login')
  50. return RedirectResponse('/')
  51. ui.run()