Falko Schindler преди 2 години
родител
ревизия
2940ff24d9
променени са 2 файла, в които са добавени 11 реда и са изтрити 12 реда
  1. 7 9
      examples/authentication/main.py
  2. 4 3
      nicegui/storage.py

+ 7 - 9
examples/authentication/main.py

@@ -1,17 +1,16 @@
 #!/usr/bin/env python3
 #!/usr/bin/env python3
-'''This is a just very simple authentication example.
+"""This is a just very simple authentication example.
 
 
 Please see the `OAuth2 example at FastAPI <https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/>`_  or
 Please see the `OAuth2 example at FastAPI <https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/>`_  or
 use the great `Authlib package <https://docs.authlib.org/en/v0.13/client/starlette.html#using-fastapi>`_ to implement a classing real authentication system.
 use the great `Authlib package <https://docs.authlib.org/en/v0.13/client/starlette.html#using-fastapi>`_ to implement a classing real authentication system.
 Here we just demonstrate the NiceGUI integration.
 Here we just demonstrate the NiceGUI integration.
-'''
-
+"""
 from fastapi.responses import RedirectResponse
 from fastapi.responses import RedirectResponse
 
 
 from nicegui import app, ui
 from nicegui import app, ui
 
 
 # in reality users passwords would obviously need to be hashed
 # in reality users passwords would obviously need to be hashed
-users = [('user1', 'pass1'), ('user2', 'pass2')]
+passwords = {'user1': 'pass1', 'user2': 'pass2'}
 
 
 
 
 @ui.page('/')
 @ui.page('/')
@@ -20,14 +19,13 @@ def main_page() -> None:
         return RedirectResponse('/login')
         return RedirectResponse('/login')
     with ui.column().classes('absolute-center items-center'):
     with ui.column().classes('absolute-center items-center'):
         ui.label(f'Hello {app.storage.user["username"]}!').classes('text-2xl')
         ui.label(f'Hello {app.storage.user["username"]}!').classes('text-2xl')
-        ui.button('', on_click=lambda: (app.storage.user.clear(), ui.open('/login'))) \
-            .props('outline round icon=logout')
+        ui.button(on_click=lambda: (app.storage.user.clear(), ui.open('/login'))).props('outline round icon=logout')
 
 
 
 
 @ui.page('/login')
 @ui.page('/login')
 def login() -> None:
 def login() -> None:
     def try_login() -> None:  # local function to avoid passing username and password as arguments
     def try_login() -> None:  # local function to avoid passing username and password as arguments
-        if (username.value, password.value) in users:
+        if passwords.get(username.value) == password.value:
             app.storage.user.update({'username': username.value, 'authenticated': True})
             app.storage.user.update({'username': username.value, 'authenticated': True})
             ui.open('/')
             ui.open('/')
         else:
         else:
@@ -37,8 +35,8 @@ def login() -> None:
         return RedirectResponse('/')
         return RedirectResponse('/')
     with ui.card().classes('absolute-center'):
     with ui.card().classes('absolute-center'):
         username = ui.input('Username').on('keydown.enter', try_login)
         username = ui.input('Username').on('keydown.enter', try_login)
-        password = ui.input('Password').props('type=password').on('keydown.enter', try_login)
+        password = ui.input('Password').on('keydown.enter', try_login).props('type=password')
         ui.button('Log in', on_click=try_login)
         ui.button('Log in', on_click=try_login)
 
 
 
 
-ui.run()
+ui.run(storage_secret='THIS_NEEDS_TO_BE_CHANGED')

+ 4 - 3
nicegui/storage.py

@@ -71,6 +71,7 @@ class PersistentDict(dict):
 
 
 
 
 class RequestTrackingMiddleware(BaseHTTPMiddleware):
 class RequestTrackingMiddleware(BaseHTTPMiddleware):
+
     async def dispatch(self, request: Request, call_next):
     async def dispatch(self, request: Request, call_next):
         request_contextvar.set(request)
         request_contextvar.set(request)
         if 'id' not in request.session:
         if 'id' not in request.session:
@@ -101,7 +102,7 @@ class Storage:
         if request.state.responded:
         if request.state.responded:
             return ReadOnlyDict(
             return ReadOnlyDict(
                 request.session,
                 request.session,
-                'the response to the browser has already been build so modifications can not be send back anymore'
+                'the response to the browser has already been built so modifications cannot be sent back anymore'
             )
             )
         return request.session
         return request.session
 
 
@@ -124,11 +125,11 @@ class Storage:
         """General storage shared between all users that is persisted on the server (where NiceGUI is executed)."""
         """General storage shared between all users that is persisted on the server (where NiceGUI is executed)."""
         return self._general
         return self._general
 
 
-    async def backup(self):
+    async def backup(self) -> None:
         await self._general.backup()
         await self._general.backup()
         await self._users.backup()
         await self._users.backup()
 
 
-    async def _loop(self):
+    async def _loop(self) -> None:
         while True:
         while True:
             await self.backup()
             await self.backup()
             await asyncio.sleep(10)
             await asyncio.sleep(10)