55 lines
1.6 KiB
Python
55 lines
1.6 KiB
Python
from flask import Flask, send_from_directory, request, jsonify, session
|
||
|
||
from .config import PROJECT_ROOT
|
||
from .routes.chat import bp as chat_bp
|
||
from .routes.faq import bp as faq_bp
|
||
from .routes.conversation import bp as convo_bp
|
||
from .routes.auth import bp as auth_bp
|
||
from .config import SECRET_KEY
|
||
from .admin import ensure_admin_file
|
||
|
||
|
||
def create_app():
|
||
dist_dir = PROJECT_ROOT / "frontend" / "dist"
|
||
app = Flask(
|
||
__name__,
|
||
static_folder=str(dist_dir),
|
||
template_folder=str(dist_dir),
|
||
)
|
||
|
||
app.secret_key = SECRET_KEY
|
||
|
||
# 确保管理员文件存在(仅存储哈希)
|
||
ensure_admin_file()
|
||
|
||
# 注册路由
|
||
app.register_blueprint(auth_bp)
|
||
app.register_blueprint(chat_bp)
|
||
app.register_blueprint(faq_bp)
|
||
app.register_blueprint(convo_bp)
|
||
|
||
@app.before_request
|
||
def require_login():
|
||
# 仅保护 API,登录接口与静态资源除外
|
||
path = request.path or ""
|
||
if request.method == "OPTIONS":
|
||
return None
|
||
if path.startswith("/api/auth"):
|
||
return None
|
||
if not path.startswith("/api"):
|
||
return None
|
||
if session.get("user"):
|
||
return None
|
||
return jsonify({"error": "未登录"}), 401
|
||
|
||
# 前端静态资源 & SPA 回退
|
||
@app.route("/", defaults={"path": ""})
|
||
@app.route("/<path:path>")
|
||
def serve_frontend(path: str):
|
||
target = dist_dir / (path or "index.html")
|
||
if target.exists():
|
||
return send_from_directory(dist_dir, path or "index.html")
|
||
return send_from_directory(dist_dir, "index.html")
|
||
|
||
return app
|