Files
api-copp/web/info.py
2026-03-23 21:28:10 +05:00

50 lines
1.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import os
import httpx
import flet as ft
API_URL = os.getenv("API_URL", "http://api:8000")
_TOKEN_KEY = "auth_token"
class AuthService:
"""Сервис авторизации: логин, логаут, проверка токена."""
def __init__(self, page: ft.Page):
self._page = page
async def login(self, username: str, password: str) -> str | None:
"""
Отправляет запрос на POST /auth/login.
Возвращает None при успехе, строку с ошибкой при неудаче.
"""
try:
async with httpx.AsyncClient(base_url=API_URL, timeout=10) as client:
resp = await client.post(
"/auth/login",
data={"username": username, "password": password},
)
if resp.status_code == 200:
token = resp.json()["access_token"]
self._page.session.set(_TOKEN_KEY, token)
return None
elif resp.status_code == 401:
return "Неверный логин или пароль"
else:
return f"Ошибка сервера: {resp.status_code}"
except httpx.ConnectError:
return "Не удалось подключиться к серверу"
except Exception as e:
return f"Ошибка: {e}"
async def logout(self):
"""Удаляет токен — пользователь разлогинен."""
self._page.session.remove(_TOKEN_KEY)
async def get_token(self) -> str | None:
"""Возвращает сохранённый токен или None если не авторизован."""
return self._page.session.get(_TOKEN_KEY)
async def is_authenticated(self) -> bool:
token = await self.get_token()
return token is not None and token != ""