-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
184 lines (152 loc) · 6.17 KB
/
Copy pathmain.py
File metadata and controls
184 lines (152 loc) · 6.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
"""
FW Builder v3 — 固件自动化构建平台(多用户 + Authentik OIDC)
启动入口:python main.py
"""
import os
import sys
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
# 内部模块
from config_store import load_config, save_config, CONFIG_PATH
from models_user import UserStore
from auth_config import load_auth_config
from auth import (
init_oidc, get_current_user, require_admin,
login_page, auth_callback, logout_page
)
from triggers import start_scheduler, stop_scheduler
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger("fw-builder")
# ── 全局状态 ──────────────────────────────────────────────
CONFIG = {}
AUTH_CONFIG = {}
USER_STORE: UserStore = None
OIDC_CLIENT = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global CONFIG, AUTH_CONFIG, USER_STORE, OIDC_CLIENT
log.info("=" * 60)
log.info("FW Builder v3 starting...")
log.info("=" * 60)
# 1. 加载主配置
CONFIG = load_config()
log.info(f"Config loaded from {CONFIG_PATH}")
# 2. 加载认证配置
AUTH_CONFIG = load_auth_config(CONFIG)
mode = AUTH_CONFIG.get("mode", "none")
log.info(f"Auth mode: {mode}")
# 3. 初始化用户存储
users_path = os.path.join(os.path.dirname(CONFIG_PATH), "_users.yaml")
USER_STORE = UserStore(users_path)
USER_STORE.load()
log.info(f"Users loaded: {len(USER_STORE.list_users())} user(s)")
# 4. 初始化 OIDC(如果启用)
if AUTH_CONFIG.get("oidc", {}).get("enabled"):
try:
OIDC_CLIENT = init_oidc(AUTH_CONFIG["oidc"])
log.info("OIDC client initialized ✅")
except Exception as e:
log.error(f"OIDC init FAILED: {e}")
log.warning("Falling back to 'none' auth mode")
AUTH_CONFIG["mode"] = "none"
else:
log.info("OIDC disabled — running in single-user mode")
# 5. 启动定时调度器
try:
start_scheduler(CONFIG)
log.info("Scheduler started ✅")
except Exception as e:
log.warning(f"Scheduler start failed: {e}")
# 6. 注入 app.state
app.state.config = CONFIG
app.state.auth_config = AUTH_CONFIG
app.state.user_store = USER_STORE
app.state.oidc_client = OIDC_CLIENT
log.info("FW Builder v3 READY 🚀")
log.info(f" Web UI : http://{CONFIG['server']['host']}:{CONFIG['server']['port']}")
log.info(f" Auth : {mode}")
yield
# ── 关闭 ──
log.info("FW Builder shutting down...")
stop_scheduler()
if USER_STORE:
USER_STORE.save()
log.info("Bye 👋")
# ── 创建 FastAPI 应用 ─────────────────────────────────────
app = FastAPI(
title="FW Builder",
description="固件自动化构建平台 — 多用户 + Authentik OIDC",
version="3.0.0",
lifespan=lifespan,
)
# CORS — 从配置读取来源。
# 规范要求:allow_origins 含通配 "*" 时不能同时 allow_credentials=True,
# 否则浏览器会拒绝带凭据的跨域请求。此处据此自动降级。
_cors_cfg = load_config().get("server", {})
_cors_origins = _cors_cfg.get("cors_origins", ["*"])
_cors_allow_credentials = "*" not in _cors_origins
app.add_middleware(
CORSMiddleware,
allow_origins=_cors_origins,
allow_credentials=_cors_allow_credentials,
allow_methods=["*"],
allow_headers=["*"],
)
# ════════════════════════════════════════════════════════
# 路由注册 —— 顺序极其重要!
# 原则:具体路由在前,通配路由在后
# ════════════════════════════════════════════════════════
# ── 0. 先导入所有 router ──
from routes_api import router as api_router
from routes_ui import router as ui_router
from webhook_routes import router as webhook_router
from routes_users import router as users_router
# ── 1. 具体路由:健康检查(最先!)──
@app.get("/health")
async def health():
return {
"status": "ok",
"version": "3.0.0",
"auth_mode": AUTH_CONFIG.get("mode", "none"),
"users": len(USER_STORE.list_users()) if USER_STORE else 0,
}
# ── 2. 具体路由:认证回调(在通配之前!)──
app.add_api_route("/login", login_page, methods=["GET"], name="login")
app.add_api_route("/auth/callback", auth_callback, methods=["GET"], name="auth_callback")
app.add_api_route("/logout", logout_page, methods=["GET"], name="logout")
# ── 3. API 路由(/api/*,都比 /hook/{path:path} 更具体)──
app.include_router(api_router, prefix="/api")
# ── 4. 用户管理(/api/users/*)──
app.include_router(users_router)
# ── 5. Web UI 页面(/page/*)──
app.include_router(ui_router)
# ── 6. Webhook 通配路由(必须最后!/hook/{path:path})──
app.include_router(webhook_router)
# ── 7. 静态文件 ──
static_dir = os.path.join(os.path.dirname(__file__), "static")
if os.path.isdir(static_dir):
app.mount("/static", StaticFiles(directory=static_dir), name="static")
# ── 直接运行 ──────────────────────────────────────────────
if __name__ == "__main__":
import uvicorn
# 注意:模块级 CONFIG 在 lifespan 前仍为空,这里显式加载以读取 config.yaml
_cfg = load_config()
server_cfg = _cfg.get("server", {})
host = server_cfg.get("host", "127.0.0.1")
port = server_cfg.get("port", 8000)
debug = server_cfg.get("debug", False)
uvicorn.run(
"main:app",
host=host,
port=port,
reload=debug,
log_level="info",
)