fix: 已有数据库再次安装时接上原库而不是报错
This commit is contained in:
@@ -37,10 +37,10 @@ def install_status() -> dict:
|
|||||||
@router.post("/install")
|
@router.post("/install")
|
||||||
def install(body: dict) -> dict:
|
def install(body: dict) -> dict:
|
||||||
try:
|
try:
|
||||||
perform_install(body)
|
already = perform_install(body)
|
||||||
except InstallError as exc:
|
except InstallError as exc:
|
||||||
raise _bad(str(exc)) from exc
|
raise _bad(str(exc)) from exc
|
||||||
return {"ok": True}
|
return {"ok": True, "already": already}
|
||||||
|
|
||||||
|
|
||||||
def _bad(message: str, status: int = 400) -> HTTPException:
|
def _bad(message: str, status: int = 400) -> HTTPException:
|
||||||
|
|||||||
+11
-2
@@ -7,8 +7,9 @@ import os
|
|||||||
import re
|
import re
|
||||||
import secrets
|
import secrets
|
||||||
|
|
||||||
from sqlalchemy import create_engine, text
|
from sqlalchemy import create_engine, select, text
|
||||||
from sqlalchemy.engine import URL
|
from sqlalchemy.engine import URL
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
|
||||||
from app.config import data_dir, install_file, installed
|
from app.config import data_dir, install_file, installed
|
||||||
from app.db import reset_engine, session_scope
|
from app.db import reset_engine, session_scope
|
||||||
@@ -55,7 +56,7 @@ def ensure_database(host: str, port: int, database: str, username: str, password
|
|||||||
raise InstallError("无法连接数据库,请检查主机、端口、账号和密码") from exc
|
raise InstallError("无法连接数据库,请检查主机、端口、账号和密码") from exc
|
||||||
|
|
||||||
|
|
||||||
def perform_install(body: dict) -> None:
|
def perform_install(body: dict) -> bool:
|
||||||
if installed():
|
if installed():
|
||||||
raise InstallError("已经安装")
|
raise InstallError("已经安装")
|
||||||
admin_username = str(body.get("adminUsername") or "").strip()
|
admin_username = str(body.get("adminUsername") or "").strip()
|
||||||
@@ -89,6 +90,8 @@ def perform_install(body: dict) -> None:
|
|||||||
|
|
||||||
migrate()
|
migrate()
|
||||||
with session_scope() as session:
|
with session_scope() as session:
|
||||||
|
already = session.get(AppSetting, 1) is not None
|
||||||
|
if not already:
|
||||||
session.add(
|
session.add(
|
||||||
AppSetting(
|
AppSetting(
|
||||||
id=1,
|
id=1,
|
||||||
@@ -103,7 +106,13 @@ def perform_install(body: dict) -> None:
|
|||||||
jwt_secret=secrets.token_hex(32),
|
jwt_secret=secrets.token_hex(32),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
if session.scalar(select(User).where(User.username == admin_username)) is None:
|
||||||
session.add(User(username=admin_username, password_hash=hash_password(admin_password), role="admin"))
|
session.add(User(username=admin_username, password_hash=hash_password(admin_password), role="admin"))
|
||||||
|
return already
|
||||||
|
except IntegrityError as exc:
|
||||||
|
install_file().unlink(missing_ok=True)
|
||||||
|
reset_engine()
|
||||||
|
raise InstallError("这个数据库已经安装过") from exc
|
||||||
except Exception:
|
except Exception:
|
||||||
install_file().unlink(missing_ok=True)
|
install_file().unlink(missing_ok=True)
|
||||||
reset_engine()
|
reset_engine()
|
||||||
|
|||||||
@@ -43,6 +43,21 @@ def client():
|
|||||||
shutil.rmtree(TEST_DATA)
|
shutil.rmtree(TEST_DATA)
|
||||||
|
|
||||||
|
|
||||||
|
def test_install_again_uses_existing_database(client: TestClient):
|
||||||
|
from app.config import install_file
|
||||||
|
from app.db import reset_engine
|
||||||
|
|
||||||
|
install_file().unlink()
|
||||||
|
reset_engine()
|
||||||
|
again = client.post("/api/install", json={"sqlite": True, "adminUsername": "other", "adminPassword": "other-pass"})
|
||||||
|
assert again.status_code == 200
|
||||||
|
assert again.json()["already"] is True
|
||||||
|
logged = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
|
||||||
|
assert logged.status_code == 200
|
||||||
|
rejected = client.post("/api/auth/local", json={"username": "other", "password": "other-pass"})
|
||||||
|
assert rejected.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
def test_period_bounds():
|
def test_period_bounds():
|
||||||
assert check_period(1) == 1
|
assert check_period(1) == 1
|
||||||
assert check_period(31) == 31
|
assert check_period(31) == 31
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted, ref } from "vue";
|
import { onMounted, ref } from "vue";
|
||||||
import { useRouter } from "vue-router";
|
import { useRoute, useRouter } from "vue-router";
|
||||||
import { NAlert, NButton, NInput } from "naive-ui";
|
import { NAlert, NButton, NInput } from "naive-ui";
|
||||||
import { api, saveSession } from "../../shared/http";
|
import { api, saveSession } from "../../shared/http";
|
||||||
import ThemeButton from "../../shell/ThemeButton.vue";
|
import ThemeButton from "../../shell/ThemeButton.vue";
|
||||||
|
|
||||||
const props = defineProps<{ purpose?: "login" | "pool" }>();
|
const props = defineProps<{ purpose?: "login" | "pool" }>();
|
||||||
const emit = defineEmits<{ done: [] }>();
|
const emit = defineEmits<{ done: [] }>();
|
||||||
|
const route = useRoute();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const mode = ref("local");
|
const mode = ref("local");
|
||||||
const username = ref("");
|
const username = ref("");
|
||||||
@@ -137,6 +138,7 @@ async function finishNqi() {
|
|||||||
<div class="brand-mark" aria-hidden="true">D</div>
|
<div class="brand-mark" aria-hidden="true">D</div>
|
||||||
<h1>{{ purpose === "pool" ? "添加账号" : "DecomEval" }}</h1>
|
<h1>{{ purpose === "pool" ? "添加账号" : "DecomEval" }}</h1>
|
||||||
</div>
|
</div>
|
||||||
|
<n-alert v-if="route.query.notice === 'already'" type="info" style="margin-bottom: 12px">这个数据库已经安装过,请使用原来的管理员账号登录。</n-alert>
|
||||||
<n-alert v-if="errorText" type="error" style="margin-bottom: 12px">{{ errorText }}</n-alert>
|
<n-alert v-if="errorText" type="error" style="margin-bottom: 12px">{{ errorText }}</n-alert>
|
||||||
<div class="form-grid">
|
<div class="form-grid">
|
||||||
<label>账号</label>
|
<label>账号</label>
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ async function submit() {
|
|||||||
busy.value = true;
|
busy.value = true;
|
||||||
errorText.value = "";
|
errorText.value = "";
|
||||||
try {
|
try {
|
||||||
await api("/api/install", {
|
const result = await api<{ already?: boolean }>("/api/install", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
host: host.value,
|
host: host.value,
|
||||||
@@ -53,7 +53,7 @@ async function submit() {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
markInstalled();
|
markInstalled();
|
||||||
router.push("/login");
|
router.push(result.already ? { path: "/login", query: { notice: "already" } } : "/login");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
errorText.value = error instanceof Error ? error.message : "安装失败";
|
errorText.value = error instanceof Error ? error.message : "安装失败";
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
Reference in New Issue
Block a user