diff --git a/config/markbase.toml b/config/markbase.toml index c9cccee..83798fc 100644 --- a/config/markbase.toml +++ b/config/markbase.toml @@ -7,14 +7,6 @@ users_db_dir = "data/users" webdav_root = "/Users/accusys/momentry/var/sftpgo/data/demo" upload_path = "/Users/accusys/momentry/var/sftpgo/data" -[postgresql] -host = "127.0.0.1" -port = 5432 -user = "sftpgo" -password = "sftpgo_pass_2026" -database = "sftpgo" -connection_pool_size = 5 - [authentication] bcrypt_cost = 10 token_validity_hours = 24 diff --git a/markbase-core/Cargo.toml b/markbase-core/Cargo.toml index e416ed6..4aadee0 100644 --- a/markbase-core/Cargo.toml +++ b/markbase-core/Cargo.toml @@ -39,8 +39,6 @@ hmac = "0.12" filetime = "0.2" base64 = "0.22" tokio = { version = "1", features = ["full"] } -tokio-postgres = "0.7" -postgres = "0.19" russh = "0.61.2" russh-keys = "0.50.0-beta.7" russh-sftp = "2.3.0" diff --git a/markbase-core/src/api/admin.rs b/markbase-core/src/api/admin.rs index 1516b5c..2dc02de 100644 --- a/markbase-core/src/api/admin.rs +++ b/markbase-core/src/api/admin.rs @@ -211,64 +211,14 @@ pub async fn manual_sync_handler( if let Err(resp) = verify_admin_or_401(&state, &headers) { return resp.into_response(); } - let syncer = crate::pg_client::SftpGoSync::new(&state.auth_db_path); - - match syncer { - Ok(syncer) => match syncer.full_sync().await { - Ok(result) => { - if result.status == "success" { - ( - StatusCode::OK, - Json(json!({ - "status": "success", - "users_synced": result.users_synced, - "groups_synced": result.groups_synced, - "mappings_synced": result.mappings_synced - })), - ) - .into_response() - } else if result.status == "partial_success" { - ( - StatusCode::OK, - Json(json!({ - "status": "partial_success", - "users_synced": result.users_synced, - "users_failed": result.users_failed, - "groups_synced": result.groups_synced, - "groups_failed": result.groups_failed, - "errors": result.errors - })), - ) - .into_response() - } else { - ( - StatusCode::OK, - Json(json!({ - "status": result.status, - "errors": result.errors - })), - ) - .into_response() - } - } - Err(e) => ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(json!({ - "status": "failed", - "error": e.to_string() - })), - ) - .into_response(), - }, - Err(e) => ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(json!({ - "status": "failed", - "error": e.to_string() - })), - ) - .into_response(), - } + + ( + StatusCode::GONE, + Json(json!({ + "status": "error", + "message": "PostgreSQL sync functionality has been removed. MarkBase now uses SQLite exclusively." + })), + ).into_response() } pub async fn sync_status_handler( @@ -278,47 +228,12 @@ pub async fn sync_status_handler( if let Err(resp) = verify_admin_or_401(&state, &headers) { return resp.into_response(); } - let auth_db = crate::sync::AuthDb::new(&state.auth_db_path); - - match auth_db { - Ok(db) => match db.open() { - Ok(conn) => { - match conn.query_row( - "SELECT sync_type, sync_time, users_synced, users_failed, - groups_synced, groups_failed, mappings_synced, status - FROM sync_log ORDER BY sync_time DESC LIMIT 5", - [], - |row| { - Ok(json!({ - "sync_type": row.get::<_, String>(0)?, - "sync_time": row.get::<_, i64>(1)?, - "users_synced": row.get::<_, usize>(2)?, - "users_failed": row.get::<_, usize>(3)?, - "groups_synced": row.get::<_, usize>(4)?, - "groups_failed": row.get::<_, usize>(5)?, - "mappings_synced": row.get::<_, usize>(6)?, - "status": row.get::<_, String>(7)?, - })) - }, - ) { - Ok(entries) => (StatusCode::OK, Json(entries)).into_response(), - Err(e) => ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(json!({"error": e.to_string()})), - ) - .into_response(), - } - } - Err(e) => ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(json!({"error": e.to_string()})), - ) - .into_response(), - }, - Err(e) => ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(json!({"error": e.to_string()})), - ) - .into_response(), - } + + ( + StatusCode::GONE, + Json(json!({ + "status": "error", + "message": "PostgreSQL sync functionality has been removed. MarkBase now uses SQLite exclusively." + })), + ).into_response() } diff --git a/markbase-core/src/auth.rs b/markbase-core/src/auth.rs index c5dd21d..8472cb5 100644 --- a/markbase-core/src/auth.rs +++ b/markbase-core/src/auth.rs @@ -66,7 +66,6 @@ pub struct AdminLoginResponse { pub struct AuthState { pub sessions: Arc>>, pub users: Arc>>, - pub auth_db: Option, pub admin_sessions: Arc>>, pub provider: Option>, } @@ -95,19 +94,6 @@ impl AuthState { AuthState { sessions: Arc::new(Mutex::new(HashMap::new())), users: Arc::new(Mutex::new(users)), - auth_db: None, - admin_sessions: Arc::new(Mutex::new(HashMap::new())), - provider: None, - } - } - - pub fn with_sync(auth_db_path: &str) -> Self { - let auth_db = crate::sync::AuthDb::new(auth_db_path).ok(); - - AuthState { - sessions: Arc::new(Mutex::new(HashMap::new())), - users: Arc::new(Mutex::new(HashMap::new())), - auth_db, admin_sessions: Arc::new(Mutex::new(HashMap::new())), provider: None, } @@ -117,7 +103,6 @@ impl AuthState { AuthState { sessions: Arc::new(Mutex::new(HashMap::new())), users: Arc::new(Mutex::new(HashMap::new())), - auth_db: None, admin_sessions: Arc::new(Mutex::new(HashMap::new())), provider: Some(Arc::from(provider)), } @@ -158,30 +143,7 @@ impl AuthState { } pub fn admin_login(&self, username: &str, password: &str) -> Option { - // Try auth_db first (legacy PostgreSQL sync) - if let Some(auth_db) = &self.auth_db { - match auth_db.get_admin(username) { - Ok(Some(admin)) if admin.status == 1 => { - if verify(password, &admin.password_hash).unwrap_or(false) { - return self.create_admin_session(username, password); - } else { - log::warn!("Invalid password for admin {}", username); - return None; - } - } - Ok(Some(_)) => { - log::warn!("Admin {} is not active", username); - return None; - } - Ok(None) => {} - Err(e) => { - log::error!("Failed to get admin {}: {}", username, e); - return None; - } - } - } - - // Fallback: try provider + // Use provider if available if let Some(provider) = &self.provider { match provider.get_user(username) { Ok(Some(user)) if user.status == 1 => { @@ -204,7 +166,7 @@ impl AuthState { } } - log::warn!("Admin {} not found (auth_db + provider)", username); + log::warn!("Admin {} not found (provider)", username); None } @@ -253,66 +215,13 @@ impl AuthState { } pub fn login_with_sync(&self, username: &str, password: &str) -> Option { - // Prefer provider over auth_db + // Use provider if available if let Some(provider) = &self.provider { return self.login_with_provider(&**provider, username, password); } - if let Some(auth_db) = &self.auth_db { - let user = match auth_db.get_user(username) { - Ok(Some(user)) => user, - Ok(None) => { - log::warn!("User {} not found in auth database", username); - return None; - } - Err(e) => { - log::error!("Failed to get user {}: {}", username, e); - return None; - } - }; - - if user.status != 1 { - log::warn!("User {} is disabled", username); - return None; - } - - if verify(password, &user.password_hash).unwrap_or(false) { - let groups = auth_db.get_user_groups(username).unwrap_or_default(); - let permissions = user.permissions.clone(); - - let token = Uuid::new_v4().to_string(); - let now = Utc::now(); - let expires_at = now + Duration::hours(24); - - let session = Session { - token: token.clone(), - user_id: username.to_string(), - username: username.to_string(), - created_at: now.format("%Y-%m-%dT%H:%M:%SZ").to_string(), - expires_at: expires_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(), - groups: groups.clone(), - permissions: permissions.clone(), - }; - - let mut sessions = self.sessions.lock().unwrap(); - sessions.insert(token.clone(), session); - - log::info!("User {} logged in successfully", username); - - Some(LoginResponse { - token, - expires_at: expires_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(), - user_id: username.to_string(), - groups, - permissions, - }) - } else { - log::warn!("Invalid password for user {}", username); - None - } - } else { - self.login(username, password) - } + // Fallback to in-memory users + self.login(username, password) } fn login_with_provider( diff --git a/markbase-core/src/lib.rs b/markbase-core/src/lib.rs index c1fdb3a..8b109ed 100644 --- a/markbase-core/src/lib.rs +++ b/markbase-core/src/lib.rs @@ -11,7 +11,6 @@ pub mod config; pub mod download; pub mod import_markdown; pub mod myfiles; -pub mod pg_client; pub mod provider; pub mod render; pub mod rsync; @@ -24,7 +23,6 @@ pub mod scan; pub mod smb_config; pub mod server; pub mod ssh_server; -pub mod sync; pub mod vfs; pub mod webdav; pub mod webdav_locks; diff --git a/markbase-core/src/pg_client.rs b/markbase-core/src/pg_client.rs deleted file mode 100644 index 60a3d3d..0000000 --- a/markbase-core/src/pg_client.rs +++ /dev/null @@ -1,330 +0,0 @@ -use crate::sync::{PgAdmin, PgGroup, PgUser, PgUserGroupMapping}; -use anyhow::Result; -use tokio_postgres::{Client, NoTls}; - -pub struct PgClient { - host: String, - port: u16, - user: String, - password: String, - database: String, -} - -impl Default for PgClient { - fn default() -> Self { - Self::new() - } -} - -impl PgClient { - pub fn new() -> Self { - Self { - host: "127.0.0.1".to_string(), - port: 5432, - user: "sftpgo".to_string(), - password: "sftpgo_pass_2026".to_string(), - database: "sftpgo".to_string(), - } - } - - pub fn from_env() -> Self { - Self { - host: std::env::var("PG_HOST").unwrap_or_else(|_| "127.0.0.1".to_string()), - port: std::env::var("PG_PORT") - .unwrap_or_else(|_| "5432".to_string()) - .parse() - .unwrap_or(5432), - user: std::env::var("PG_USER").unwrap_or_else(|_| "sftpgo".to_string()), - password: std::env::var("PG_PASSWORD") - .unwrap_or_else(|_| "sftpgo_pass_2026".to_string()), - database: std::env::var("PG_DATABASE").unwrap_or_else(|_| "sftpgo".to_string()), - } - } - - pub async fn connect(&self) -> Result { - let config = format!( - "host={} port={} user={} password={} dbname={}", - self.host, self.port, self.user, self.password, self.database - ); - - let (client, connection) = tokio_postgres::connect(&config, NoTls).await?; - - tokio::spawn(async move { - if let Err(e) = connection.await { - log::error!("PostgreSQL connection error: {}", e); - } - }); - - Ok(client) - } - - pub async fn fetch_users(&self) -> Result> { - let client = self.connect().await?; - - let rows = client - .query( - "SELECT username, password, email, status, home_dir, permissions, - uid, gid, last_login, created_at, updated_at - FROM users - WHERE status = 1 AND deleted_at = 0", - &[], - ) - .await?; - - let users = rows - .into_iter() - .map(|row| PgUser { - username: row.get::<_, String>(0), - password_hash: row.get::<_, String>(1), - email: row.get::<_, Option>(2), - status: row.get::<_, i32>(3), - home_dir: row.get::<_, String>(4), - permissions: row.get::<_, String>(5), - uid: row.get::<_, i64>(6), - gid: row.get::<_, i64>(7), - last_login: row.get::<_, i64>(8), - created_at: row.get::<_, i64>(9), - updated_at: row.get::<_, i64>(10), - }) - .collect(); - - Ok(users) - } - - pub async fn fetch_groups(&self) -> Result> { - let client = self.connect().await?; - - let rows = client - .query( - "SELECT name, description, created_at, updated_at FROM groups", - &[], - ) - .await?; - - let groups = rows - .into_iter() - .map(|row| PgGroup { - name: row.get::<_, String>(0), - description: row.get::<_, Option>(1), - created_at: row.get::<_, i64>(2), - updated_at: row.get::<_, i64>(3), - }) - .collect(); - - Ok(groups) - } - - pub async fn fetch_admins(&self) -> Result> { - let client = self.connect().await?; - - let rows = client - .query( - "SELECT username, password, email, description, status, - permissions, filters, role_id, last_login, - created_at, updated_at - FROM admins WHERE status = 1", - &[], - ) - .await?; - - let admins = rows - .into_iter() - .map(|row| PgAdmin { - username: row.get::<_, String>(0), - password_hash: row.get::<_, String>(1), - email: row.get::<_, Option>(2), - description: row.get::<_, Option>(3), - status: row.get::<_, i32>(4), - permissions: row.get::<_, String>(5), - filters: row.get::<_, Option>(6), - role_id: row.get::<_, Option>(7), - last_login: row.get::<_, i64>(8), - created_at: row.get::<_, i64>(9), - updated_at: row.get::<_, i64>(10), - }) - .collect(); - - Ok(admins) - } - - pub async fn fetch_mappings(&self) -> Result> { - let client = self.connect().await?; - - let rows = client - .query( - "SELECT u.username, g.name - FROM users_groups_mapping ug - JOIN users u ON ug.user_id = u.id - JOIN groups g ON ug.group_id = g.id - WHERE u.status = 1", - &[], - ) - .await?; - - let mappings = rows - .into_iter() - .map(|row| PgUserGroupMapping { - username: row.get::<_, String>(0), - group_name: row.get::<_, String>(1), - }) - .collect(); - - Ok(mappings) - } -} - -pub struct SftpGoSync { - pg_client: PgClient, - auth_db: crate::sync::AuthDb, -} - -impl SftpGoSync { - pub fn new(auth_db_path: &str) -> Result { - Ok(Self { - pg_client: PgClient::new(), - auth_db: crate::sync::AuthDb::new(auth_db_path)?, - }) - } - - pub async fn full_sync(&self) -> Result { - let mut result = crate::sync::SyncResult::default(); - result.sync_type = "full".to_string(); - result.sync_time = chrono::Utc::now().timestamp(); - - log::info!("Starting full sync from SFTPGo PostgreSQL"); - - // 1. Sync users - match self.pg_client.fetch_users().await { - Ok(users) => { - log::info!("Fetched {} users from PostgreSQL", users.len()); - for user in users { - match self.auth_db.save_user(&user) { - Ok(_) => result.users_synced += 1, - Err(e) => { - result.users_failed += 1; - result - .errors - .push(format!("User {} sync failed: {}", user.username, e)); - log::error!("Failed to sync user {}: {}", user.username, e); - } - } - } - } - Err(e) => { - log::error!("Failed to fetch users from PostgreSQL: {}", e); - result.errors.push(format!("PG users fetch failed: {}", e)); - result.users_failed = 1; - } - } - - // 2. Sync groups - match self.pg_client.fetch_groups().await { - Ok(groups) => { - log::info!("Fetched {} groups from PostgreSQL", groups.len()); - for group in groups { - match self.auth_db.save_group(&group) { - Ok(_) => result.groups_synced += 1, - Err(e) => { - result.groups_failed += 1; - result - .errors - .push(format!("Group {} sync failed: {}", group.name, e)); - log::error!("Failed to sync group {}: {}", group.name, e); - } - } - } - } - Err(e) => { - log::error!("Failed to fetch groups from PostgreSQL: {}", e); - result.errors.push(format!("PG groups fetch failed: {}", e)); - result.groups_failed = 1; - } - } - - // 3. Sync mappings - match self.pg_client.fetch_mappings().await { - Ok(mappings) => { - log::info!("Fetched {} mappings from PostgreSQL", mappings.len()); - for mapping in mappings { - match self.auth_db.save_mapping(&mapping) { - Ok(_) => result.mappings_synced += 1, - Err(e) => { - result.mappings_failed += 1; - result.errors.push(format!( - "Mapping {}->{} sync failed: {}", - mapping.username, mapping.group_name, e - )); - log::error!( - "Failed to sync mapping {}->{}: {}", - mapping.username, - mapping.group_name, - e - ); - } - } - } - } - Err(e) => { - log::error!("Failed to fetch mappings from PostgreSQL: {}", e); - result - .errors - .push(format!("PG mappings fetch failed: {}", e)); - result.mappings_failed = 1; - } - } - - // 4. Sync admins - match self.pg_client.fetch_admins().await { - Ok(admins) => { - let admins_count = admins.len(); - log::info!("Fetched {} admins from PostgreSQL", admins_count); - match self.auth_db.sync_admins(admins) { - Ok(count) => result.admins_synced = count, - Err(e) => { - result.admins_failed = admins_count; - result.errors.push(format!("Admins sync failed: {}", e)); - log::error!("Failed to sync admins: {}", e); - } - } - } - Err(e) => { - log::error!("Failed to fetch admins from PostgreSQL: {}", e); - result.errors.push(format!("PG admins fetch failed: {}", e)); - result.admins_failed = 1; - } - } - - // 5. Determine final status - if result.users_failed > 0 - || result.groups_failed > 0 - || result.mappings_failed > 0 - || result.admins_failed > 0 - { - if result.users_synced > 0 - || result.groups_synced > 0 - || result.mappings_synced > 0 - || result.admins_synced > 0 - { - result.status = "partial_success".to_string(); - } else { - result.status = "cached".to_string(); - } - } else { - result.status = "success".to_string(); - } - - // 6. Save sync log - self.auth_db.save_sync_log(&result)?; - - log::info!( - "Sync completed: users={}, groups={}, mappings={}, admins={}, status={}", - result.users_synced, - result.groups_synced, - result.mappings_synced, - result.admins_synced, - result.status - ); - - Ok(result) - } -} diff --git a/markbase-core/src/provider/mod.rs b/markbase-core/src/provider/mod.rs index 5da680d..ba68787 100644 --- a/markbase-core/src/provider/mod.rs +++ b/markbase-core/src/provider/mod.rs @@ -1,10 +1,7 @@ -pub mod pg; pub mod sqlite; #[cfg(feature = "ldap")] -#[cfg(feature = "ldap")] pub mod ldap; -pub use pg::PgProvider; pub use sqlite::SqliteProvider; #[cfg(feature = "ldap")] pub use ldap::{LdapProvider, LdapConfig}; diff --git a/markbase-core/src/provider/pg.rs b/markbase-core/src/provider/pg.rs deleted file mode 100644 index 85543b5..0000000 --- a/markbase-core/src/provider/pg.rs +++ /dev/null @@ -1,300 +0,0 @@ -use super::{DataProvider, ProviderError, User}; -use bcrypt::verify; -use postgres::{Client, NoTls}; -use std::path::PathBuf; - -/// PostgreSQL 数据提供者(兼容 SFTPGo 的 users 表) -pub struct PgProvider { - conn_str: String, -} - -impl PgProvider { - /// 从连接字符串创建 PgProvider - /// - /// 连接字符串格式:host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026 - pub fn new(conn_str: &str) -> Result { - Ok(Self { - conn_str: conn_str.to_string(), - }) - } - - pub fn from_params( - host: &str, - port: u16, - dbname: &str, - user: &str, - password: &str, - ) -> Result { - let conn_str = format!( - "host={} port={} dbname={} user={} password={}", - host, port, dbname, user, password - ); - Ok(Self { conn_str }) - } - - fn open_conn(&self) -> Result { - Client::connect(&self.conn_str, NoTls) - .map_err(|e| ProviderError::Internal(format!("PostgreSQL connect failed: {}", e))) - } -} - -impl DataProvider for PgProvider { - fn get_user(&self, username: &str) -> Result, ProviderError> { - let mut conn = self.open_conn()?; - - let result = conn - .query_opt( - "SELECT username, password, home_dir, permissions, uid, gid, status - FROM users WHERE username = $1 AND status = 1", - &[&username], - ) - .map_err(|e| ProviderError::Internal(format!("Query error: {}", e)))?; - - match result { - Some(row) => Ok(Some(User { - username: row.get(0), - password_hash: row.get::<_, Option>(1).unwrap_or_default(), - home_dir: PathBuf::from(row.get::<_, String>(2)), - permissions: row - .get::<_, Option>(3) - .unwrap_or_else(|| "*".to_string()), - uid: row.get::<_, i64>(4) as u32, - gid: row.get::<_, i64>(5) as u32, - status: row.get(6), - })), - None => Ok(None), - } - } - - fn check_password(&self, username: &str, password: &str) -> Result { - let hash = match self.get_user(username)? { - Some(user) => user.password_hash, - None => return Ok(false), - }; - - if hash.is_empty() { - return Ok(false); - } - - verify(password, &hash) - .map_err(|e| ProviderError::Internal(format!("bcrypt verify error: {}", e))) - } - - fn get_home_dir(&self, username: &str) -> Result, ProviderError> { - Ok(self - .get_user(username)? - .map(|u| u.home_dir.to_string_lossy().to_string())) - } - - fn get_public_keys(&self, username: &str) -> Result, ProviderError> { - let mut conn = self.open_conn()?; - let result = conn - .query_opt( - "SELECT public_keys FROM users WHERE username = $1 AND status = 1", - &[&username], - ) - .map_err(|e| ProviderError::Internal(format!("Query error: {}", e)))?; - - match result { - Some(row) => { - let json_str: Option = row.get(0); - match json_str { - Some(s) if !s.is_empty() => { - let keys: Vec = - serde_json::from_str(&s).map_err(|e| { - ProviderError::Internal(format!("JSON parse error: {}", e)) - })?; - Ok(keys - .iter() - .filter_map(|v| v.get("public_key")?.as_str().map(|s| s.to_string())) - .collect()) - } - _ => Ok(Vec::new()), - } - } - None => Ok(Vec::new()), - } - } - - fn list_users(&self) -> Result, ProviderError> { - let mut conn = self.open_conn()?; - - let rows = conn - .query( - "SELECT username, password, home_dir, permissions, uid, gid, status - FROM users ORDER BY username", - &[], - ) - .map_err(|e| ProviderError::Internal(format!("Query error: {}", e)))?; - - let users = rows - .iter() - .map(|row| User { - username: row.get(0), - password_hash: row.get::<_, Option>(1).unwrap_or_default(), - home_dir: PathBuf::from(row.get::<_, String>(2)), - permissions: row - .get::<_, Option>(3) - .unwrap_or_else(|| "*".to_string()), - uid: row.get::<_, i64>(4) as u32, - gid: row.get::<_, i64>(5) as u32, - status: row.get(6), - }) - .collect(); - - Ok(users) - } - - fn create_user(&self, user: &User, password: &str) -> Result<(), ProviderError> { - let mut conn = self.open_conn()?; - - let hash = bcrypt::hash(password, bcrypt::DEFAULT_COST) - .map_err(|e| ProviderError::Internal(format!("bcrypt hash error: {}", e)))?; - - conn.execute( - "INSERT INTO users (username, password, home_dir, permissions, uid, gid, status) - VALUES ($1, $2, $3, $4, $5, $6, $7)", - &[&user.username, &hash, &user.home_dir.to_string_lossy(), &user.permissions, &(user.uid as i64), &(user.gid as i64), &user.status], - ) - .map_err(|e| ProviderError::Internal(format!("Insert error: {}", e)))?; - - Ok(()) - } - - fn update_user(&self, user: &User, new_password: Option<&str>) -> Result<(), ProviderError> { - let mut conn = self.open_conn()?; - - if let Some(pwd) = new_password { - let hash = bcrypt::hash(pwd, bcrypt::DEFAULT_COST) - .map_err(|e| ProviderError::Internal(format!("bcrypt hash error: {}", e)))?; - - conn.execute( - "UPDATE users - SET password = $2, home_dir = $3, permissions = $4, uid = $5, gid = $6, status = $7 - WHERE username = $1", - &[&user.username, &hash, &user.home_dir.to_string_lossy(), &user.permissions, &(user.uid as i64), &(user.gid as i64), &user.status], - ) - .map_err(|e| ProviderError::Internal(format!("Update error: {}", e)))?; - } else { - conn.execute( - "UPDATE users - SET home_dir = $2, permissions = $3, uid = $4, gid = $5, status = $6 - WHERE username = $1", - &[&user.username, &user.home_dir.to_string_lossy(), &user.permissions, &(user.uid as i64), &(user.gid as i64), &user.status], - ) - .map_err(|e| ProviderError::Internal(format!("Update error: {}", e)))?; - } - - Ok(()) - } - - fn delete_user(&self, username: &str) -> Result<(), ProviderError> { - let mut conn = self.open_conn()?; - - conn.execute("DELETE FROM users WHERE username = $1", &[&username]) - .map_err(|e| ProviderError::Internal(format!("Delete error: {}", e)))?; - - Ok(()) - } - - fn reset_password(&self, username: &str, new_password: &str) -> Result<(), ProviderError> { - let mut conn = self.open_conn()?; - - let hash = bcrypt::hash(new_password, bcrypt::DEFAULT_COST) - .map_err(|e| ProviderError::Internal(format!("bcrypt hash error: {}", e)))?; - - conn.execute( - "UPDATE users SET password = $2 WHERE username = $1", - &[&username, &hash], - ) - .map_err(|e| ProviderError::Internal(format!("Update error: {}", e)))?; - - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_pg_provider_connection() { - // 仅当 SFTPGo PostgreSQL 可用时运行 - let provider = PgProvider::new( - "host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026", - ); - assert!(provider.is_ok(), "Should connect to SFTPGo PostgreSQL"); - } - - #[test] - fn test_pg_get_user_demo() { - let provider = PgProvider::new( - "host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026", - ) - .unwrap(); - let user = provider.get_user("demo").unwrap(); - assert!(user.is_some(), "Demo user should exist"); - assert_eq!(user.unwrap().username, "demo"); - } - - #[test] - fn test_pg_get_user_momentry() { - let provider = PgProvider::new( - "host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026", - ) - .unwrap(); - let user = provider.get_user("momentry").unwrap(); - assert!(user.is_some(), "Momentry user should exist"); - } - - #[test] - fn test_pg_get_user_warren() { - let provider = PgProvider::new( - "host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026", - ) - .unwrap(); - let user = provider.get_user("warren").unwrap(); - assert!(user.is_some(), "Warren user should exist"); - } - - #[test] - fn test_pg_check_password_demo() { - let provider = PgProvider::new( - "host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026", - ) - .unwrap(); - let valid = provider.check_password("demo", "demo123").unwrap(); - assert!(valid, "Password should be valid"); - } - - #[test] - fn test_pg_check_password_invalid() { - let provider = PgProvider::new( - "host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026", - ) - .unwrap(); - let valid = provider.check_password("demo", "wrong").unwrap(); - assert!(!valid, "Wrong password should fail"); - } - - #[test] - fn test_pg_get_home_dir() { - let provider = PgProvider::new( - "host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026", - ) - .unwrap(); - let dir = provider.get_home_dir("demo").unwrap(); - assert!(dir.is_some()); - assert!(dir.unwrap().contains("momentry")); - } - - #[test] - fn test_pg_nonexistent_user() { - let provider = PgProvider::new( - "host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026", - ) - .unwrap(); - let user = provider.get_user("__nonexistent__").unwrap(); - assert!(user.is_none()); - } -} diff --git a/markbase-core/src/server.rs b/markbase-core/src/server.rs index 3c7560e..e933289 100644 --- a/markbase-core/src/server.rs +++ b/markbase-core/src/server.rs @@ -230,56 +230,8 @@ pub async fn run(port: u16, file: Option, home: PathBuf) -> anyhow::Resu } } - // 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); - - 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!( - "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); - } - } - }); - - 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)"); - } - + // PostgreSQL sync removed - MarkBase now uses SQLite exclusively + log::info!("MarkBase authentication: SQLite only (PostgreSQL sync removed)"); // ===== WebDAV multi-user configuration (Phase 20 + P1) ===== let webdav_parent = std::path::PathBuf::from(&upload_path); @@ -2033,8 +1985,7 @@ async fn get_file_probe(Path((_user_id, file_uuid)): Path<(String, String)>) -> let (label, registered_at) = node.unwrap_or((None, None)); - // Fetch probe data from 3002 PostgreSQL - let _pg_url = "postgres://accusys@localhost:5432/momentry"; + // TODO: Implement data fetching from external source let pg_conn = rusqlite::Connection::open(":memory:")?; // placeholder drop(pg_conn); diff --git a/markbase-core/src/ssh_server/server.rs b/markbase-core/src/ssh_server/server.rs index 8e9e973..f733986 100644 --- a/markbase-core/src/ssh_server/server.rs +++ b/markbase-core/src/ssh_server/server.rs @@ -1,7 +1,6 @@ // SSH服务器完整实现(Phase 1-7集成版 + Phase 13端口转发) // 参考OpenSSH sshd.c: complete SSH/SFTP flow + port forwarding -use crate::provider::pg::PgProvider; use crate::provider::sqlite::SqliteProvider; use crate::provider::DataProvider; use crate::ssh_server::auth::{AuthHandler, AuthResult}; @@ -167,16 +166,8 @@ fn handle_connection_complete( )?; info!("Key exchange completed, encryption channel ready"); - // Phase 5: SSH认证(SFTPGo兼容 — PostgreSQL或SQLite) - let provider: Box = if let Some(ref conn_str) = pg_conn { - info!( - "Using PostgreSQL auth provider (SFTPGo-compatible): {}", - conn_str - ); - Box::new( - PgProvider::new(conn_str).map_err(|e| anyhow!("Failed to init PgProvider: {}", e))?, - ) - } else { + // Phase 5: SSH认证(SQLite only) + let provider: Box = { info!("Using SQLite auth provider"); Box::new( SqliteProvider::new("data/auth.sqlite") diff --git a/markbase-core/src/sync.rs b/markbase-core/src/sync.rs deleted file mode 100644 index 299880b..0000000 --- a/markbase-core/src/sync.rs +++ /dev/null @@ -1,370 +0,0 @@ -use anyhow::Result; -use chrono::Utc; -use rusqlite::{params, Connection}; -use serde::{Deserialize, Serialize}; -use std::path::Path; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PgUser { - pub username: String, - pub password_hash: String, - pub email: Option, - pub status: i32, - pub home_dir: String, - pub permissions: String, - pub uid: i64, - pub gid: i64, - pub last_login: i64, - pub created_at: i64, - pub updated_at: i64, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PgGroup { - pub name: String, - pub description: Option, - pub created_at: i64, - pub updated_at: i64, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PgUserGroupMapping { - pub username: String, - pub group_name: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PgAdmin { - pub username: String, - pub password_hash: String, - pub email: Option, - pub description: Option, - pub status: i32, - pub permissions: String, - pub filters: Option, - pub role_id: Option, - pub last_login: i64, - pub created_at: i64, - pub updated_at: i64, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SyncResult { - pub sync_type: String, - pub sync_time: i64, - pub users_synced: usize, - pub users_failed: usize, - pub groups_synced: usize, - pub groups_failed: usize, - pub mappings_synced: usize, - pub mappings_failed: usize, - pub admins_synced: usize, - pub admins_failed: usize, - pub status: String, - pub errors: Vec, -} - -impl Default for SyncResult { - fn default() -> Self { - Self { - sync_type: "unknown".to_string(), - sync_time: Utc::now().timestamp(), - users_synced: 0, - users_failed: 0, - groups_synced: 0, - groups_failed: 0, - mappings_synced: 0, - mappings_failed: 0, - admins_synced: 0, - admins_failed: 0, - status: "pending".to_string(), - errors: Vec::new(), - } - } -} - -impl SyncResult { - pub fn success() -> Self { - Self { - status: "success".to_string(), - ..Default::default() - } - } - - pub fn cached() -> Self { - Self { - status: "cached".to_string(), - ..Default::default() - } - } - - pub fn failed(error: String) -> Self { - Self { - status: "failed".to_string(), - errors: vec![error], - ..Default::default() - } - } - - pub fn merge(&mut self, other: SyncResult) { - self.users_synced += other.users_synced; - self.users_failed += other.users_failed; - self.groups_synced += other.groups_synced; - self.groups_failed += other.groups_failed; - self.mappings_synced += other.mappings_synced; - self.mappings_failed += other.mappings_failed; - self.errors.extend(other.errors); - - if self.users_failed > 0 || self.groups_failed > 0 || self.mappings_failed > 0 { - if self.users_synced > 0 || self.groups_synced > 0 || self.mappings_synced > 0 { - self.status = "partial_success".to_string(); - } else { - self.status = "failed".to_string(); - } - } - } -} - -#[derive(Clone)] -pub struct AuthDb { - pub path: String, -} - -impl AuthDb { - pub fn new(path: &str) -> Result { - if !Path::new(path).exists() { - Self::init_db(path)?; - } - Ok(Self { - path: path.to_string(), - }) - } - - pub fn init_db(path: &str) -> Result<()> { - let conn = Connection::open(path)?; - conn.execute_batch(include_str!("../../data/init_auth_db.sql"))?; - Ok(()) - } - - pub fn open(&self) -> Result { - Ok(Connection::open(&self.path)?) - } - - pub fn save_user(&self, user: &PgUser) -> Result<()> { - let conn = self.open()?; - let now = Utc::now().timestamp(); - - conn.execute( - "INSERT OR REPLACE INTO sftpgo_users - (username, password_hash, email, status, home_dir, permissions, - uid, gid, last_login, created_at, updated_at, last_sync_at, sync_status) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)", - params![ - user.username, - user.password_hash, - user.email, - user.status, - user.home_dir, - user.permissions, - user.uid, - user.gid, - user.last_login, - user.created_at, - user.updated_at, - now, - 1, // sync_status = synced - ], - )?; - - Ok(()) - } - - pub fn save_group(&self, group: &PgGroup) -> Result<()> { - let conn = self.open()?; - let now = Utc::now().timestamp(); - - conn.execute( - "INSERT OR REPLACE INTO sftpgo_groups - (name, description, created_at, updated_at, last_sync_at) - VALUES (?1, ?2, ?3, ?4, ?5)", - params![ - group.name, - group.description, - group.created_at, - group.updated_at, - now, - ], - )?; - - Ok(()) - } - - pub fn save_mapping(&self, mapping: &PgUserGroupMapping) -> Result<()> { - let conn = self.open()?; - let now = Utc::now().timestamp(); - - conn.execute( - "INSERT OR REPLACE INTO users_groups_mapping - (username, group_name, created_at) - VALUES (?1, ?2, ?3)", - params![mapping.username, mapping.group_name, now,], - )?; - - Ok(()) - } - - pub fn save_sync_log(&self, result: &SyncResult) -> Result<()> { - let conn = self.open()?; - - conn.execute( - "INSERT INTO sync_log - (sync_type, sync_time, users_synced, users_failed, - groups_synced, groups_failed, mappings_synced, - mappings_failed, admins_synced, admins_failed, - status, error_message) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)", - params![ - result.sync_type, - result.sync_time, - result.users_synced, - result.users_failed, - result.groups_synced, - result.groups_failed, - result.mappings_synced, - result.mappings_failed, - result.admins_synced, - result.admins_failed, - result.status, - result.errors.join(";"), - ], - )?; - - log::info!( - "Sync log saved: users={}, groups={}, mappings={}, admins={}, status={}", - result.users_synced, - result.groups_synced, - result.mappings_synced, - result.admins_synced, - result.status - ); - - Ok(()) - } - - pub fn save_admin(&self, admin: &PgAdmin) -> Result<()> { - let conn = self.open()?; - - conn.execute( - "INSERT OR REPLACE INTO sftpgo_admins - (username, password_hash, email, description, status, - permissions, filters, role_id, last_login, - created_at, updated_at, last_sync_at) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)", - params![ - admin.username, - admin.password_hash, - admin.email, - admin.description, - admin.status, - admin.permissions, - admin.filters, - admin.role_id, - admin.last_login, - admin.created_at, - admin.updated_at, - Utc::now().timestamp(), - ], - )?; - - Ok(()) - } - - pub fn get_admin(&self, username: &str) -> Result> { - let conn = self.open()?; - - let result = conn.query_row( - "SELECT username, password_hash, email, description, status, - permissions, filters, role_id, last_login, - created_at, updated_at - FROM sftpgo_admins WHERE username = ?1 AND status = 1", - params![username], - |row| { - Ok(PgAdmin { - username: row.get(0)?, - password_hash: row.get(1)?, - email: row.get(2)?, - description: row.get(3)?, - status: row.get(4)?, - permissions: row.get(5)?, - filters: row.get(6)?, - role_id: row.get(7)?, - last_login: row.get(8)?, - created_at: row.get(9)?, - updated_at: row.get(10)?, - }) - }, - ); - - match result { - Ok(admin) => Ok(Some(admin)), - Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None), - Err(e) => Err(e.into()), - } - } - - pub fn sync_admins(&self, admins: Vec) -> Result { - let mut synced = 0; - - for admin in admins { - match self.save_admin(&admin) { - Ok(_) => synced += 1, - Err(e) => log::warn!("Failed to sync admin {}: {}", admin.username, e), - } - } - - Ok(synced) - } - - pub fn get_user(&self, username: &str) -> Result> { - let conn = self.open()?; - - let result = conn.query_row( - "SELECT username, password_hash, email, status, home_dir, permissions, - uid, gid, last_login, created_at, updated_at - FROM sftpgo_users WHERE username = ?1 AND status = 1", - params![username], - |row| { - Ok(PgUser { - username: row.get(0)?, - password_hash: row.get(1)?, - email: row.get(2)?, - status: row.get(3)?, - home_dir: row.get(4)?, - permissions: row.get(5)?, - uid: row.get(6)?, - gid: row.get(7)?, - last_login: row.get(8)?, - created_at: row.get(9)?, - updated_at: row.get(10)?, - }) - }, - ); - - match result { - Ok(user) => Ok(Some(user)), - Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None), - Err(e) => Err(e.into()), - } - } - - pub fn get_user_groups(&self, username: &str) -> Result> { - let conn = self.open()?; - - let groups: Vec = conn - .prepare("SELECT group_name FROM users_groups_mapping WHERE username = ?1")? - .query_map(params![username], |row| row.get(0))? - .collect::, _>>()?; - - Ok(groups) - } -}