-
-
Notifications
You must be signed in to change notification settings - Fork 649
/
Copy pathmain.py
executable file
·74 lines (53 loc) · 2.76 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python3
"""This is just a simple authentication example.
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.
Here we just demonstrate the NiceGUI integration.
"""
from typing import Optional
from fastapi import Request
from fastapi.responses import RedirectResponse
from starlette.middleware.base import BaseHTTPMiddleware
from nicegui import app, ui
# in reality users passwords would obviously need to be hashed
passwords = {'user1': 'pass1', 'user2': 'pass2'}
unrestricted_page_routes = {'/login'}
class AuthMiddleware(BaseHTTPMiddleware):
"""This middleware restricts access to all NiceGUI pages.
It redirects the user to the login page if they are not authenticated.
"""
async def dispatch(self, request: Request, call_next):
if not app.storage.user.get('authenticated', False):
if not request.url.path.startswith('/_nicegui') and request.url.path not in unrestricted_page_routes:
app.storage.user['referrer_path'] = request.url.path # remember where the user wanted to go
return RedirectResponse('/login')
return await call_next(request)
app.add_middleware(AuthMiddleware)
@ui.page('/')
def main_page() -> None:
def logout() -> None:
app.storage.user.clear()
ui.navigate.to('/login')
with ui.column().classes('absolute-center items-center'):
ui.label(f'Hello {app.storage.user["username"]}!').classes('text-2xl')
ui.button(on_click=logout, icon='logout').props('outline round')
@ui.page('/subpage')
def test_page() -> None:
ui.label('This is a sub page.')
@ui.page('/login')
def login() -> Optional[RedirectResponse]:
def try_login() -> None: # local function to avoid passing username and password as arguments
if passwords.get(username.value) == password.value:
app.storage.user.update({'username': username.value, 'authenticated': True})
ui.navigate.to(app.storage.user.get('referrer_path', '/')) # go back to where the user wanted to go
else:
ui.notify('Wrong username or password', color='negative')
if app.storage.user.get('authenticated', False):
return RedirectResponse('/')
with ui.card().classes('absolute-center'):
username = ui.input('Username').on('keydown.enter', try_login)
password = ui.input('Password', password=True, password_toggle_button=True).on('keydown.enter', try_login)
ui.button('Log in', on_click=try_login)
return None
if __name__ in {'__main__', '__mp_main__'}:
ui.run(storage_secret='THIS_NEEDS_TO_BE_CHANGED')