Files
NqiTools/backend/app/platform/auth.py
T

127 lines
3.9 KiB
Python

"""平台登录。各功能共用这一份会话。"""
from __future__ import annotations
import base64
import logging
import uuid
from fastapi import APIRouter, HTTPException
from app.platform.client import NqiError
from app.shared.state import state
logger = logging.getLogger("nqi.auth")
router = APIRouter(prefix="/api/auth", tags=["auth"])
def _bad(message: str, status: int = 400) -> HTTPException:
return HTTPException(status_code=status, detail=message)
def _captcha_payload(session_id: str, challenge, **extra) -> dict:
encoded = base64.b64encode(challenge.captcha_png).decode("ascii")
return {
"sessionId": session_id,
"captcha": f"data:{challenge.captcha_type};base64,{encoded}",
**extra,
}
@router.post("/captcha")
async def captcha() -> dict:
from app.platform.client import NqiClient
client = NqiClient()
try:
challenge = await client.open_login()
except Exception as exc:
await client.aclose()
logger.info("打开登录页失败: %s", exc)
raise _bad("连接失败,请稍后重试") from exc
session_id = uuid.uuid4().hex
state.flows[session_id] = (client, challenge)
return _captcha_payload(session_id, challenge)
@router.post("/captcha/refresh")
async def refresh(body: dict) -> dict:
session_id = str(body.get("sessionId") or "")
pair = state.flows.get(session_id)
if pair is None:
raise _bad("验证码已失效,请重新打开登录页")
client, challenge = pair
try:
await client.refresh_captcha(challenge)
except NqiError as exc:
raise _bad(str(exc)) from exc
return _captcha_payload(session_id, challenge)
@router.post("/sms")
async def sms(body: dict) -> dict:
session_id = str(body.get("sessionId") or "")
pair = state.flows.get(session_id)
if pair is None:
raise _bad("登录已过期,请刷新验证码")
client, challenge = pair
if not challenge.config_ready:
raise _bad("请先填写账号、密码和验证码")
try:
message = await client.send_sms(challenge)
except NqiError as exc:
raise _bad(str(exc)) from exc
return {"ok": True, "message": message}
@router.post("/login")
async def login(body: dict) -> dict:
session_id = str(body.get("sessionId") or "")
pair = state.flows.get(session_id)
if pair is None:
raise _bad("验证码已失效,请刷新后重试")
client, challenge = pair
username = str(body.get("username") or "").strip()
password = str(body.get("password") or "")
captcha = str(body.get("captcha") or "").strip()
sms_code = str(body.get("smsCode") or "").strip()
if not username or not password:
raise _bad("请输入账号和密码")
if not captcha:
raise _bad("请输入验证码")
try:
if not (challenge.config_ready and sms_code):
code = await client.prepare_login(challenge, username, password, captcha)
if code == "1" and not sms_code:
return {"status": "sms_required", "message": "请获取并填写短信验证码"}
user = await client.submit_login(challenge, sms_code)
except NqiError as exc:
try:
await client.refresh_captcha(challenge)
except NqiError:
pass
challenge.config_ready = False
raise HTTPException(status_code=400, detail=str(exc)) from exc
challenge.password = ""
state.flows.pop(session_id, None)
if state.client is not None and state.client is not client:
await state.client.aclose()
state.client = client
state.user = user
return {"status": "ok", "user": user}
@router.get("/me")
async def me() -> dict:
state.require_client()
return {"user": state.user}
@router.post("/logout")
async def logout() -> dict:
if state.client is not None:
await state.client.aclose()
state.client = None
state.user = None
return {"ok": True}