feat: create NAV_ADMIN user if missing; optional password sync from env
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -87,6 +87,7 @@ def create_app() -> Flask:
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
_ensure_default_user()
|
||||
_ensure_admin_from_env()
|
||||
|
||||
@app.route("/login", methods=["GET", "POST"])
|
||||
def login():
|
||||
@@ -327,6 +328,32 @@ def _ensure_default_user() -> None:
|
||||
)
|
||||
|
||||
|
||||
def _ensure_admin_from_env() -> None:
|
||||
"""库中已有用户后,.env 里的管理员账号不会自动覆盖旧库;若配置了用户名且尚不存在则补建。"""
|
||||
username = (os.environ.get("NAV_ADMIN_USERNAME") or "").strip()
|
||||
password = os.environ.get("NAV_ADMIN_PASSWORD")
|
||||
if not username or password is None or password == "":
|
||||
return
|
||||
existing = User.query.filter_by(username=username).first()
|
||||
if existing:
|
||||
if os.environ.get("NAV_ADMIN_UPDATE_PASSWORD") == "1":
|
||||
existing.set_password(password)
|
||||
db.session.commit()
|
||||
print(
|
||||
f"[nav] 已按 NAV_ADMIN_UPDATE_PASSWORD=1 更新用户「{username}」的登录密码。",
|
||||
flush=True,
|
||||
)
|
||||
return
|
||||
u = User(username=username)
|
||||
u.set_password(password)
|
||||
db.session.add(u)
|
||||
db.session.commit()
|
||||
print(
|
||||
f"[nav] 已从环境变量创建用户「{username}」(此前库中无此用户名)。",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
app = create_app()
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user