44 lines
1.2 KiB
Python
44 lines
1.2 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
认证 API:登录(无需 token)。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import uuid
|
||
|
||
from fastapi import APIRouter, HTTPException, Request, Response, status
|
||
|
||
from server import config, db
|
||
from server.models import LoginRequest, LoginResponse
|
||
from server.api.deps import parse_body
|
||
|
||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||
|
||
|
||
@router.post("/login", response_model=LoginResponse)
|
||
async def login(request: Request, response: Response):
|
||
"""
|
||
登录接口(支持 JSON 和 form-data):
|
||
- 校验用户名/密码
|
||
- 生成 token,写入数据库
|
||
- 通过 Set-Cookie 返回 auth_token,前端后续请求自动携带
|
||
- 下一次登录会生成新 token,旧 token 自动失效
|
||
"""
|
||
req = LoginRequest(**(await parse_body(request)))
|
||
|
||
if req.username != config.ADMIN_USERNAME or req.password != config.ADMIN_PASSWORD:
|
||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户名或密码错误")
|
||
|
||
token = uuid.uuid4().hex
|
||
db.set_auth_token(req.username, token)
|
||
|
||
response.set_cookie(
|
||
key="auth_token",
|
||
value=token,
|
||
httponly=True,
|
||
max_age=365 * 24 * 60 * 60,
|
||
samesite="lax",
|
||
)
|
||
|
||
return LoginResponse(token=token)
|