69 lines
2.0 KiB
Python
69 lines
2.0 KiB
Python
import flet as ft
|
|
import asyncio
|
|
|
|
from app.api.auth import login, get_me
|
|
from app.state import state
|
|
|
|
def login_page(page: ft.Page, on_login_success):
|
|
username = ft.TextField(
|
|
label="Email",
|
|
on_submit=lambda _: handle_login(), # เรียก wrapper
|
|
autofocus=True
|
|
)
|
|
|
|
password = ft.TextField(
|
|
label="Password",
|
|
password=True,
|
|
can_reveal_password=True,
|
|
on_submit=lambda _: handle_login(), # เรียก wrapper
|
|
)
|
|
|
|
message = ft.Text()
|
|
|
|
# WRAPPER (sync)
|
|
def handle_login(e=None):
|
|
asyncio.create_task(do_login()) # ยิง async
|
|
|
|
# ASYNC ตัวจริง
|
|
async def do_login():
|
|
if not username.value or not password.value:
|
|
message.value = "กรุณากรอกข้อมูลให้ครบถ้วน"
|
|
message.color = ft.Colors.RED_400
|
|
page.update()
|
|
return
|
|
|
|
try:
|
|
message.value = "กำลังตรวจสอบข้อมูล..."
|
|
message.color = ft.Colors.BLUE_400
|
|
page.update()
|
|
|
|
result = await asyncio.to_thread(login, username.value, password.value)
|
|
state.access_token = result["access"]
|
|
|
|
state.user = await asyncio.to_thread(get_me, state.access_token)
|
|
|
|
await on_login_success() # ไป route
|
|
|
|
except Exception as e:
|
|
message.value = "เข้าสู่ระบบไม่สำเร็จ"
|
|
message.color = ft.Colors.RED_400
|
|
print("LOGIN ERROR:", e)
|
|
page.update()
|
|
|
|
login_button = ft.FilledButton(
|
|
"ล็อกอิน",
|
|
on_click=handle_login, # ใช้ wrapper
|
|
width=200,
|
|
)
|
|
|
|
return ft.Column(
|
|
controls=[
|
|
ft.Text("เข้าสู่ระบบ", size=24),
|
|
username,
|
|
password,
|
|
login_button,
|
|
message,
|
|
],
|
|
horizontal_alignment=ft.CrossAxisAlignment.CENTER,
|
|
spacing=20,
|
|
) |