Files
boss_dp/server/api/auth.py
Your Name 620149716d 哈哈
2026-02-12 18:17:15 +08:00

39 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.

from __future__ import annotations
import uuid
from fastapi import APIRouter, HTTPException, Response, status
from server import config, db
from server.models import LoginRequest, LoginResponse
router = APIRouter(prefix="/api/auth", tags=["auth"])
@router.post("/login", response_model=LoginResponse)
async def login(req: LoginRequest, response: Response):
"""
登录接口:
- 校验用户名/密码是否匹配 config.ADMIN_USERNAME / ADMIN_PASSWORD
- 生成一个新的 token写入数据库并通过 cookie 返回给前端
- 之前的 token 自动失效(同一用户名只保留一个有效 token
"""
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)
# 将 token 写入 cookie前端后续请求自动携带
response.set_cookie(
key="auth_token",
value=token,
httponly=True,
max_age=365 * 24 * 60 * 60, # 一年;直到下次登录前不会过期
samesite="lax",
)
return LoginResponse(token=token)