@app.middleware("http")
async def cors_middleware(request: Request, call_next):
    print("CORS 中间件 start")

    # 处理 OPTIONS 预检请求
    if request.method == "OPTIONS":
        from fastapi.responses import Response
        response = Response()
    else:
        response = await call_next(request)

    # 添加 CORS 响应头
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers["Access-Control-Allow-Methods"] = "*"
    response.headers["Access-Control-Allow-Headers"] = "*"

    print("CORS 中间件 end")
    return response


# ================= 日志中间件(文件写入版) =================
@app.middleware("http")
async def log_user_request(request: Request, call_next):
    print("日志中间件 start")

    auth_header = request.headers.get("Authorization")
    username = "未登录用户"

    if auth_header and auth_header.startswith("Bearer "):
        token = auth_header.split(" ")[1]
        payload = verify_token(token)  # 你已有函数
        if payload and "sub" in payload:
            username = payload.get("sub")

    client_ip = request.headers.get("X-Forwarded-For", request.client.host)
    req_path = request.url.path

    log_msg = f"用户: {username} | IP: {client_ip} | 访问接口: {req_path}\n"

    # 👉 原生文件写入(追加模式)
    with open("log.txt", "a", encoding="utf-8") as f:
        f.write(log_msg)

    response = await call_next(request)

    print("日志中间件 end")
    return response
posted on 2025-09-11 09:35  谢晨锋  阅读(20)  评论(0)    收藏  举报