fix: show login flashes and CSRF errors; proxy and cookie options for HTTPS deploys

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-05-12 15:53:12 +08:00
parent e3b9fca45d
commit a5e1e94fb2
4 changed files with 45 additions and 0 deletions
+24
View File
@@ -6,6 +6,7 @@ from typing import Optional
from flask import Flask, flash, redirect, render_template, request, url_for
from flask_login import LoginManager, current_user, login_required, login_user, logout_user
from flask_wtf.csrf import CSRFProtect
from werkzeug.middleware.proxy_fix import ProxyFix
from forms import GroupForm, LoginForm, ServiceForm
from models import Service, ServiceGroup, User, db
@@ -63,6 +64,16 @@ def create_app() -> Flask:
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["WTF_CSRF_TIME_LIMIT"] = None
if os.environ.get("NAV_SESSION_COOKIE_SECURE") == "1":
app.config["SESSION_COOKIE_SECURE"] = True
app.config["REMEMBER_COOKIE_SECURE"] = True
trusted = os.environ.get("NAV_CSRF_TRUSTED_ORIGINS", "").strip()
if trusted:
app.config["WTF_CSRF_TRUSTED_ORIGINS"] = [
o.strip() for o in trusted.split(",") if o.strip()
]
db.init_app(app)
login_manager.init_app(app)
login_manager.login_view = "login"
@@ -271,6 +282,19 @@ def create_app() -> Flask:
flash("服务已删除", "success")
return redirect(url_for("admin_services"))
if os.environ.get("NAV_TRUST_PROXY") == "1":
app.wsgi_app = ProxyFix(
app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1, x_prefix=1
)
if not os.environ.get("NAV_SECRET_KEY"):
print(
"[nav] 警告: 未设置 NAV_SECRET_KEY。"
"若使用 gunicorn/uwsgi 等多 worker,或未固定密钥,登录后会话会失效;"
"请在环境变量中配置随机 NAV_SECRET_KEY。",
flush=True,
)
return app