refactor: 管理员账号存储在数据库,生产环境使用宿主机目录存储数据

- 管理员账号在数据库初始化时创建,不再从环境变量读取
  - 默认账号: admin / admin123
  - 首次启动时自动创建,请在登录后修改密码
- 移除 ADMIN_USERNAME 和 ADMIN_PASSWORD 环境变量
- 生产环境 MySQL 数据直接存储在宿主机 /opt/vitals/mysql_data
  - 便于备份和恢复
  - 更直观的数据管理
- 更新部署指南,添加 MySQL 数据目录创建和备份说明
- 更新 .env.example 和 README.md 反映新的配置方式

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
lzh
2026-01-23 21:16:32 +08:00
parent 18e0668941
commit 4c22a137cf
7 changed files with 98 additions and 91 deletions

View File

@@ -15,51 +15,13 @@ from uuid import uuid4
from ..core import database as db
from ..core.models import Exercise, Meal, Sleep, UserConfig, Weight, User, Reading, Invite
from ..core.auth import hash_password, verify_password, create_token, decode_token, generate_invite_code, get_token_expire_seconds
from ..core.auth import verify_password, create_token, decode_token, generate_invite_code, get_token_expire_seconds
# 初始化数据库
db.init_db()
db.migrate_auth_fields() # 迁移认证字段
def ensure_admin_user():
"""确保管理员账户存在,密码与环境变量同步"""
admin_username = os.environ.get("ADMIN_USERNAME")
admin_password = os.environ.get("ADMIN_PASSWORD")
if not admin_username or not admin_password:
return # 未配置环境变量,跳过
# 检查是否已存在该用户名
existing = db.get_user_by_name(admin_username)
new_password_hash = hash_password(admin_password)
if existing:
# 用户已存在,同步密码(环境变量优先)
if not existing.is_admin:
existing.is_admin = True
if existing.password_hash != new_password_hash:
existing.password_hash = new_password_hash
db.update_user(existing)
print(f"[Vitals] 管理员密码已从环境变量同步")
return
# 创建管理员账户
admin_user = User(
name=admin_username,
password_hash=new_password_hash,
is_admin=True,
is_active=True,
is_disabled=False,
)
db.add_user(admin_user)
print(f"[Vitals] 管理员账户 '{admin_username}' 已创建")
# 启动时创建管理员账户
ensure_admin_user()
app = FastAPI(
title="Vitals 健康管理",
description="本地优先的综合健康管理应用",