fix: 移除后台登录默认凭据
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user