feat(web): add password setup page, change password, and settings tabs

- First-time visitors see a password setup page instead of open access
- Password persisted to SQLite (env var DBX_PASSWORD takes priority)
- Add change password in settings dialog (Security tab, web only)
- Split settings dialog into Editor and Security tabs
- Argon2 hashing for all password storage
This commit is contained in:
t8y2 2026-05-05 22:22:04 +08:00
parent 8cc4dfb268
commit 0f40488bf1
10 changed files with 460 additions and 140 deletions

View File

@ -17,7 +17,7 @@ FROM --platform=$BUILDPLATFORM rust:1-bookworm AS backend
ARG TARGETARCH
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \
python3-pip gcc-aarch64-linux-gnu gcc-x86-64-linux-gnu \
build-essential cmake pkg-config perl python3-pip gcc-aarch64-linux-gnu gcc-x86-64-linux-gnu \
&& pip3 install --break-system-packages ziglang \
&& cargo install cargo-zigbuild \
&& rustup target add x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu \
@ -45,7 +45,7 @@ RUN --mount=type=cache,target=/usr/local/cargo/registry \
# Stage 3: Final image
FROM debian:bookworm-slim
ARG TARGETPLATFORM
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates libssl3 && rm -rf /var/lib/apt/lists/*
COPY --from=backend /out/${TARGETPLATFORM}/dbx-web /usr/local/bin/
COPY --from=frontend /app/dist /app/static
ENV DBX_STATIC_DIR=/app/static

View File

@ -49,6 +49,10 @@ const SCHEMA_STATEMENTS: &[&str] = &[
id INTEGER PRIMARY KEY CHECK (id = 1),
layout_json TEXT NOT NULL
)",
"CREATE TABLE IF NOT EXISTS app_settings (
id INTEGER PRIMARY KEY CHECK (id = 1),
settings_json TEXT NOT NULL
)",
];
// ---------------------------------------------------------------------------
@ -182,6 +186,36 @@ impl Storage {
}
}
// ---------------------------------------------------------------------------
// App Settings
// ---------------------------------------------------------------------------
impl Storage {
pub async fn save_password_hash(&self, hash: &str) -> Result<(), String> {
let json = serde_json::json!({ "password_hash": hash }).to_string();
sqlx::query("INSERT OR REPLACE INTO app_settings (id, settings_json) VALUES (1, ?)")
.bind(&json)
.execute(&self.db)
.await
.map_err(|e| e.to_string())?;
Ok(())
}
pub async fn load_password_hash(&self) -> Result<Option<String>, String> {
let row: Option<(String,)> = sqlx::query_as("SELECT settings_json FROM app_settings WHERE id = 1")
.fetch_optional(&self.db)
.await
.map_err(|e| e.to_string())?;
match row {
Some((json,)) => {
let v: serde_json::Value = serde_json::from_str(&json).map_err(|e| e.to_string())?;
Ok(v.get("password_hash").and_then(|v| v.as_str()).map(|s| s.to_string()))
}
None => Ok(None),
}
}
}
// ---------------------------------------------------------------------------
// AI Conversations
// ---------------------------------------------------------------------------

View File

@ -1,6 +1,8 @@
use std::sync::Arc;
use argon2::{Argon2, PasswordHash, PasswordVerifier};
use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::SaltString;
use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
use axum::extract::State;
use axum::http::{Request, StatusCode};
use axum::middleware::Next;
@ -15,22 +17,31 @@ pub struct LoginRequest {
pub password: String,
}
#[derive(Deserialize)]
pub struct ChangePasswordRequest {
pub old_password: String,
pub new_password: String,
}
#[derive(Serialize)]
pub struct AuthCheckResponse {
pub authenticated: bool,
pub required: bool,
pub setup_required: bool,
}
const MAX_ATTEMPTS: u32 = 5;
const LOCKOUT_SECS: u64 = 60;
pub async fn login(State(state): State<Arc<WebState>>, Json(body): Json<LoginRequest>) -> Result<Response, StatusCode> {
let password_hash = match &state.password_hash {
Some(h) => h,
let hash_guard = state.password_hash.read().await;
let hash_str = match hash_guard.as_deref() {
Some(h) => h.to_string(),
None => {
return Ok((StatusCode::OK, Json(serde_json::json!({"ok": true}))).into_response());
}
};
drop(hash_guard);
// Check rate limit
{
@ -47,7 +58,7 @@ pub async fn login(State(state): State<Arc<WebState>>, Json(body): Json<LoginReq
}
}
let parsed_hash = PasswordHash::new(password_hash).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let parsed_hash = PasswordHash::new(&hash_str).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if Argon2::default().verify_password(body.password.as_bytes(), &parsed_hash).is_err() {
let mut rl = state.login_rate_limit.lock().await;
@ -73,15 +84,78 @@ pub async fn login(State(state): State<Arc<WebState>>, Json(body): Json<LoginReq
Ok((StatusCode::OK, [("set-cookie", cookie.as_str())], Json(serde_json::json!({"ok": true}))).into_response())
}
pub async fn setup(State(state): State<Arc<WebState>>, Json(body): Json<LoginRequest>) -> Result<Response, StatusCode> {
// Only allow setup when no password is configured
if state.password_hash.read().await.is_some() {
return Err(StatusCode::FORBIDDEN);
}
if body.password.is_empty() {
return Err(StatusCode::BAD_REQUEST);
}
let salt = SaltString::generate(&mut OsRng);
let hash = Argon2::default()
.hash_password(body.password.as_bytes(), &salt)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.to_string();
// Save to database
state.app.storage.save_password_hash(&hash).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// Update in-memory state
*state.password_hash.write().await = Some(hash);
// Auto-login: create session
let token = uuid::Uuid::new_v4().to_string();
state.sessions.write().await.insert(token.clone());
let cookie = format!("dbx_session={token}; Path=/; HttpOnly; SameSite=Lax");
Ok((StatusCode::OK, [("set-cookie", cookie.as_str())], Json(serde_json::json!({"ok": true}))).into_response())
}
pub async fn check(State(state): State<Arc<WebState>>, req: Request<axum::body::Body>) -> Json<AuthCheckResponse> {
if state.password_hash.is_none() {
return Json(AuthCheckResponse { authenticated: true, required: false });
let has_password = state.password_hash.read().await.is_some();
if !has_password {
return Json(AuthCheckResponse { authenticated: false, required: false, setup_required: true });
}
let authenticated = match extract_session_token(&req) {
Some(token) => state.sessions.read().await.contains(&token),
None => false,
};
Json(AuthCheckResponse { authenticated, required: true })
Json(AuthCheckResponse { authenticated, required: true, setup_required: false })
}
pub async fn change_password(
State(state): State<Arc<WebState>>,
Json(body): Json<ChangePasswordRequest>,
) -> Result<Response, StatusCode> {
let hash_guard = state.password_hash.read().await;
let hash_str = match hash_guard.as_deref() {
Some(h) => h.to_string(),
None => return Err(StatusCode::BAD_REQUEST),
};
drop(hash_guard);
if body.new_password.is_empty() {
return Err(StatusCode::BAD_REQUEST);
}
let parsed_hash = PasswordHash::new(&hash_str).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if Argon2::default().verify_password(body.old_password.as_bytes(), &parsed_hash).is_err() {
return Err(StatusCode::UNAUTHORIZED);
}
let salt = SaltString::generate(&mut OsRng);
let new_hash = Argon2::default()
.hash_password(body.new_password.as_bytes(), &salt)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.to_string();
state.app.storage.save_password_hash(&new_hash).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
*state.password_hash.write().await = Some(new_hash);
Ok((StatusCode::OK, Json(serde_json::json!({"ok": true}))).into_response())
}
pub async fn logout(State(state): State<Arc<WebState>>, req: Request<axum::body::Body>) -> Response {
@ -111,7 +185,7 @@ pub async fn auth_middleware(
next: Next,
) -> Response {
// No password set — allow everything
if state.password_hash.is_none() {
if state.password_hash.read().await.is_none() {
return next.run(req).await;
}

View File

@ -46,16 +46,18 @@ async fn main() {
Arc::new(AppState::new(storage))
};
// Password hash
let password_hash = std::env::var("DBX_PASSWORD").ok().map(|pw| {
// Password hash: env var takes priority, then database
let password_hash = if let Some(pw) = std::env::var("DBX_PASSWORD").ok() {
let salt = SaltString::generate(&mut OsRng);
Argon2::default().hash_password(pw.as_bytes(), &salt).expect("Failed to hash password").to_string()
});
Some(Argon2::default().hash_password(pw.as_bytes(), &salt).expect("Failed to hash password").to_string())
} else {
app_state.storage.load_password_hash().await.unwrap_or(None)
};
let web_state = Arc::new(WebState {
app: app_state,
data_dir,
password_hash,
password_hash: RwLock::new(password_hash),
sessions: RwLock::new(HashSet::new()),
sse_channels: RwLock::new(HashMap::new()),
login_rate_limit: tokio::sync::Mutex::new(state::LoginRateLimit { fail_count: 0, locked_until: None }),
@ -69,6 +71,8 @@ async fn main() {
// Auth
.route("/auth/login", post(auth::login))
.route("/auth/check", get(auth::check))
.route("/auth/setup", post(auth::setup))
.route("/auth/change-password", post(auth::change_password))
.route("/auth/logout", post(auth::logout))
// Connection
.route("/connection/test", post(routes::connection::test_connection))

View File

@ -12,7 +12,7 @@ pub struct LoginRateLimit {
pub struct WebState {
pub app: Arc<AppState>,
pub data_dir: PathBuf,
pub password_hash: Option<String>,
pub password_hash: RwLock<Option<String>>,
pub sessions: RwLock<HashSet<String>>,
pub sse_channels: RwLock<HashMap<String, broadcast::Sender<String>>>,
pub login_rate_limit: Mutex<LoginRateLimit>,

View File

@ -59,6 +59,7 @@ const { setupFileDrop } = useFileDrop();
const isDesktop = isTauriRuntime();
const needsAuth = ref(!isDesktop);
const authenticated = ref(isDesktop);
const setupRequired = ref(false);
const showConnectionDialog = ref(false);
const showSettingsDialog = ref(false);
@ -296,6 +297,8 @@ function handleKeydown(e: KeyboardEvent) {
function onLoginSuccess() {
authenticated.value = true;
setupRequired.value = false;
needsAuth.value = true;
window.history.replaceState(null, "", "/");
initApp();
}
@ -336,13 +339,14 @@ onMounted(async () => {
const data = await res.json();
needsAuth.value = data.required;
authenticated.value = data.authenticated;
setupRequired.value = data.setup_required;
} catch {
/* server unreachable */
}
if (needsAuth.value && !authenticated.value) {
history.replaceState(null, "", "/login");
}
if (!needsAuth.value || authenticated.value) initApp();
if (!setupRequired.value && (!needsAuth.value || authenticated.value)) initApp();
api
.getAppVersion()
.then((v) => {
@ -369,8 +373,12 @@ onUnmounted(() => {
</script>
<template>
<LoginPage v-if="needsAuth && !authenticated" @authenticated="onLoginSuccess" />
<div v-show="!needsAuth || authenticated">
<LoginPage
v-if="setupRequired || (needsAuth && !authenticated)"
:setup-mode="setupRequired"
@authenticated="onLoginSuccess"
/>
<div v-show="!setupRequired && (!needsAuth || authenticated)">
<TooltipProvider :delay-duration="300">
<div class="h-screen w-screen flex flex-col bg-background text-foreground overflow-hidden">
<AppToolbar

View File

@ -1,20 +1,36 @@
<script setup lang="ts">
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Lock, Loader2 } from "lucide-vue-next";
import { Lock, Loader2, ShieldCheck } from "lucide-vue-next";
const props = withDefaults(
defineProps<{
setupMode?: boolean;
}>(),
{ setupMode: false },
);
const emit = defineEmits<{ authenticated: [] }>();
const { t } = useI18n();
const password = ref("");
const confirmPassword = ref("");
const error = ref("");
const loading = ref(false);
async function login() {
async function submit() {
if (props.setupMode && password.value !== confirmPassword.value) {
error.value = t("auth.passwordMismatch");
return;
}
loading.value = true;
error.value = "";
try {
const res = await fetch("/api/auth/login", {
const url = props.setupMode ? "/api/auth/setup" : "/api/auth/login";
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password: password.value }),
@ -23,10 +39,10 @@ async function login() {
emit("authenticated");
} else {
const text = await res.text();
error.value = text || "密码错误";
error.value = text || t("auth.loginFailed");
}
} catch (e: any) {
error.value = e?.message || "连接失败";
error.value = e?.message || t("auth.connectFailed");
} finally {
loading.value = false;
}
@ -42,26 +58,46 @@ async function login() {
<img src="/logo.png" alt="DBX" class="w-20 h-20 rounded-2xl shadow-lg shadow-blue-500/20" />
<div class="text-center">
<h1 class="text-2xl font-bold tracking-tight">DBX</h1>
<p class="text-sm text-muted-foreground mt-1">数据库管理工具</p>
<p class="text-sm text-muted-foreground mt-1">
{{ setupMode ? t("auth.setupDescription") : t("auth.loginDescription") }}
</p>
</div>
</div>
<form class="space-y-4" @submit.prevent="login" autocomplete="off">
<form class="space-y-4" @submit.prevent="submit" autocomplete="off">
<div v-if="setupMode" class="flex items-center justify-center gap-2 text-sm text-muted-foreground">
<ShieldCheck class="w-4 h-4" />
<span>{{ t("auth.setupTitle") }}</span>
</div>
<div class="relative">
<Lock class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
v-model="password"
type="password"
placeholder="请输入访问密码"
:placeholder="setupMode ? t('auth.newPassword') : t('auth.enterPassword')"
class="pl-10 h-11"
autocomplete="off"
autofocus
/>
</div>
<div v-if="setupMode" class="relative">
<Lock class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
v-model="confirmPassword"
type="password"
:placeholder="t('auth.confirmPassword')"
class="pl-10 h-11"
autocomplete="off"
/>
</div>
<p v-if="error" class="text-sm text-destructive text-center">{{ error }}</p>
<Button type="submit" class="w-full h-11 text-sm font-medium" :disabled="loading || !password">
<Button
type="submit"
class="w-full h-11 text-sm font-medium"
:disabled="loading || !password || (setupMode && !confirmPassword)"
>
<Loader2 v-if="loading" class="w-4 h-4 animate-spin mr-2" />
{{ loading ? "登录中..." : "登录" }}
{{ loading ? t("auth.processing") : setupMode ? t("auth.setPassword") : t("auth.login") }}
</Button>
</form>

View File

@ -5,11 +5,14 @@ import { useI18n } from "vue-i18n";
import { Settings } from "lucide-vue-next";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useSettingsStore, EDITOR_THEMES, FONT_FAMILIES, DEFAULT_EDITOR_SETTINGS } from "@/stores/settingsStore";
import { loadEditorTheme, editorFontTheme } from "@/lib/editorThemes";
import { isTauriRuntime } from "@/lib/tauriRuntime";
const { t } = useI18n();
const settingsStore = useSettingsStore();
@ -79,6 +82,63 @@ function onThemeChange(v: any) {
if (typeof v === "string") editTheme.value = v as typeof DEFAULT_EDITOR_SETTINGS.theme;
}
const activeSettingsTab = ref("editor");
const isWeb = !isTauriRuntime();
watch(
() => props.open,
(open) => {
if (open) {
activeSettingsTab.value = "editor";
passwordMessage.value = "";
oldPassword.value = "";
newPassword.value = "";
confirmNewPassword.value = "";
}
},
);
const oldPassword = ref("");
const newPassword = ref("");
const confirmNewPassword = ref("");
const passwordMessage = ref("");
const passwordError = ref(false);
const changingPassword = ref(false);
async function changePassword() {
if (newPassword.value !== confirmNewPassword.value) {
passwordMessage.value = t("auth.passwordMismatch");
passwordError.value = true;
return;
}
changingPassword.value = true;
passwordMessage.value = "";
try {
const res = await fetch("/api/auth/change-password", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ old_password: oldPassword.value, new_password: newPassword.value }),
});
if (res.ok) {
passwordMessage.value = t("auth.passwordChanged");
passwordError.value = false;
oldPassword.value = "";
newPassword.value = "";
confirmNewPassword.value = "";
} else if (res.status === 401) {
passwordMessage.value = t("auth.oldPasswordWrong");
passwordError.value = true;
} else {
passwordMessage.value = t("auth.changePasswordFailed");
passwordError.value = true;
}
} catch {
passwordMessage.value = t("auth.connectFailed");
passwordError.value = true;
} finally {
changingPassword.value = false;
}
}
// ---------- CodeMirror preview ----------
const previewRef = ref<HTMLDivElement>();
const previewView = shallowRef<EditorViewType | null>(null);
@ -115,6 +175,17 @@ watch(
let previewInitialized = false;
watch(activeSettingsTab, (tab) => {
if (tab !== "editor" && previewView.value) {
previewView.value.destroy();
previewView.value = null;
previewInitialized = false;
fontThemeComp = null;
themeComp = null;
editorViewModule = null;
}
});
watch(previewRef, async (el) => {
if (!el || previewInitialized) return;
previewInitialized = true;
@ -172,124 +243,173 @@ watch(
</DialogTitle>
</DialogHeader>
<div class="space-y-5 py-2">
<!-- Font Family -->
<div class="space-y-2">
<Label>{{ t("settings.fontFamily") }}</Label>
<Select :model-value="editFontFamily" @update:model-value="onFontFamilyChange">
<SelectTrigger>
<SelectValue :placeholder="t('settings.selectFont')" />
</SelectTrigger>
<SelectContent>
<SelectItem
v-for="font in FONT_FAMILIES"
:key="font.value"
:value="font.value"
:style="{ fontFamily: font.value }"
>
{{ font.label }}
</SelectItem>
</SelectContent>
</Select>
<p class="text-xs text-muted-foreground leading-relaxed font-mono" :style="{ fontFamily: editFontFamily }">
SELECT * FROM users WHERE id = 1;
</p>
</div>
<Tabs v-model="activeSettingsTab">
<TabsList class="w-full">
<TabsTrigger value="editor" class="flex-1">{{ t("settings.editorTab") }}</TabsTrigger>
<TabsTrigger v-if="isWeb" value="security" class="flex-1">{{ t("settings.securityTab") }}</TabsTrigger>
</TabsList>
<Separator />
<!-- Font Size -->
<div class="space-y-2">
<div class="flex items-center justify-between">
<Label>{{ t("settings.fontSize") }}</Label>
<span class="text-xs text-muted-foreground tabular-nums">{{ editFontSize }}px</span>
<TabsContent value="editor" class="space-y-5 py-2">
<!-- Font Family -->
<div class="space-y-2">
<Label>{{ t("settings.fontFamily") }}</Label>
<Select :model-value="editFontFamily" @update:model-value="onFontFamilyChange">
<SelectTrigger>
<SelectValue :placeholder="t('settings.selectFont')" />
</SelectTrigger>
<SelectContent>
<SelectItem
v-for="font in FONT_FAMILIES"
:key="font.value"
:value="font.value"
:style="{ fontFamily: font.value }"
>
{{ font.label }}
</SelectItem>
</SelectContent>
</Select>
<p class="text-xs text-muted-foreground leading-relaxed font-mono" :style="{ fontFamily: editFontFamily }">
SELECT * FROM users WHERE id = 1;
</p>
</div>
<input
type="range"
min="10"
max="24"
step="1"
:value="editFontSize"
@input="editFontSize = Number(($event.target as HTMLInputElement).value)"
class="w-full accent-primary"
/>
<div class="flex items-center gap-2 text-xs text-muted-foreground">
<span>10px</span>
<span class="flex-1 border-b border-dashed border-muted-foreground/30" />
<span>24px</span>
<Separator />
<!-- Font Size -->
<div class="space-y-2">
<div class="flex items-center justify-between">
<Label>{{ t("settings.fontSize") }}</Label>
<span class="text-xs text-muted-foreground tabular-nums">{{ editFontSize }}px</span>
</div>
<input
type="range"
min="10"
max="24"
step="1"
:value="editFontSize"
@input="editFontSize = Number(($event.target as HTMLInputElement).value)"
class="w-full accent-primary"
/>
<div class="flex items-center gap-2 text-xs text-muted-foreground">
<span>10px</span>
<span class="flex-1 border-b border-dashed border-muted-foreground/30" />
<span>24px</span>
</div>
</div>
</div>
<Separator />
<Separator />
<!-- Theme -->
<div class="space-y-2">
<Label>{{ t("settings.theme") }}</Label>
<Select :model-value="editTheme" @update:model-value="onThemeChange">
<SelectTrigger>
<SelectValue :placeholder="t('settings.selectTheme')" />
</SelectTrigger>
<SelectContent>
<SelectItem v-for="theme in EDITOR_THEMES" :key="theme.value" :value="theme.value">
<div class="flex items-center gap-2">
<span
class="h-3 w-3 rounded-full border"
:class="
theme.dark
? 'bg-foreground border-foreground/20'
: 'bg-muted-foreground/30 border-muted-foreground/40'
"
/>
{{ theme.label }}
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
<div class="space-y-2">
<Label>{{ t("settings.executeMode") }}</Label>
<Select :model-value="editExecuteMode" @update:model-value="onExecuteModeChange">
<SelectTrigger>
<SelectValue :placeholder="t('settings.executeMode')" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">{{ t("settings.executeModeAll") }}</SelectItem>
<SelectItem value="current">{{ t("settings.executeModeCurrent") }}</SelectItem>
</SelectContent>
</Select>
</div>
<Separator />
<!-- Live Preview -->
<div class="space-y-2">
<Label>{{ t("settings.preview") }}</Label>
<div
class="rounded-md border overflow-auto max-w-full"
:class="
editTheme === 'vscode-light' || editTheme === 'duotone-light' || editTheme === 'xcode'
? 'border-border'
: 'border-border/50'
"
>
<div ref="previewRef" style="min-width: 100%" />
<!-- Theme -->
<div class="space-y-2">
<Label>{{ t("settings.theme") }}</Label>
<Select :model-value="editTheme" @update:model-value="onThemeChange">
<SelectTrigger>
<SelectValue :placeholder="t('settings.selectTheme')" />
</SelectTrigger>
<SelectContent>
<SelectItem v-for="theme in EDITOR_THEMES" :key="theme.value" :value="theme.value">
<div class="flex items-center gap-2">
<span
class="h-3 w-3 rounded-full border"
:class="
theme.dark
? 'bg-foreground border-foreground/20'
: 'bg-muted-foreground/30 border-muted-foreground/40'
"
/>
{{ theme.label }}
</div>
</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
<DialogFooter class="gap-2 sm:gap-0">
<Button variant="outline" @click="resetDefaults">
{{ t("settings.resetDefaults") }}
</Button>
<div class="flex-1" />
<Button variant="outline" @click="emit('update:open', false)">
{{ t("common.close") }}
</Button>
<Button :disabled="!hasChanges()" @click="applySettings">
{{ t("settings.apply") }}
</Button>
</DialogFooter>
<div class="space-y-2">
<Label>{{ t("settings.executeMode") }}</Label>
<Select :model-value="editExecuteMode" @update:model-value="onExecuteModeChange">
<SelectTrigger>
<SelectValue :placeholder="t('settings.executeMode')" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">{{ t("settings.executeModeAll") }}</SelectItem>
<SelectItem value="current">{{ t("settings.executeModeCurrent") }}</SelectItem>
</SelectContent>
</Select>
</div>
<Separator />
<!-- Live Preview -->
<div class="space-y-2">
<Label>{{ t("settings.preview") }}</Label>
<div
class="rounded-md border overflow-auto max-w-full"
:class="
editTheme === 'vscode-light' || editTheme === 'duotone-light' || editTheme === 'xcode'
? 'border-border'
: 'border-border/50'
"
>
<div ref="previewRef" style="min-width: 100%" />
</div>
</div>
<DialogFooter class="gap-2 sm:gap-0">
<Button variant="outline" @click="resetDefaults">
{{ t("settings.resetDefaults") }}
</Button>
<div class="flex-1" />
<Button variant="outline" @click="emit('update:open', false)">
{{ t("common.close") }}
</Button>
<Button :disabled="!hasChanges()" @click="applySettings">
{{ t("settings.apply") }}
</Button>
</DialogFooter>
</TabsContent>
<TabsContent v-if="isWeb" value="security" class="space-y-5 py-2">
<div class="space-y-3">
<Label class="text-base">{{ t("auth.changePassword") }}</Label>
<p class="text-sm text-muted-foreground">{{ t("auth.changePasswordDescription") }}</p>
<Input
v-model="oldPassword"
type="password"
:placeholder="t('auth.oldPassword')"
class="h-9"
autocomplete="off"
/>
<Input
v-model="newPassword"
type="password"
:placeholder="t('auth.newPassword')"
class="h-9"
autocomplete="off"
/>
<Input
v-model="confirmNewPassword"
type="password"
:placeholder="t('auth.confirmPassword')"
class="h-9"
autocomplete="off"
/>
<p v-if="passwordMessage" class="text-xs" :class="passwordError ? 'text-destructive' : 'text-green-500'">
{{ passwordMessage }}
</p>
</div>
<DialogFooter>
<Button variant="outline" @click="emit('update:open', false)">
{{ t("common.close") }}
</Button>
<Button
:disabled="changingPassword || !oldPassword || !newPassword || !confirmNewPassword"
@click="changePassword"
>
{{ t("auth.changePassword") }}
</Button>
</DialogFooter>
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
</template>

View File

@ -2,6 +2,26 @@ export default {
app: {
name: "DBX",
},
auth: {
setupTitle: "Set up access password",
setupDescription: "Set a password to protect your instance",
loginDescription: "Database management tool",
newPassword: "Enter new password",
confirmPassword: "Confirm password",
enterPassword: "Enter access password",
passwordMismatch: "Passwords do not match",
setPassword: "Set Password",
login: "Login",
processing: "Processing...",
loginFailed: "Incorrect password",
connectFailed: "Connection failed",
changePassword: "Change Password",
oldPassword: "Current password",
oldPasswordWrong: "Current password is incorrect",
passwordChanged: "Password changed successfully",
changePasswordFailed: "Failed to change password",
changePasswordDescription: "Enter your current password and choose a new one",
},
toolbar: {
newConnection: "New Connection",
newQuery: "New Query",
@ -625,6 +645,8 @@ export default {
},
settings: {
title: "Settings",
editorTab: "Editor",
securityTab: "Security",
fontFamily: "Font Family",
selectFont: "Select font...",
fontSize: "Font Size",

View File

@ -2,6 +2,26 @@ export default {
app: {
name: "DBX",
},
auth: {
setupTitle: "设置访问密码",
setupDescription: "设置密码以保护您的实例",
loginDescription: "数据库管理工具",
newPassword: "输入新密码",
confirmPassword: "确认密码",
enterPassword: "请输入访问密码",
passwordMismatch: "两次输入的密码不一致",
setPassword: "设置密码",
login: "登录",
processing: "处理中...",
loginFailed: "密码错误",
connectFailed: "连接失败",
changePassword: "修改密码",
oldPassword: "当前密码",
oldPasswordWrong: "当前密码不正确",
passwordChanged: "密码修改成功",
changePasswordFailed: "密码修改失败",
changePasswordDescription: "输入当前密码并设置新密码",
},
toolbar: {
newConnection: "新建连接",
newQuery: "新建查询",
@ -617,6 +637,8 @@ export default {
},
settings: {
title: "设置",
editorTab: "编辑器",
securityTab: "安全",
fontFamily: "字体",
selectFont: "选择字体...",
fontSize: "字号",