# main.py · GHCS后端 · CORS修复版 · 2026-06-04

## 用法

全选 → 复制 → 粘贴到 VS Code 的 [main.py](http://main.py) → ⌘+S 保存

```python
from fastapi import FastAPI, Depends, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from auth import (
    ADMIN_USERNAME, ADMIN_PASSWORD_HASH,
    create_access_token, verify_token, verify_password
)
from heartbeat_router import router as heartbeat_router
from logs_router import router as logs_router
from models_router import router as models_router
from servers_router import router as servers_router
from deploy_router import router as deploy_router
from api_keys import router as api_keys_router
from log_middleware import RequestLogMiddleware

app = FastAPI(title="GHCS Console API", version="0.1.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "http://localhost:3002"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.add_middleware(RequestLogMiddleware)

app.include_router(heartbeat_router)
app.include_router(logs_router)
app.include_router(models_router)
app.include_router(servers_router)
app.include_router(deploy_router)
app.include_router(api_keys_router)

class LoginRequest(BaseModel):
    username: str
    password: str

@app.get("/")
async def root():
    return {
        "system": "GHCS · 光湖作战系统",
        "version": "v0.1",
        "owner": "TCS-GL-0016∞ · Awen",
        "repo": "https://guanghulab.com/code/awen/ghcs",
        "server": "43.139.207.172 · 4核4GB · Ubuntu 24.04",
        "domain": "guanghutcs.top",
        "belongs_to": "光湖语言世界 · 现实执行层",
        "sovereignty": "本系统及全部代码归 Awen(TCS-GL-0016∞) 所有"
    }

@app.get("/health")
async def health():
    return {"status": "ok"}

@app.post("/api/login")
async def login(req: LoginRequest):
    if req.username != ADMIN_USERNAME:
        raise HTTPException(status_code=401, detail="wrong credentials")
    if not verify_password(req.password, ADMIN_PASSWORD_HASH):
        raise HTTPException(status_code=401, detail="wrong credentials")
    token = create_access_token(req.username)
    return {"access_token": token, "token_type": "bearer"}

@app.get("/api/me")
async def me(username: str = Depends(verify_token)):
    return {"username": username, "role": "admin"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="127.0.0.1", port=5002, reload=True)
```

## 改了什么

- 删除重复的 `from fastapi.middleware.cors import CORSMiddleware`
- 两次 CORS 中间件合并为一次，两个 origin 写在一起
- `RequestLogMiddleware` 放在 CORS 之后