mirror of
https://github.com/t8y2/dbx.git
synced 2026-10-21 04:35:15 +00:00
Refactor code structure for improved readability and maintainability
This commit is contained in:
+1
-1
@@ -7,7 +7,7 @@
|
||||
"dev": "vite",
|
||||
"dev:tauri": "tauri dev",
|
||||
"dev:web": "vite --port 5173 --mode web",
|
||||
"dev:backend": "RUST_LOG=info cargo watch -x 'run -p dbx-web'",
|
||||
"dev:backend": "RUST_LOG=${RUST_LOG:-info} DBX_PASSWORD=${DBX_PASSWORD:-test} cargo watch -x 'run -p dbx-web'",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri"
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 141 KiB |
@@ -21,6 +21,9 @@ pub struct AuthCheckResponse {
|
||||
pub 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>,
|
||||
@@ -36,14 +39,41 @@ pub async fn login(
|
||||
}
|
||||
};
|
||||
|
||||
// Check rate limit
|
||||
{
|
||||
let rl = state.login_rate_limit.lock().await;
|
||||
if let Some(locked_until) = rl.locked_until {
|
||||
if locked_until > std::time::Instant::now() {
|
||||
let remaining = (locked_until - std::time::Instant::now()).as_secs();
|
||||
return Ok((
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
Json(serde_json::json!({"error": format!("请 {remaining} 秒后再试")})),
|
||||
).into_response());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(body.password.as_bytes());
|
||||
let hash = hex::encode(hasher.finalize());
|
||||
|
||||
if hash != *password_hash {
|
||||
let mut rl = state.login_rate_limit.lock().await;
|
||||
rl.fail_count += 1;
|
||||
if rl.fail_count >= MAX_ATTEMPTS {
|
||||
rl.locked_until = Some(std::time::Instant::now() + std::time::Duration::from_secs(LOCKOUT_SECS));
|
||||
rl.fail_count = 0;
|
||||
}
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
// Success — reset rate limit
|
||||
{
|
||||
let mut rl = state.login_rate_limit.lock().await;
|
||||
rl.fail_count = 0;
|
||||
rl.locked_until = None;
|
||||
}
|
||||
|
||||
let token = uuid::Uuid::new_v4().to_string();
|
||||
state.sessions.write().await.insert(token.clone());
|
||||
|
||||
|
||||
+6
-2
@@ -61,6 +61,10 @@ async fn main() {
|
||||
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,
|
||||
}),
|
||||
});
|
||||
|
||||
// CORS
|
||||
@@ -146,12 +150,12 @@ async fn main() {
|
||||
.route("/update/check", get(routes::update::check_for_updates))
|
||||
// Layout
|
||||
.route("/layout/sidebar", post(routes::layout::save_sidebar_layout).get(routes::layout::load_sidebar_layout))
|
||||
.layer(middleware::from_fn_with_state(web_state.clone(), auth::auth_middleware))
|
||||
.with_state(web_state.clone());
|
||||
|
||||
// Build app with auth middleware
|
||||
// Build app
|
||||
let mut app = Router::new()
|
||||
.nest("/api", api)
|
||||
.layer(middleware::from_fn_with_state(web_state.clone(), auth::auth_middleware))
|
||||
.layer(cors);
|
||||
|
||||
// Static file serving
|
||||
|
||||
@@ -2,7 +2,12 @@ use dbx_core::connection::AppState;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{broadcast, RwLock};
|
||||
use tokio::sync::{broadcast, Mutex, RwLock};
|
||||
|
||||
pub struct LoginRateLimit {
|
||||
pub fail_count: u32,
|
||||
pub locked_until: Option<std::time::Instant>,
|
||||
}
|
||||
|
||||
pub struct WebState {
|
||||
pub app: Arc<AppState>,
|
||||
@@ -10,4 +15,5 @@ pub struct WebState {
|
||||
pub password_hash: Option<String>,
|
||||
pub sessions: RwLock<HashSet<String>>,
|
||||
pub sse_channels: RwLock<HashMap<String, broadcast::Sender<String>>>,
|
||||
pub login_rate_limit: Mutex<LoginRateLimit>,
|
||||
}
|
||||
|
||||
+13
-2
@@ -201,6 +201,12 @@ function handleKeydown(e: KeyboardEvent) {
|
||||
}
|
||||
}
|
||||
|
||||
function onLoginSuccess() {
|
||||
authenticated.value = true;
|
||||
window.history.replaceState(null, "", "/");
|
||||
initApp();
|
||||
}
|
||||
|
||||
function initApp() {
|
||||
connectionStore.initFromDisk().then(() => {
|
||||
reconnectRestoredTabs();
|
||||
@@ -235,6 +241,9 @@ onMounted(async () => {
|
||||
needsAuth.value = data.required;
|
||||
authenticated.value = data.authenticated;
|
||||
} catch { /* server unreachable */ }
|
||||
if (needsAuth.value && !authenticated.value) {
|
||||
history.replaceState(null, "", "/login");
|
||||
}
|
||||
if (!needsAuth.value || authenticated.value) initApp();
|
||||
api.checkForUpdates().then((info) => { appVersion.value = info.current_version; }).catch(() => {});
|
||||
return;
|
||||
@@ -252,8 +261,9 @@ onUnmounted(() => { window.removeEventListener("keydown", handleKeydown, true);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<LoginPage v-if="needsAuth && !authenticated" @authenticated="authenticated = true; initApp()" />
|
||||
<TooltipProvider v-show="!needsAuth || authenticated" :delay-duration="300">
|
||||
<LoginPage v-if="needsAuth && !authenticated" @authenticated="onLoginSuccess" />
|
||||
<div v-show="!needsAuth || authenticated">
|
||||
<TooltipProvider :delay-duration="300">
|
||||
<div class="h-screen w-screen flex flex-col bg-background text-foreground overflow-hidden">
|
||||
<AppToolbar
|
||||
:is-dark="isDark" :show-ai-panel="showAiPanel" :show-history="showHistory"
|
||||
@@ -355,6 +365,7 @@ onUnmounted(() => { window.removeEventListener("keydown", handleKeydown, true);
|
||||
</Transition>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { ref } from "vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { DatabaseZap } from "lucide-vue-next";
|
||||
import { Lock, Loader2 } from "lucide-vue-next";
|
||||
|
||||
const emit = defineEmits<{ authenticated: [] }>();
|
||||
|
||||
@@ -34,24 +34,38 @@ async function login() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex items-center justify-center h-screen bg-background">
|
||||
<div class="w-80 space-y-6 text-center">
|
||||
<div class="flex items-center justify-center gap-2 text-2xl font-bold">
|
||||
<DatabaseZap class="w-8 h-8" />
|
||||
<span>DBX</span>
|
||||
<div class="flex items-center justify-center h-screen bg-gradient-to-br from-background via-background to-blue-950/20">
|
||||
<div class="w-[360px] space-y-8">
|
||||
<div class="flex flex-col items-center gap-4">
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
<form class="space-y-4" @submit.prevent="login">
|
||||
<Input
|
||||
v-model="password"
|
||||
type="password"
|
||||
placeholder="请输入访问密码"
|
||||
autofocus
|
||||
/>
|
||||
<p v-if="error" class="text-sm text-destructive">{{ error }}</p>
|
||||
<Button type="submit" class="w-full" :disabled="loading || !password">
|
||||
|
||||
<form class="space-y-4" @submit.prevent="login" autocomplete="off">
|
||||
<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="请输入访问密码"
|
||||
class="pl-10 h-11"
|
||||
autocomplete="off"
|
||||
autofocus
|
||||
/>
|
||||
</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">
|
||||
<Loader2 v-if="loading" class="w-4 h-4 animate-spin mr-2" />
|
||||
{{ loading ? "登录中..." : "登录" }}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<p class="text-center text-xs text-muted-foreground/50">
|
||||
Powered by DBX
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
Reference in New Issue
Block a user