fix: 移除后台登录默认凭据

This commit is contained in:
2026-07-09 16:45:09 +08:00
parent 55333445f4
commit ef24868105
5 changed files with 53 additions and 10 deletions

View File

@@ -60,8 +60,8 @@ class Settings(BaseSettings):
chat_max_queue_size: int = 20
chat_queue_timeout_seconds: int = 60
chat_active_lease_seconds: int = 900
bootstrap_admin_username: str = "admin"
bootstrap_admin_password: str = "admin123456"
bootstrap_admin_username: str = ""
bootstrap_admin_password: str = ""
bootstrap_admin_name: str = "系统管理员"

View File

@@ -15,6 +15,44 @@ from app.models.logs import AiRequestLog, OperationLog
from app.models.user import User
DEVELOPMENT_ENVS = {"local", "dev", "development", "docker", "test", "testing"}
UNSAFE_BOOTSTRAP_PASSWORDS = {
"123456",
"admin",
"admin123456",
"change-me-in-production",
"password",
"replace-with-strong-password",
}
def _is_production_env(app_env: str) -> bool:
return app_env.strip().lower() not in DEVELOPMENT_ENVS
def _get_bootstrap_admin_config() -> tuple[str, str, str]:
settings = get_settings()
username = settings.bootstrap_admin_username.strip()
password = settings.bootstrap_admin_password
name = settings.bootstrap_admin_name.strip() or username
if not username or not password:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="未配置首个管理员初始化账号,请配置 BOOTSTRAP_ADMIN_USERNAME/BOOTSTRAP_ADMIN_PASSWORD",
)
if _is_production_env(settings.app_env):
normalized_password = password.strip().lower()
if normalized_password in UNSAFE_BOOTSTRAP_PASSWORDS or len(password) < 12:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="生产环境首个管理员初始化密码不安全,请重新配置 BOOTSTRAP_ADMIN_PASSWORD",
)
return username, password, name
class AdminAuthService:
@classmethod
def login(cls, db: Session, username: str, password: str) -> dict:
@@ -47,11 +85,11 @@ class AdminAuthService:
has_admin = db.scalar(select(func.count(Admin.id))) or 0
if has_admin:
return
settings = get_settings()
username, password, name = _get_bootstrap_admin_config()
admin = Admin(
username=settings.bootstrap_admin_username,
password=hash_password(settings.bootstrap_admin_password),
name=settings.bootstrap_admin_name,
username=username,
password=hash_password(password),
name=name,
status=1,
)
db.add(admin)