111 lines
4.1 KiB
Python
111 lines
4.1 KiB
Python
"""首次安装:连接数据库、建表、创建管理员,并把配置写入数据库。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import secrets
|
|
|
|
from sqlalchemy import create_engine, text
|
|
from sqlalchemy.engine import URL
|
|
|
|
from app.config import data_dir, install_file, installed
|
|
from app.db import reset_engine, session_scope
|
|
from app.models import AppSetting, User
|
|
from app.security import hash_password
|
|
|
|
_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$")
|
|
|
|
|
|
class InstallError(Exception):
|
|
pass
|
|
|
|
|
|
def _identifier(value: str, label: str) -> str:
|
|
if not _IDENT.match(value):
|
|
raise InstallError(f"{label}只能使用字母、数字和下划线")
|
|
return value
|
|
|
|
|
|
def build_postgres_url(host: str, port: int, database: str, username: str, password: str) -> str:
|
|
return URL.create(
|
|
"postgresql+psycopg",
|
|
username=username,
|
|
password=password,
|
|
host=host,
|
|
port=port,
|
|
database=database,
|
|
).render_as_string(hide_password=False)
|
|
|
|
|
|
def ensure_database(host: str, port: int, database: str, username: str, password: str) -> None:
|
|
maintenance = build_postgres_url(host, port, "postgres", username, password)
|
|
try:
|
|
checker = create_engine(maintenance, isolation_level="AUTOCOMMIT")
|
|
with checker.connect() as connection:
|
|
exists = connection.execute(
|
|
text("SELECT 1 FROM pg_database WHERE datname = :name"),
|
|
{"name": database},
|
|
).scalar()
|
|
if not exists:
|
|
connection.execute(text(f'CREATE DATABASE "{database}"'))
|
|
checker.dispose()
|
|
except Exception as exc:
|
|
raise InstallError("无法连接数据库,请检查主机、端口、账号和密码") from exc
|
|
|
|
|
|
def perform_install(body: dict) -> None:
|
|
if installed():
|
|
raise InstallError("已经安装")
|
|
admin_username = str(body.get("adminUsername") or "").strip()
|
|
admin_password = str(body.get("adminPassword") or "")
|
|
if not admin_username or not admin_password:
|
|
raise InstallError("请填写管理员账号和密码")
|
|
use_sqlite = bool(body.get("sqlite"))
|
|
data_dir().mkdir(parents=True, exist_ok=True)
|
|
if use_sqlite:
|
|
if os.environ.get("DECOM_ALLOW_SQLITE") != "1":
|
|
raise InstallError("请使用 PostgreSQL")
|
|
url = f"sqlite+pysqlite:///{(data_dir() / 'decom.db').as_posix()}"
|
|
host, port, database, username, password = "", 0, "", "", ""
|
|
else:
|
|
host = str(body.get("host") or "").strip()
|
|
database = _identifier(str(body.get("database") or "").strip(), "数据库名")
|
|
username = _identifier(str(body.get("username") or "").strip(), "数据库用户")
|
|
password = str(body.get("password") or "")
|
|
try:
|
|
port = int(body.get("port") or 0)
|
|
except (TypeError, ValueError) as exc:
|
|
raise InstallError("端口不正确") from exc
|
|
if not host or port < 1 or port > 65535 or not password:
|
|
raise InstallError("请填写完整的数据库连接")
|
|
ensure_database(host, port, database, username, password)
|
|
url = build_postgres_url(host, port, database, username, password)
|
|
install_file().write_text(json.dumps({"databaseUrl": url}, ensure_ascii=False), encoding="utf-8")
|
|
reset_engine()
|
|
try:
|
|
from app.bootstrap import migrate
|
|
|
|
migrate()
|
|
with session_scope() as session:
|
|
session.add(
|
|
AppSetting(
|
|
id=1,
|
|
login_mode="local",
|
|
credential_refresh_seconds=300,
|
|
worker_concurrency=4,
|
|
db_host=host,
|
|
db_port=port,
|
|
db_name=database,
|
|
db_user=username,
|
|
db_password=password,
|
|
jwt_secret=secrets.token_hex(32),
|
|
)
|
|
)
|
|
session.add(User(username=admin_username, password_hash=hash_password(admin_password), role="admin"))
|
|
except Exception:
|
|
install_file().unlink(missing_ok=True)
|
|
reset_engine()
|
|
raise
|