Files
boss_dp/server/api/auth.py
Your Name c030902c0a 哈哈
2026-02-12 18:22:02 +08:00

44 lines
1.2 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.

# -*- 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)