49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
"""登录 / 鉴权状态。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from fastapi import APIRouter, Response
|
|
from pydantic import BaseModel, Field
|
|
|
|
from apps.api.auth import COOKIE_NAME, auth_disabled, issue_token
|
|
|
|
router = APIRouter(prefix="/auth", tags=["auth"])
|
|
|
|
|
|
class LoginBody(BaseModel):
|
|
password: str = Field(min_length=1, max_length=256)
|
|
|
|
|
|
@router.get("/status")
|
|
def auth_status() -> dict:
|
|
return {
|
|
"auth_required": not auth_disabled(),
|
|
"product": "比特骆驼行情采集分析",
|
|
}
|
|
|
|
|
|
@router.post("/login")
|
|
def login(body: LoginBody, response: Response) -> dict:
|
|
if auth_disabled():
|
|
return {"ok": True, "auth_required": False, "token": None}
|
|
token = issue_token(body.password)
|
|
if not token:
|
|
from fastapi import HTTPException, status
|
|
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid 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}
|
|
|
|
|
|
@router.post("/logout")
|
|
def logout(response: Response) -> dict:
|
|
response.delete_cookie(COOKIE_NAME, path="/")
|
|
return {"ok": True}
|