Compare commits
7 Commits
6292a77dff
...
2fdfb0bd0c
| Author | SHA1 | Date | |
|---|---|---|---|
| 2fdfb0bd0c | |||
| 3bedaad87f | |||
| a1feffea0b | |||
| 8c9c0217c9 | |||
| 8ac3177384 | |||
| e45cb96d07 | |||
| b9bea0db23 |
Binary file not shown.
+897
-382
File diff suppressed because it is too large
Load Diff
@@ -261,3 +261,14 @@ mod tests {
|
||||
assert!(dir.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bcrypt_hash() {
|
||||
let password = "demo123";
|
||||
let hash = bcrypt::hash(password, bcrypt::DEFAULT_COST).unwrap();
|
||||
println!("Hash for demo123: {}", hash);
|
||||
|
||||
// Verify the hash works
|
||||
let valid = bcrypt::verify(password, &hash).unwrap();
|
||||
assert!(valid);
|
||||
}
|
||||
|
||||
+555
-69
@@ -9,7 +9,10 @@ use axum::{
|
||||
Router,
|
||||
};
|
||||
use base64::Engine as _;
|
||||
use bcrypt::{hash, DEFAULT_COST};
|
||||
use rusqlite::Connection;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
use std::sync::{Arc, LazyLock, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -26,6 +29,89 @@ use crate::render;
|
||||
use filetree::{self, FileTree};
|
||||
use tower_http::cors::CorsLayer;
|
||||
|
||||
/// Initialize database with demo user if not exists
|
||||
fn init_database(db_path: &PathBuf, home: &PathBuf) -> anyhow::Result<()> {
|
||||
let db_exists = db_path.exists();
|
||||
|
||||
// Create database if not exists
|
||||
let conn = Connection::open(db_path)?;
|
||||
|
||||
if !db_exists {
|
||||
log::info!("Creating new database: {}", db_path.display());
|
||||
|
||||
// Create tables
|
||||
conn.execute_batch(
|
||||
r#"
|
||||
CREATE TABLE IF NOT EXISTS sftpgo_users (
|
||||
username TEXT PRIMARY KEY,
|
||||
password_hash TEXT NOT NULL,
|
||||
email TEXT,
|
||||
status INTEGER DEFAULT 1,
|
||||
home_dir TEXT,
|
||||
permissions TEXT,
|
||||
uid INTEGER,
|
||||
gid INTEGER,
|
||||
last_login INTEGER,
|
||||
created_at INTEGER,
|
||||
updated_at INTEGER,
|
||||
last_sync_at INTEGER,
|
||||
sync_status INTEGER DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_users_status ON sftpgo_users(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_users_sync_status ON sftpgo_users(sync_status);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sftpgo_groups (
|
||||
name TEXT PRIMARY KEY,
|
||||
description TEXT,
|
||||
created_at INTEGER,
|
||||
updated_at INTEGER,
|
||||
last_sync_at INTEGER
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users_groups_mapping (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL,
|
||||
group_name TEXT NOT NULL,
|
||||
created_at INTEGER,
|
||||
FOREIGN KEY (username) REFERENCES sftpgo_users(username) ON DELETE CASCADE,
|
||||
FOREIGN KEY (group_name) REFERENCES sftpgo_groups(name) ON DELETE CASCADE,
|
||||
UNIQUE(username, group_name)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_mapping_username ON users_groups_mapping(username);
|
||||
CREATE INDEX IF NOT EXISTS idx_mapping_group ON users_groups_mapping(group_name);
|
||||
"#,
|
||||
)?;
|
||||
|
||||
// Create demo user with home directory relative to user's home
|
||||
let demo_home = home.join("markbase").join("data").join("demo");
|
||||
let demo_home_str = demo_home.to_string_lossy().to_string();
|
||||
let password_hash = hash("demo123", DEFAULT_COST)?;
|
||||
let created_at = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as i64;
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO sftpgo_users (username, password_hash, home_dir, permissions, status, uid, gid, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, 1, 501, 20, ?5)",
|
||||
rusqlite::params![
|
||||
"demo",
|
||||
password_hash,
|
||||
demo_home_str,
|
||||
r#"{"*": ["/"]}"#,
|
||||
created_at
|
||||
],
|
||||
)?;
|
||||
|
||||
log::info!("Created demo user: demo (password: demo123, home: {})", demo_home.display());
|
||||
log::info!("Demo user is ready for testing");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub html: Arc<Mutex<String>>,
|
||||
@@ -39,7 +125,23 @@ pub struct AppState {
|
||||
pub upload_path: String,
|
||||
}
|
||||
|
||||
pub async fn run(port: u16, file: Option<String>) -> anyhow::Result<()> {
|
||||
pub async fn run(port: u16, file: Option<String>, home: PathBuf) -> anyhow::Result<()> {
|
||||
// Initialize data directory structure
|
||||
let data_dir = home.join("markbase").join("data");
|
||||
let users_dir = data_dir.join("users");
|
||||
let demo_dir = data_dir.join("demo");
|
||||
let auth_db_path = data_dir.join("auth.sqlite");
|
||||
|
||||
// Create directories if not exist
|
||||
std::fs::create_dir_all(&users_dir)?;
|
||||
std::fs::create_dir_all(&demo_dir)?;
|
||||
|
||||
log::info!("Data directory: {}", data_dir.display());
|
||||
log::info!("Auth database: {}", auth_db_path.display());
|
||||
|
||||
// Initialize database with demo user if not exists
|
||||
init_database(&auth_db_path, &home)?;
|
||||
|
||||
let welcome = if let Some(f) = &file {
|
||||
let md = std::fs::read_to_string(f).unwrap_or_default();
|
||||
let body = render::md_to_html(&md);
|
||||
@@ -80,7 +182,12 @@ pub async fn run(port: u16, file: Option<String>) -> anyhow::Result<()> {
|
||||
|
||||
// Initialize admin WebDAV upload path + MyFiles upload path (replaces env var reads)
|
||||
let _ = UPLOAD_PATH.set(upload_path.clone());
|
||||
crate::myfiles::init_upload_path(upload_path.clone());
|
||||
// MyFiles uses VfsBackend (LocalFs) directly — no init needed
|
||||
|
||||
let users_dir_str = users_dir.to_string_lossy().to_string();
|
||||
let auth_db_str = auth_db_path.to_string_lossy().to_string();
|
||||
let s3_keys_path = data_dir.join("s3_keys.json");
|
||||
let s3_keys_path_str = s3_keys_path.to_string_lossy().to_string();
|
||||
|
||||
let state = AppState {
|
||||
html: Arc::new(Mutex::new(html)),
|
||||
@@ -89,19 +196,19 @@ pub async fn run(port: u16, file: Option<String>) -> anyhow::Result<()> {
|
||||
"step": 0, "total": 0, "id": "", "label": "", "voice": "off"
|
||||
}))),
|
||||
labels: Arc::new(Mutex::new(vec![])),
|
||||
db_dir: "data/users".to_string(),
|
||||
db_dir: users_dir_str.clone(),
|
||||
auth: AuthState::with_provider(Box::new(
|
||||
SqliteProvider::new("data/auth.sqlite")
|
||||
SqliteProvider::new(&auth_db_str)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to init SqliteProvider: {}", e))?,
|
||||
)),
|
||||
auth_db_path: "data/auth.sqlite".to_string(),
|
||||
auth_db_path: auth_db_str.clone(),
|
||||
upload_path: upload_path.clone(),
|
||||
s3_keys: Arc::new(Mutex::new(load_s3_keys())),
|
||||
s3_keys: Arc::new(Mutex::new(load_s3_keys(&s3_keys_path_str))),
|
||||
};
|
||||
|
||||
// Load S3 keys from file
|
||||
fn load_s3_keys() -> Vec<crate::s3::S3AccessKey> {
|
||||
if let Ok(content) = std::fs::read_to_string("data/s3_keys.json") {
|
||||
fn load_s3_keys(path: &str) -> Vec<crate::s3::S3AccessKey> {
|
||||
if let Ok(content) = std::fs::read_to_string(path) {
|
||||
serde_json::from_str(&content).unwrap_or_default()
|
||||
} else {
|
||||
vec![
|
||||
@@ -123,52 +230,62 @@ pub async fn run(port: u16, file: Option<String>) -> anyhow::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
// Initial sync from SFTPGo PostgreSQL
|
||||
let syncer = crate::pg_client::SftpGoSync::new("data/auth.sqlite")?;
|
||||
tokio::spawn(async move {
|
||||
match syncer.full_sync().await {
|
||||
Ok(result) => {
|
||||
log::info!(
|
||||
"Initial sync completed: users={}, groups={}, mappings={}, status={}",
|
||||
result.users_synced,
|
||||
result.groups_synced,
|
||||
result.mappings_synced,
|
||||
result.status
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Initial sync failed: {}", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
// SFTPGo sync (optional fallback - default disabled)
|
||||
// Set MARKBASE_ENABLE_SFTPGO_SYNC=1 to enable sync from SFTPGo PostgreSQL
|
||||
let enable_sftpgo_sync = std::env::var("MARKBASE_ENABLE_SFTPGO_SYNC")
|
||||
.map(|v| v == "1" || v.to_lowercase() == "true")
|
||||
.unwrap_or(false);
|
||||
|
||||
// Periodic sync task (every hour)
|
||||
let syncer_clone = crate::pg_client::SftpGoSync::new("data/auth.sqlite")?;
|
||||
tokio::spawn(async move {
|
||||
let mut interval = tokio::time::interval(std::time::Duration::from_secs(3600));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
match syncer_clone.full_sync().await {
|
||||
if enable_sftpgo_sync {
|
||||
log::info!("SFTPGo sync enabled - syncing from PostgreSQL to auth.sqlite");
|
||||
let syncer = crate::pg_client::SftpGoSync::new(&auth_db_str)?;
|
||||
tokio::spawn(async move {
|
||||
match syncer.full_sync().await {
|
||||
Ok(result) => {
|
||||
log::info!(
|
||||
"Hourly sync: users={}, groups={}, status={}",
|
||||
"Initial sync completed: users={}, groups={}, mappings={}, status={}",
|
||||
result.users_synced,
|
||||
result.groups_synced,
|
||||
result.mappings_synced,
|
||||
result.status
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Hourly sync failed, keeping cached data: {}", e);
|
||||
log::error!("Initial sync failed: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
let syncer_clone = crate::pg_client::SftpGoSync::new(&auth_db_str)?;
|
||||
tokio::spawn(async move {
|
||||
let mut interval = tokio::time::interval(std::time::Duration::from_secs(3600));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
match syncer_clone.full_sync().await {
|
||||
Ok(result) => {
|
||||
log::info!(
|
||||
"Hourly sync: users={}, groups={}, status={}",
|
||||
result.users_synced,
|
||||
result.groups_synced,
|
||||
result.status
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Hourly sync failed, keeping cached data: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
log::info!("SFTPGo sync disabled - using local auth.sqlite for user management (set MARKBASE_ENABLE_SFTPGO_SYNC=1 to enable)");
|
||||
}
|
||||
|
||||
|
||||
// ===== WebDAV multi-user configuration (Phase 20 + P1) =====
|
||||
let webdav_parent = std::path::PathBuf::from(&upload_path);
|
||||
|
||||
// WebDAV versioning storage
|
||||
let version_storage = std::path::PathBuf::from("data/webdav_versions");
|
||||
let version_storage = data_dir.join("webdav_versions");
|
||||
std::fs::create_dir_all(&version_storage).ok();
|
||||
|
||||
// Upload hook (disabled by default)
|
||||
@@ -229,6 +346,14 @@ pub async fn run(port: u16, file: Option<String>) -> anyhow::Result<()> {
|
||||
// Admin authentication API endpoints (public)
|
||||
.route("/api/v2/admin/login", post(crate::api::admin::admin_login_handler))
|
||||
.route("/api/v2/admin/verify", get(crate::api::admin::admin_verify_handler))
|
||||
// User management endpoints (require admin token)
|
||||
.route("/api/v2/admin/users", get(crate::api::admin::list_users_handler).post(crate::api::admin::create_user_handler))
|
||||
.route("/api/v2/admin/users/:username", delete(crate::api::admin::delete_user_handler).put(crate::api::admin::update_user_handler))
|
||||
.route("/api/v2/admin/users/:username/password", post(crate::api::admin::change_password_handler))
|
||||
// Service management endpoints
|
||||
.route("/api/v2/service/stop", post(service_stop_handler))
|
||||
.route("/api/v2/service/start", post(service_start_handler))
|
||||
.route("/api/v2/worker/status", get(worker_status_handler))
|
||||
// Protected endpoints (require auth)
|
||||
.route("/api/v2/tree/:user_id", get(get_tree))
|
||||
.route("/api/v2/tree/:user_id/search", get(search_tree))
|
||||
@@ -314,15 +439,6 @@ pub async fn run(port: u16, file: Option<String>) -> anyhow::Result<()> {
|
||||
.route("/admin/products", get(crate::api::admin::admin_products_page))
|
||||
.route("/admin/files", get(crate::api::admin::admin_files_page))
|
||||
.route("/tools/usb-ssd-test", get(|| async { Html(include_str!("usb_ssd_test.html")) }))
|
||||
.route("/upload", get(|| async { Html(include_str!("upload.html")) }))
|
||||
// Product management API (admin auth required)
|
||||
.route("/api/v2/products", get(crate::api::admin::admin_list_all_products))
|
||||
.route("/api/v2/products/create", post(crate::api::admin::admin_create_product))
|
||||
.route("/api/v2/products/stats", get(crate::api::admin::admin_get_series_stats))
|
||||
.route("/api/v2/products/:product_id/files", get(crate::api::admin::admin_get_product_files))
|
||||
.route("/api/v2/products/:product_id", delete(crate::api::admin::admin_delete_product))
|
||||
.route("/api/v2/products/:product_id/assign-files", post(crate::api::admin::admin_assign_files))
|
||||
.route("/api/v2/files/:user_id", get(crate::api::admin::admin_list_uploaded_files))
|
||||
// WebDAV API endpoints (Phase 20, multi-user P1)
|
||||
.route("/webdav", any(handle_webdav_multi))
|
||||
.route("/webdav/", any(handle_webdav_multi))
|
||||
@@ -334,12 +450,20 @@ pub async fn run(port: u16, file: Option<String>) -> anyhow::Result<()> {
|
||||
// MyFiles User Interface (Web UI + API)
|
||||
.route("/myfiles", get(crate::myfiles::ui_page))
|
||||
.route("/api/v2/myfiles/:username/folders", get(crate::myfiles::list_folders).post(crate::myfiles::create_folder))
|
||||
.route("/api/v2/myfiles/:username/folders/:folder_name", delete(crate::myfiles::delete_folder))
|
||||
.route("/api/v2/myfiles/:username/folders/tree", get(crate::myfiles::folder_tree))
|
||||
.route("/api/v2/myfiles/:username/folders/*folder_path", delete(crate::myfiles::delete_folder))
|
||||
.route("/api/v2/myfiles/:username/files", get(crate::myfiles::list_files))
|
||||
.route("/api/v2/myfiles/:username/files/:filename", delete(crate::myfiles::delete_file))
|
||||
.route("/api/v2/myfiles/:username/tags", post(crate::myfiles::add_tag).delete(crate::myfiles::remove_tag))
|
||||
.route("/api/v2/myfiles/:username/move", post(crate::myfiles::move_file))
|
||||
.route("/api/v2/myfiles/:username/move-folder", post(crate::myfiles::move_folder))
|
||||
.route("/api/v2/myfiles/:username/rename-file", post(crate::myfiles::rename_file))
|
||||
.route("/api/v2/myfiles/:username/rename-folder", post(crate::myfiles::rename_folder))
|
||||
.route("/api/v2/myfiles/:username/files/:filename/tags", get(crate::myfiles::file_tags))
|
||||
.route("/api/v2/myfiles/:username/preview/:filename", get(crate::myfiles::preview_file))
|
||||
// Admin Panel endpoints
|
||||
.route("/api/v2/admin/system-stats", get(admin_system_stats))
|
||||
.route("/api/v2/admin/shares", get(admin_list_shares))
|
||||
// Backup/Snapshot API endpoints (Phase 5-6)
|
||||
.route("/api/v2/backup/stats", get(get_backup_stats_handler))
|
||||
.route("/api/v2/backup/config", get(get_backup_config_handler).post(set_backup_config_handler))
|
||||
@@ -1439,10 +1563,6 @@ async fn upload_unlimited(
|
||||
let base_dir = &state.upload_path;
|
||||
let user_dir = format!("{}/{}", base_dir, user_id);
|
||||
|
||||
let mut filename = String::new();
|
||||
let mut file_size: i64 = 0;
|
||||
let mut file_hash = String::new();
|
||||
|
||||
if let Err(e) = tokio::fs::create_dir_all(&user_dir).await {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
@@ -1451,18 +1571,99 @@ async fn upload_unlimited(
|
||||
.into_response();
|
||||
}
|
||||
|
||||
// Collect all parts: text fields (small) and file fields (chunked)
|
||||
enum Part {
|
||||
Text(String, String),
|
||||
File(String, String, Vec<bytes::Bytes>), // (field_name, filename, chunks)
|
||||
}
|
||||
let mut parts = Vec::new();
|
||||
|
||||
while let Ok(Some(mut field)) = multipart.next_field().await {
|
||||
let name = field.name().unwrap_or("").to_string();
|
||||
if name == "folder" || name == "user_id" {
|
||||
if let Ok(text) = field.text().await {
|
||||
parts.push(Part::Text(name, text.trim().to_string()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if name != "file" {
|
||||
continue;
|
||||
}
|
||||
let filename = field.file_name().unwrap_or("upload.bin").to_string();
|
||||
let mut chunks = Vec::new();
|
||||
while let Ok(Some(chunk)) = field.chunk().await {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
parts.push(Part::File(name, filename, chunks));
|
||||
}
|
||||
|
||||
filename = field.file_name().unwrap_or("upload.bin").to_string();
|
||||
let file_path = format!("{}/{}", user_dir, filename);
|
||||
// Extract metadata fields
|
||||
let mut folder = String::new();
|
||||
for part in &parts {
|
||||
if let Part::Text(ref name, ref val) = part {
|
||||
if name == "folder" {
|
||||
folder = val.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process file parts
|
||||
let mut results = Vec::new();
|
||||
for part in parts {
|
||||
let (filename, chunks) = match part {
|
||||
Part::File(_, fname, chunks) => (fname, chunks),
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
// Prepend folder to path if specified
|
||||
let target_dir = if folder.is_empty() {
|
||||
format!("{}/{}", base_dir, user_id)
|
||||
} else {
|
||||
let folder_clean = folder.trim_start_matches('/');
|
||||
format!("{}/{}/{}", base_dir, user_id, folder_clean)
|
||||
};
|
||||
|
||||
if let Err(e) = tokio::fs::create_dir_all(&target_dir).await {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": format!("create_dir error: {}", e)})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
let mut filename = filename;
|
||||
|
||||
// Auto-suffix if file exists: test.txt → test_1.txt, test_2.txt, etc.
|
||||
{
|
||||
let fpath = format!("{}/{}", target_dir, filename);
|
||||
if tokio::fs::try_exists(&fpath).await.unwrap_or(false) {
|
||||
let fname = std::path::Path::new(&filename);
|
||||
let stem = fname.file_stem().unwrap_or_default().to_str().unwrap_or(&filename);
|
||||
let ext = fname.extension().and_then(|e| e.to_str()).unwrap_or("");
|
||||
let mut counter = 1;
|
||||
loop {
|
||||
let alt = if ext.is_empty() {
|
||||
format!("{}_{}", stem, counter)
|
||||
} else {
|
||||
format!("{}_{}.{}", stem, counter, ext)
|
||||
};
|
||||
let alt_path = format!("{}/{}", target_dir, alt);
|
||||
if !tokio::fs::try_exists(&alt_path).await.unwrap_or(false) {
|
||||
filename = alt;
|
||||
break;
|
||||
}
|
||||
counter += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let stored_at = format!("{}/{}", target_dir, filename);
|
||||
let file_path = stored_at.clone();
|
||||
let file_path = stored_at.clone();
|
||||
|
||||
// Create subdirectory if filename contains path (webkitdirectory)
|
||||
if let Some(parent) = std::path::Path::new(&file_path).parent() {
|
||||
if parent != std::path::Path::new(&user_dir) {
|
||||
if parent != std::path::Path::new(&target_dir) {
|
||||
if let Err(e) = tokio::fs::create_dir_all(parent).await {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
@@ -1487,11 +1688,10 @@ async fn upload_unlimited(
|
||||
}
|
||||
};
|
||||
|
||||
while let Ok(Some(chunk)) = field.chunk().await {
|
||||
for chunk in &chunks {
|
||||
total_written += chunk.len() as u64;
|
||||
hasher.update(&chunk);
|
||||
|
||||
if let Err(e) = file.write_all(&chunk).await {
|
||||
hasher.update(chunk);
|
||||
if let Err(e) = file.write_all(chunk).await {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({"error": format!("write error: {}", e)})),
|
||||
@@ -1503,15 +1703,24 @@ async fn upload_unlimited(
|
||||
let _ = file.flush().await;
|
||||
drop(file);
|
||||
|
||||
file_hash = format!("{:x}", hasher.finalize());
|
||||
file_size = total_written as i64;
|
||||
let file_hash = format!("{:x}", hasher.finalize());
|
||||
|
||||
results.push(serde_json::json!({
|
||||
"ok": true,
|
||||
"filename": filename,
|
||||
"file_size": total_written as i64,
|
||||
"file_hash": file_hash,
|
||||
"user_id": user_id,
|
||||
"folder": folder,
|
||||
"stored_at": stored_at,
|
||||
"timestamp": chrono::Utc::now().to_rfc3339()
|
||||
}));
|
||||
}
|
||||
|
||||
// Allow empty files (0 bytes) for .localized, .keep, .gitkeep, etc.
|
||||
if filename.is_empty() {
|
||||
if results.is_empty() {
|
||||
return (
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({"error": "no filename provided"})),
|
||||
Json(serde_json::json!({"error": "no file provided"})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
@@ -1520,11 +1729,9 @@ async fn upload_unlimited(
|
||||
StatusCode::OK,
|
||||
Json(serde_json::json!({
|
||||
"ok": true,
|
||||
"filename": filename,
|
||||
"file_size": file_size,
|
||||
"file_hash": file_hash,
|
||||
"files": results,
|
||||
"user_id": user_id,
|
||||
"stored_at": format!("{}/{}", user_dir, filename),
|
||||
"folder": folder,
|
||||
"timestamp": chrono::Utc::now().to_rfc3339()
|
||||
})),
|
||||
)
|
||||
@@ -1925,6 +2132,62 @@ async fn login_handler(
|
||||
}
|
||||
}
|
||||
|
||||
// === Admin Panel Handlers ===
|
||||
|
||||
async fn admin_system_stats() -> impl IntoResponse {
|
||||
let mut sys = sysinfo::System::new_all();
|
||||
sys.refresh_all();
|
||||
let cpu = sys.global_cpu_usage().round() as u32;
|
||||
let mem_used = sys.used_memory();
|
||||
let mem_total = sys.total_memory();
|
||||
let memory = if mem_total > 0 {
|
||||
((mem_used as f64 / mem_total as f64) * 100.0).round() as u32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// Disk: parse df output (works on macOS and Linux)
|
||||
let disk = if let Ok(output) = std::process::Command::new("df").arg("-k").arg("/").output() {
|
||||
if let Ok(text) = String::from_utf8(output.stdout) {
|
||||
if let Some(line) = text.lines().nth(1) {
|
||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||
if parts.len() >= 5 {
|
||||
if let (Ok(total), Ok(used)) = (parts[1].parse::<f64>(), parts[2].parse::<f64>()) {
|
||||
if total > 0.0 {
|
||||
((used / total) * 100.0).round() as u32
|
||||
} else { 0 }
|
||||
} else { 0 }
|
||||
} else { 0 }
|
||||
} else { 0 }
|
||||
} else { 0 }
|
||||
} else { 0 };
|
||||
Json(serde_json::json!({"cpu": cpu, "memory": memory, "disk": disk}))
|
||||
}
|
||||
|
||||
async fn admin_list_users(State(state): State<AppState>) -> impl IntoResponse {
|
||||
let mut users = Vec::new();
|
||||
if let Some(provider) = &state.auth.provider {
|
||||
if let Ok(user_list) = provider.list_users() {
|
||||
for u in user_list {
|
||||
users.push(serde_json::json!({
|
||||
"username": u.username,
|
||||
"homeDir": u.home_dir.to_string_lossy(),
|
||||
"status": u.status
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
Json(serde_json::Value::Array(users))
|
||||
}
|
||||
|
||||
async fn admin_list_shares() -> impl IntoResponse {
|
||||
let shares = vec![
|
||||
serde_json::json!({"name": "MarkBase Web", "port": 11438, "status": "running", "protocol": "HTTP/WebDAV", "url": "http://localhost:11438"}),
|
||||
serde_json::json!({"name": "SFTP", "port": 2024, "status": "running", "protocol": "SSH/SFTP"}),
|
||||
serde_json::json!({"name": "SMB", "port": 4445, "status": "running", "protocol": "SMB"}),
|
||||
];
|
||||
Json(serde_json::Value::Array(shares))
|
||||
}
|
||||
|
||||
async fn logout_handler(State(state): State<AppState>, headers: HeaderMap) -> impl IntoResponse {
|
||||
let auth_header = headers
|
||||
.get("Authorization")
|
||||
@@ -1999,6 +2262,199 @@ fn verify_auth(state: &AppState, headers: &HeaderMap) -> Result<String, StatusCo
|
||||
}
|
||||
}
|
||||
|
||||
// === Service Management Handlers ===
|
||||
|
||||
async fn service_stop_handler(
|
||||
Json(body): Json<serde_json::Value>,
|
||||
) -> impl IntoResponse {
|
||||
let name = body.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||||
// Worker has no port — stop via pidfile / pkill instead of lsof
|
||||
if name == "Worker" || name == "worker" {
|
||||
let cmd = format!(
|
||||
"sleep 0.5; WPID=$(cat /Users/accusys/momentry_core/logs/worker_3002.pid 2>/dev/null); \
|
||||
if [ -n \"$WPID\" ]; then pkill -P $WPID 2>/dev/null; kill -9 $WPID 2>/dev/null; fi; \
|
||||
pkill -9 -f 'target/release/momentry worker' 2>/dev/null; rm -f /Users/accusys/momentry_core/logs/worker_3002.pid; \
|
||||
echo 'stopped'"
|
||||
);
|
||||
let _ = std::process::Command::new("sh").arg("-c").arg(cmd).spawn();
|
||||
return (StatusCode::OK, Json(serde_json::json!({"result": "stopped"}))).into_response();
|
||||
}
|
||||
let port = match name {
|
||||
"Core API" | "core" => 3002,
|
||||
"MarkBase" | "markbase" => 11438,
|
||||
"MarkBaseEngine" | "mbe" => 8080,
|
||||
"SFTP" => 2024,
|
||||
"SMB" => 4445,
|
||||
"Proxy" | "proxy" => 8888,
|
||||
_ => return (StatusCode::BAD_REQUEST, Json(serde_json::json!({"error": format!("Unknown service: {}", name)}))).into_response(),
|
||||
};
|
||||
// Spawn (not wait) so the server can respond before killing itself
|
||||
let _ = std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(format!("sleep 0.5; lsof -ti :{} | xargs kill -9 2>/dev/null; echo 'stopped'", port))
|
||||
.spawn();
|
||||
(StatusCode::OK, Json(serde_json::json!({"result": "stopped"}))).into_response()
|
||||
}
|
||||
|
||||
async fn service_start_handler(
|
||||
Json(body): Json<serde_json::Value>,
|
||||
) -> impl IntoResponse {
|
||||
let name = body.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||||
// Worker has no port — start via run script, poll pidfile for liveness
|
||||
if name == "Worker" || name == "worker" {
|
||||
let cmd = "cd /Users/accusys/momentry_core && nohup bash run-worker-3002.sh > /tmp/momentry_worker.log 2>&1 &";
|
||||
return match std::process::Command::new("sh").arg("-c").arg(cmd).output() {
|
||||
Ok(_) => {
|
||||
let mut waited = 0u64;
|
||||
let step = 2u64;
|
||||
let max_wait = 10u64;
|
||||
while waited < max_wait {
|
||||
std::thread::sleep(std::time::Duration::from_secs(step));
|
||||
waited += step;
|
||||
let check = std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg("WPID=$(cat /Users/accusys/momentry_core/logs/worker_3002.pid 2>/dev/null); [ -n \"$WPID\" ] && kill -0 $WPID 2>/dev/null && echo alive")
|
||||
.output();
|
||||
if let Ok(c) = check {
|
||||
if String::from_utf8_lossy(&c.stdout).contains("alive") {
|
||||
return (StatusCode::OK, Json(serde_json::json!({"result": "started"}))).into_response();
|
||||
}
|
||||
}
|
||||
}
|
||||
(StatusCode::OK, Json(serde_json::json!({"result": "started", "warning": "Worker pid check inconclusive, verify manually"}))).into_response()
|
||||
}
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": format!("Failed to start: {}", e)}))).into_response(),
|
||||
};
|
||||
}
|
||||
let (cmd, port) = match name {
|
||||
"MarkBase" | "markbase" => (
|
||||
"cd /Users/accusys/markbase && nohup cargo run --bin markbase-core -- web-start --port 11438 > /tmp/markbase_web.log 2>&1 &",
|
||||
11438,
|
||||
),
|
||||
"Core API" | "core" => (
|
||||
"cd /Users/accusys/momentry_core && nohup bash run-server-3002.sh > /tmp/momentry_start.log 2>&1 &",
|
||||
3002,
|
||||
),
|
||||
"Proxy" | "proxy" => (
|
||||
"cd /Users/accusys/momentry_studio/src-tauri && nohup ./target/debug/momentry-proxy > /tmp/momentry_proxy.log 2>&1 &",
|
||||
8888,
|
||||
),
|
||||
"MarkBaseEngine" | "mbe" => (
|
||||
"cd /Users/accusys/MarkBaseEngine && nohup .build/arm64-apple-macosx/release/MarkBaseServer E4B-MarkBase 8080 > /tmp/markbase_engine.log 2>&1 &",
|
||||
8080,
|
||||
),
|
||||
"SFTP" => (
|
||||
"cd /Users/accusys/markbase && nohup cargo run --bin markbase-core -- ssh-start --port 2024 > /tmp/markbase_ssh.log 2>&1 &",
|
||||
2024,
|
||||
),
|
||||
"SMB" => (
|
||||
"cd /Users/accusys/markbase && nohup cargo run --bin markbase-core --features smb-server -- smb-start --port 4445 --share-name markbase --root /Users/accusys/momentry/var/sftpgo/data --user demo:demo123 > /tmp/markbase_smb.log 2>&1 &",
|
||||
4445,
|
||||
),
|
||||
_ => return (StatusCode::BAD_REQUEST, Json(serde_json::json!({"error": format!("Unknown service: {}", name)}))).into_response(),
|
||||
};
|
||||
match std::process::Command::new("sh").arg("-c").arg(cmd).output() {
|
||||
Ok(_) => {
|
||||
// Poll for port up to 60s (MBE needs time to load model)
|
||||
let max_wait = match port {
|
||||
8080 => 60u64, // MarkBaseEngine
|
||||
_ => 5u64,
|
||||
};
|
||||
let mut waited = 0u64;
|
||||
let step = 2u64;
|
||||
while waited < max_wait {
|
||||
std::thread::sleep(std::time::Duration::from_secs(step));
|
||||
waited += step;
|
||||
let check = std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(format!("lsof -ti :{} 2>/dev/null", port))
|
||||
.output();
|
||||
if let Ok(c) = check {
|
||||
if !c.stdout.is_empty() {
|
||||
return (StatusCode::OK, Json(serde_json::json!({"result": "started"}))).into_response();
|
||||
}
|
||||
}
|
||||
}
|
||||
(StatusCode::OK, Json(serde_json::json!({"result": "started", "warning": "Port check inconclusive, verify manually"}))).into_response()
|
||||
}
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": format!("Failed to start: {}", e)}))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn worker_status_handler() -> impl IntoResponse {
|
||||
let pid_file = "/Users/accusys/momentry_core/logs/worker_3002.pid";
|
||||
let pid = std::fs::read_to_string(pid_file)
|
||||
.ok()
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty());
|
||||
let mut running = false;
|
||||
if let Some(pid_str) = &pid {
|
||||
if let Ok(pid_num) = pid_str.parse::<i32>() {
|
||||
running = std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(format!("kill -0 {} 2>/dev/null", pid_num))
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false);
|
||||
}
|
||||
}
|
||||
if !running {
|
||||
// Fallback: pgrep by process name
|
||||
running = std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg("pgrep -f 'target/release/momentry worker' >/dev/null 2>&1")
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false);
|
||||
}
|
||||
let uptime = if running {
|
||||
let etime = std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg("ps -o etime= -p $(cat /Users/accusys/momentry_core/logs/worker_3002.pid 2>/dev/null) 2>/dev/null")
|
||||
.output()
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
|
||||
.unwrap_or_default();
|
||||
parse_etime_seconds(&etime)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(serde_json::json!({
|
||||
"status": if running { "running" } else { "stopped" },
|
||||
"pid": pid.and_then(|p| p.parse::<u64>().ok()),
|
||||
"uptime": uptime,
|
||||
"version": "worker (momentry-core)",
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// Parse `ps -o etime` output like `HH:MM:SS` / `MM:SS` / `D-HH:MM:SS` into seconds.
|
||||
fn parse_etime_seconds(etime: &str) -> u64 {
|
||||
let etime = etime.trim();
|
||||
if etime.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let (days, rest) = if let Some((d, r)) = etime.split_once('-') {
|
||||
(d.parse::<u64>().unwrap_or(0), r)
|
||||
} else {
|
||||
(0, etime)
|
||||
};
|
||||
let parts: Vec<&str> = rest.split(':').collect();
|
||||
let secs = match parts.as_slice() {
|
||||
[s] => s.parse::<u64>().unwrap_or(0),
|
||||
[m, s] => m.parse::<u64>().unwrap_or(0) * 60 + s.parse::<u64>().unwrap_or(0),
|
||||
[h, m, s] => {
|
||||
h.parse::<u64>().unwrap_or(0) * 3600
|
||||
+ m.parse::<u64>().unwrap_or(0) * 60
|
||||
+ s.parse::<u64>().unwrap_or(0)
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
days * 86400 + secs
|
||||
}
|
||||
|
||||
// === Sync Handlers ===
|
||||
|
||||
fn html_escape(s: &str) -> String {
|
||||
@@ -2409,7 +2865,6 @@ async fn handle_webdav_admin(
|
||||
// ============================================================================
|
||||
|
||||
use crate::vfs::{VfsBackend, local_fs::LocalFs, backup_scheduler::{BackupScheduler, BackupScheduleConfig}};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct BackupStatsResponse {
|
||||
@@ -2582,3 +3037,34 @@ async fn get_storage_stats_handler(Query(params): Query<std::collections::HashMa
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parse_etime_seconds;
|
||||
|
||||
#[test]
|
||||
fn test_parse_etime_seconds_hm() {
|
||||
assert_eq!(parse_etime_seconds("12:34"), 754);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_etime_seconds_hms() {
|
||||
assert_eq!(parse_etime_seconds("1:02:03"), 3723);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_etime_seconds_days() {
|
||||
assert_eq!(parse_etime_seconds("2-03:04:05"), 183845);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_etime_seconds_seconds() {
|
||||
assert_eq!(parse_etime_seconds("42"), 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_etime_seconds_empty() {
|
||||
assert_eq!(parse_etime_seconds(""), 0);
|
||||
assert_eq!(parse_etime_seconds(" "), 0);
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+17
@@ -3570,6 +3570,7 @@ dependencies = [
|
||||
"tokio-postgres",
|
||||
"tokio-util",
|
||||
"toml 0.8.23",
|
||||
"tower-http",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"ureq",
|
||||
@@ -7120,6 +7121,22 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-http"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5"
|
||||
dependencies = [
|
||||
"bitflags 2.13.0",
|
||||
"bytes",
|
||||
"http 1.4.2",
|
||||
"http-body 1.0.1",
|
||||
"http-body-util",
|
||||
"pin-project-lite",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-layer"
|
||||
version = "0.3.3"
|
||||
|
||||
@@ -12,12 +12,15 @@ rust-version = "1.60"
|
||||
[workspace]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "1.5.6", features = [] }
|
||||
tauri-build = { version = "2.0", features = [] }
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
tauri = { version = "1.8.3", features = ["fs-all", "path-all", "http-all", "shell-all"] }
|
||||
tauri = { version = "2.0", features = [] }
|
||||
tauri-plugin-fs = "2.0"
|
||||
tauri-plugin-http = "2.0"
|
||||
tauri-plugin-shell = "2.0"
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
sysinfo = "0.30"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
|
||||
@@ -10,6 +10,13 @@ pub struct UserInfo {
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct LoginResult {
|
||||
pub success: bool,
|
||||
pub username: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref DATA_PROVIDER: LazyLock<Arc<Mutex<Box<dyn DataProvider>>>> =
|
||||
LazyLock::new(|| {
|
||||
@@ -20,6 +27,27 @@ lazy_static::lazy_static! {
|
||||
});
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn auth_login(username: String, password: String) -> Result<LoginResult, String> {
|
||||
let provider = DATA_PROVIDER.lock().unwrap();
|
||||
|
||||
let valid = provider.check_password(&username, &password).map_err(|e| e.to_string())?;
|
||||
|
||||
if valid {
|
||||
Ok(LoginResult {
|
||||
success: true,
|
||||
username: username.clone(),
|
||||
message: "Login successful".to_string(),
|
||||
})
|
||||
} else {
|
||||
Ok(LoginResult {
|
||||
success: false,
|
||||
username: String::new(),
|
||||
message: "Invalid username or password".to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn list_auth_users() -> Result<Vec<UserInfo>, String> {
|
||||
let provider = DATA_PROVIDER.lock().unwrap();
|
||||
|
||||
@@ -6,6 +6,9 @@ use commands::*;
|
||||
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_fs::init())
|
||||
.plugin(tauri_plugin_http::init())
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
get_tree,
|
||||
list_files,
|
||||
@@ -42,6 +45,7 @@ fn main() {
|
||||
get_backup_config,
|
||||
set_backup_config,
|
||||
run_backup,
|
||||
auth_login,
|
||||
list_auth_users,
|
||||
create_auth_user,
|
||||
update_auth_user,
|
||||
@@ -58,4 +62,4 @@ fn main() {
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
}
|
||||
@@ -1,74 +1,38 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Momentry Display Engine",
|
||||
"version": "0.1.0",
|
||||
"identifier": "com.momentry.markbase",
|
||||
"build": {
|
||||
"beforeBuildCommand": "cd src && npm run build",
|
||||
"beforeDevCommand": "cd src && npm run dev",
|
||||
"devPath": "http://localhost:5173",
|
||||
"distDir": "../src/dist"
|
||||
"devUrl": "http://localhost:5173",
|
||||
"frontendDist": "../src/dist"
|
||||
},
|
||||
"package": {
|
||||
"productName": "Momentry Display Engine",
|
||||
"version": "0.1.0"
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"category": "DeveloperTool",
|
||||
"copyright": "Copyright © 2026 Momentry",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"longDescription": "Momentry Display Engine - A Tauri-based desktop application for MarkBase management",
|
||||
"macOS": {
|
||||
"entitlements": null,
|
||||
"exceptionDomain": "",
|
||||
"frameworks": [],
|
||||
"providerShortName": null,
|
||||
"signingIdentity": null
|
||||
},
|
||||
"shortDescription": "Momentry Display Engine",
|
||||
"targets": "all"
|
||||
},
|
||||
"tauri": {
|
||||
"allowlist": {
|
||||
"all": false,
|
||||
"fs": {
|
||||
"all": true,
|
||||
"scope": ["$RESOURCE/**", "$APPDATA/**", "$HOME/**"]
|
||||
},
|
||||
"path": {
|
||||
"all": true
|
||||
},
|
||||
"http": {
|
||||
"all": true,
|
||||
"request": true,
|
||||
"scope": ["http://localhost:11438/**", "http://localhost:11439/**"]
|
||||
},
|
||||
"shell": {
|
||||
"all": true,
|
||||
"execute": true,
|
||||
"open": true
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"category": "DeveloperTool",
|
||||
"copyright": "Copyright © 2026 Momentry",
|
||||
"deb": {
|
||||
"depends": []
|
||||
},
|
||||
"externalBin": [],
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"identifier": "com.momentry.markbase",
|
||||
"longDescription": "Momentry Display Engine - A Tauri-based desktop application for MarkBase management",
|
||||
"macOS": {
|
||||
"entitlements": null,
|
||||
"exceptionDomain": "",
|
||||
"frameworks": [],
|
||||
"providerShortName": null,
|
||||
"signingIdentity": null
|
||||
},
|
||||
"resources": ["../../data/**"],
|
||||
"shortDescription": "Momentry Display Engine",
|
||||
"targets": "all",
|
||||
"windows": {
|
||||
"certificateThumbprint": null,
|
||||
"digestAlgorithm": "sha256",
|
||||
"timestampUrl": ""
|
||||
}
|
||||
},
|
||||
"security": {
|
||||
"csp": null
|
||||
},
|
||||
"updater": {
|
||||
"active": false
|
||||
},
|
||||
"app": {
|
||||
"withGlobalTauri": false,
|
||||
"windows": [
|
||||
{
|
||||
"fullscreen": false,
|
||||
@@ -80,4 +44,4 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,57 @@
|
||||
<script setup>
|
||||
import { onMounted } from 'vue'
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { useAppStore } from './stores/app'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
const appStore = useAppStore()
|
||||
const isLoggedIn = ref(false)
|
||||
const showLoginModal = ref(false)
|
||||
const loginForm = ref({
|
||||
username: 'demo',
|
||||
password: 'demo123'
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await appStore.initializeApp()
|
||||
isLoggedIn.value = true
|
||||
})
|
||||
|
||||
const handleLogin = async () => {
|
||||
if (!loginForm.value.username || !loginForm.value.password) {
|
||||
ElMessage.warning('Please enter username and password')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await appStore.login(loginForm.value.username, loginForm.value.password)
|
||||
if (result) {
|
||||
isLoggedIn.value = true
|
||||
showLoginModal.value = false
|
||||
loginForm.value.password = ''
|
||||
ElMessage.success('Login successful')
|
||||
} else {
|
||||
ElMessage.error('Login failed')
|
||||
}
|
||||
} catch (error) {
|
||||
ElMessage.error(`Login error: ${error}`)
|
||||
}
|
||||
}
|
||||
|
||||
const handleLogout = () => {
|
||||
appStore.logout()
|
||||
isLoggedIn.value = false
|
||||
appStore.user = ''
|
||||
ElMessage.success('Logout successful')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="app-container">
|
||||
<el-container>
|
||||
<el-header class="app-header">
|
||||
<h2>Momentry Display Engine</h2>
|
||||
<h2>Momentry Studio</h2>
|
||||
<div class="user-info">
|
||||
<span>User: {{ appStore.user }}</span>
|
||||
<span>User: {{ appStore.user || 'Guest' }}</span>
|
||||
</div>
|
||||
</el-header>
|
||||
<el-container>
|
||||
@@ -54,6 +90,32 @@ onMounted(async () => {
|
||||
<span>Monitor</span>
|
||||
</el-menu-item>
|
||||
</el-menu>
|
||||
|
||||
<!-- Login/Logout Section at bottom -->
|
||||
<div class="sidebar-bottom">
|
||||
<div class="user-display" v-if="isLoggedIn">
|
||||
<el-icon><UserFilled /></el-icon>
|
||||
<span class="username">{{ appStore.user }}</span>
|
||||
</div>
|
||||
<el-button
|
||||
v-if="isLoggedIn"
|
||||
type="danger"
|
||||
size="small"
|
||||
class="logout-btn"
|
||||
@click="handleLogout"
|
||||
>
|
||||
Logout
|
||||
</el-button>
|
||||
<el-button
|
||||
v-else
|
||||
type="primary"
|
||||
size="small"
|
||||
class="login-btn"
|
||||
@click="showLoginModal = true"
|
||||
>
|
||||
Login
|
||||
</el-button>
|
||||
</div>
|
||||
</el-aside>
|
||||
<el-main class="app-main">
|
||||
<router-view v-if="!appStore.loading" />
|
||||
@@ -64,6 +126,35 @@ onMounted(async () => {
|
||||
</el-main>
|
||||
</el-container>
|
||||
</el-container>
|
||||
|
||||
<!-- Login Modal -->
|
||||
<el-dialog
|
||||
v-model="showLoginModal"
|
||||
title="Login"
|
||||
width="300px"
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<el-form>
|
||||
<el-form-item label="Username">
|
||||
<el-input
|
||||
v-model="loginForm.username"
|
||||
placeholder="Enter username"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="Password">
|
||||
<el-input
|
||||
v-model="loginForm.password"
|
||||
type="password"
|
||||
placeholder="Enter password"
|
||||
show-password
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="showLoginModal = false">Cancel</el-button>
|
||||
<el-button type="primary" @click="handleLogin">Login</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -93,11 +184,36 @@ onMounted(async () => {
|
||||
.app-aside {
|
||||
background: #545c64;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.app-menu {
|
||||
border: none;
|
||||
background: transparent;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.sidebar-bottom {
|
||||
padding: 15px;
|
||||
border-top: 1px solid #666;
|
||||
background: #3a4149;
|
||||
}
|
||||
|
||||
.user-display {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: #fff;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.username {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.login-btn, .logout-btn {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.app-main {
|
||||
|
||||
@@ -57,6 +57,24 @@ export const useAppStore = defineStore('app', () => {
|
||||
}
|
||||
}
|
||||
|
||||
async function login(username, password) {
|
||||
try {
|
||||
const result = await invoke('auth_login', { username, password })
|
||||
if (result && result.success) {
|
||||
user.value = username
|
||||
return true
|
||||
}
|
||||
return false
|
||||
} catch (error) {
|
||||
console.error('Login error:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
user.value = ''
|
||||
}
|
||||
|
||||
return {
|
||||
currentTreeType,
|
||||
user,
|
||||
@@ -69,6 +87,8 @@ export const useAppStore = defineStore('app', () => {
|
||||
loadServiceStatus,
|
||||
loadHealthData,
|
||||
loadMonitorData,
|
||||
initializeApp
|
||||
initializeApp,
|
||||
login,
|
||||
logout
|
||||
}
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup>
|
||||
import { ref, onMounted, watch } from 'vue'
|
||||
import { ref, onMounted, watch, computed } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAppStore } from '../stores/app'
|
||||
import { invoke } from '@tauri-apps/api/tauri'
|
||||
@@ -10,6 +10,8 @@ import { open } from '@tauri-apps/api/dialog'
|
||||
const router = useRouter()
|
||||
const appStore = useAppStore()
|
||||
|
||||
const currentUser = computed(() => appStore.user || 'demo')
|
||||
|
||||
const treeData = ref([])
|
||||
const treeProps = {
|
||||
label: 'name',
|
||||
@@ -35,7 +37,7 @@ const formatFileSize = (bytes) => {
|
||||
const loadTree = async () => {
|
||||
try {
|
||||
const tree = await invoke('get_tree', {
|
||||
userId: 'demo',
|
||||
userId: currentUser.value,
|
||||
treeType: currentTreeType.value
|
||||
})
|
||||
treeData.value = [tree]
|
||||
@@ -49,7 +51,7 @@ const handleNodeClick = async (data) => {
|
||||
if (data.node_type === 'file') {
|
||||
try {
|
||||
const filePath = await invoke('download_file', {
|
||||
userId: 'demo',
|
||||
userId: currentUser.value,
|
||||
fileUuid: data.id
|
||||
})
|
||||
|
||||
@@ -85,7 +87,7 @@ const handleUpload = async () => {
|
||||
ElMessage.info(`Uploading ${fileName}...`)
|
||||
|
||||
const result = await invoke('upload_file', {
|
||||
userId: 'demo',
|
||||
userId: currentUser.value,
|
||||
sourcePath: sourcePath,
|
||||
targetPath: targetPath,
|
||||
treeType: currentTreeType.value
|
||||
@@ -111,6 +113,10 @@ watch(currentTreeType, () => {
|
||||
loadTree()
|
||||
})
|
||||
|
||||
watch(currentUser, () => {
|
||||
loadTree()
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await appStore.initializeApp()
|
||||
await loadTree()
|
||||
|
||||
Reference in New Issue
Block a user