From 00d975066279456efced077d93abb173088db3ec Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 16 Jul 2026 19:06:37 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E9=A6=96=E6=AC=A1=E5=90=AF=E5=8A=A8?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E8=AE=BE=E7=BD=AE=E9=BB=98=E8=AE=A4=E5=AF=86?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新服务器无 .env 文件时,get_or_set_password() 自动: 1. 设置默认密码 admin123 2. 写入 .env 文件 3. 控制台打印提示 解决新服务器无法登录的问题。 --- app.py | 4 ++++ auth.py | 25 ++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/app.py b/app.py index 0080b4c..24ab0f3 100644 --- a/app.py +++ b/app.py @@ -13,6 +13,10 @@ from services.backup_service import set_backup_dir def create_app(): + # 确保密码已设置(首次启动自动设置默认密码) + from auth import get_or_set_password + get_or_set_password() + app = Flask(__name__) app.config.from_object(Config) app.config["SECRET_KEY"] = os.environ.get( diff --git a/auth.py b/auth.py index 840328c..ed89061 100644 --- a/auth.py +++ b/auth.py @@ -8,7 +8,7 @@ bp = Blueprint("auth", __name__) def _get_admin_creds(): import os - _ENV = "/root/socks-manager/.env" + _ENV = os.environ.get("SM_ENV_PATH", os.path.join(os.path.dirname(__file__), ".env")) pwd = os.environ.get("SM_ADMIN_PASSWORD") user = os.environ.get("SM_ADMIN_USER", "admin") if not pwd and os.path.exists(_ENV): @@ -26,6 +26,29 @@ def _get_admin_creds(): return (user, pwd or "") +def get_or_set_password(): + """启动时检查密码,如果为空则设置默认值并打印提示。""" + import os + u, p = _get_admin_creds() + if not p: + # 没有密码,设置默认值 + default_pwd = "admin123" + os.environ["SM_ADMIN_PASSWORD"] = default_pwd + os.environ["SM_ADMIN_USER"] = u + # 写入 .env 文件 + _ENV = os.environ.get("SM_ENV_PATH", os.path.join(os.path.dirname(__file__), ".env")) + try: + with open(_ENV, "w") as f: + f.write(f"SM_ADMIN_USER={u}\nSM_ADMIN_PASSWORD={default_pwd}\n") + print(f"⚠️ 密码未设置,已使用默认密码: {default_pwd}") + print(f" 配置文件: {_ENV}") + print(f" 请立即修改密码!") + except Exception as e: + print(f"⚠️ 密码未设置,默认: {default_pwd} (无法写入 .env: {e})") + return (u, default_pwd) + return (u, p) + + def login_required(f): @wraps(f) def decorated(*args, **kwargs):