Files
market_intel/apps/api/routes/auth.py
T
2026-08-02 08:56:54 +08:00

59 lines
1.6 KiB
Python

"""登录 / 鉴权状态。"""
from __future__ import annotations
from fastapi import APIRouter, HTTPException, Response, status
from pydantic import BaseModel, Field
from apps.api.auth import COOKIE_NAME, auth_disabled, issue_token
from packages.config import get_settings
router = APIRouter(prefix="/auth", tags=["auth"])
class LoginBody(BaseModel):
username: str = Field(default="admin", min_length=1, max_length=64)
password: str = Field(min_length=1, max_length=256)
@router.get("/status")
def auth_status() -> dict:
s = get_settings()
return {
"auth_required": not auth_disabled(),
"product": "比特骆驼行情采集分析",
"username": s.admin_username,
}
@router.post("/login")
def login(body: LoginBody, response: Response) -> dict:
if auth_disabled():
return {"ok": True, "auth_required": False, "token": None, "username": body.username}
token = issue_token(body.username.strip(), body.password)
if not token:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid username or password",
)
response.set_cookie(
key=COOKIE_NAME,
value=token,
httponly=True,
samesite="lax",
max_age=7 * 24 * 3600,
path="/",
)
return {
"ok": True,
"auth_required": True,
"token": token,
"username": body.username.strip(),
}
@router.post("/logout")
def logout(response: Response) -> dict:
response.delete_cookie(COOKIE_NAME, path="/")
return {"ok": True}