feat: add user management handlers (SQLite-based)
- Add CreateUserRequest, UpdateUserRequest, ChangePasswordRequest - Implement list_users_handler, create_user_handler - Implement delete_user_handler, update_user_handler - Implement change_password_handler - All handlers use SQLite (data/auth.sqlite) - No PostgreSQL dependency - Routes: /api/v2/admin/users/* - Integrated from M5Max48 into M4Mini architecture - Fix duplicate dependencies in Cargo.toml - Resolve merge conflicts in web.rs and Cargo.lock
This commit is contained in:
@@ -237,3 +237,226 @@ pub async fn sync_status_handler(
|
||||
})),
|
||||
).into_response()
|
||||
}
|
||||
|
||||
// === User Management Handlers ===
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateUserRequest {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
#[serde(default)]
|
||||
pub home_dir: Option<String>,
|
||||
#[serde(default = "default_status")]
|
||||
pub status: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct UpdateUserRequest {
|
||||
pub home_dir: Option<String>,
|
||||
pub status: Option<i64>,
|
||||
pub permissions: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ChangePasswordRequest {
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
fn default_status() -> i64 { 1 }
|
||||
|
||||
fn verify_admin_token_or_401(
|
||||
state: &AppState,
|
||||
headers: &HeaderMap,
|
||||
) -> Result<(), impl IntoResponse> {
|
||||
let auth_header = headers
|
||||
.get("Authorization")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "));
|
||||
|
||||
match auth_header {
|
||||
Some(token) if state.auth.verify_admin_token(token).is_some() => Ok(()),
|
||||
_ => Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({"ok": false, "error": "Invalid admin token"})),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list_users_handler(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(resp) = verify_admin_token_or_401(&state, &headers) {
|
||||
return resp.into_response();
|
||||
}
|
||||
|
||||
let conn = match rusqlite::Connection::open("data/auth.sqlite") {
|
||||
Ok(c) => c,
|
||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
};
|
||||
|
||||
let mut stmt = match conn.prepare("SELECT username, status, home_dir, permissions, created_at FROM sftpgo_users ORDER BY username") {
|
||||
Ok(s) => s,
|
||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
};
|
||||
|
||||
let users: Vec<serde_json::Value> = match stmt.query_map([], |row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, i64>(1)?,
|
||||
row.get::<_, Option<String>>(2)?,
|
||||
row.get::<_, Option<String>>(3)?,
|
||||
row.get::<_, Option<i64>>(4)?,
|
||||
))
|
||||
}) {
|
||||
Ok(m) => m.filter_map(|r| r.ok()).map(|(username, status, home_dir, permissions, created_at)| {
|
||||
json!({
|
||||
"username": username,
|
||||
"status": status,
|
||||
"home_dir": home_dir,
|
||||
"permissions": permissions,
|
||||
"created_at": created_at,
|
||||
})
|
||||
}).collect(),
|
||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
};
|
||||
|
||||
(StatusCode::OK, Json(json!({"users": users, "total": users.len()}))).into_response()
|
||||
}
|
||||
|
||||
pub async fn create_user_handler(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<CreateUserRequest>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(resp) = verify_admin_token_or_401(&state, &headers) {
|
||||
return resp.into_response();
|
||||
}
|
||||
|
||||
let conn = match rusqlite::Connection::open("data/auth.sqlite") {
|
||||
Ok(c) => c,
|
||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
};
|
||||
|
||||
let username = body.username.clone();
|
||||
let exists: i64 = match conn.query_row("SELECT COUNT(*) FROM sftpgo_users WHERE username = ?", [&username], |row| row.get(0)) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
};
|
||||
|
||||
if exists > 0 {
|
||||
return (StatusCode::CONFLICT, Json(json!({"error": "User already exists"}))).into_response();
|
||||
}
|
||||
|
||||
let password_hash = match bcrypt::hash(&body.password, bcrypt::DEFAULT_COST) {
|
||||
Ok(h) => h,
|
||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
};
|
||||
|
||||
let home_dir = body.home_dir.unwrap_or_else(|| format!("/Users/accusys/momentry/var/sftpgo/data/{}", username));
|
||||
|
||||
match conn.execute(
|
||||
"INSERT INTO sftpgo_users (username, password_hash, home_dir, status, permissions) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
rusqlite::params![username, password_hash, home_dir, body.status, "{\"/\": [\"*\"]}"],
|
||||
) {
|
||||
Ok(_) => (StatusCode::CREATED, Json(json!({"ok": true, "username": username}))).into_response(),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_user_handler(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
Path(username): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(resp) = verify_admin_token_or_401(&state, &headers) {
|
||||
return resp.into_response();
|
||||
}
|
||||
|
||||
let conn = match rusqlite::Connection::open("data/auth.sqlite") {
|
||||
Ok(c) => c,
|
||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
};
|
||||
|
||||
match conn.execute("DELETE FROM sftpgo_users WHERE username = ?", [&username]) {
|
||||
Ok(0) => (StatusCode::NOT_FOUND, Json(json!({"error": "User not found"}))).into_response(),
|
||||
Ok(_) => (StatusCode::OK, Json(json!({"ok": true, "username": username}))).into_response(),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn change_password_handler(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
Path(username): Path<String>,
|
||||
Json(body): Json<ChangePasswordRequest>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(resp) = verify_admin_token_or_401(&state, &headers) {
|
||||
return resp.into_response();
|
||||
}
|
||||
|
||||
let conn = match rusqlite::Connection::open("data/auth.sqlite") {
|
||||
Ok(c) => c,
|
||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
};
|
||||
|
||||
let password_hash = match bcrypt::hash(&body.password, bcrypt::DEFAULT_COST) {
|
||||
Ok(h) => h,
|
||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
};
|
||||
|
||||
match conn.execute("UPDATE sftpgo_users SET password_hash = ?1 WHERE username = ?2", rusqlite::params![password_hash, username]) {
|
||||
Ok(0) => (StatusCode::NOT_FOUND, Json(json!({"error": "User not found"}))).into_response(),
|
||||
Ok(_) => (StatusCode::OK, Json(json!({"ok": true, "username": username}))).into_response(),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_user_handler(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
Path(username): Path<String>,
|
||||
Json(body): Json<UpdateUserRequest>,
|
||||
) -> impl IntoResponse {
|
||||
if let Err(resp) = verify_admin_token_or_401(&state, &headers) {
|
||||
return resp.into_response();
|
||||
}
|
||||
|
||||
let conn = match rusqlite::Connection::open("data/auth.sqlite") {
|
||||
Ok(c) => c,
|
||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
};
|
||||
|
||||
let mut updates = Vec::new();
|
||||
let mut params: Vec<Box<dyn rusqlite::types::ToSql>> = Vec::new();
|
||||
|
||||
if let Some(home_dir) = &body.home_dir {
|
||||
updates.push("home_dir = ?");
|
||||
params.push(Box::new(home_dir.clone()));
|
||||
}
|
||||
if let Some(status) = body.status {
|
||||
updates.push("status = ?");
|
||||
params.push(Box::new(status));
|
||||
}
|
||||
if let Some(permissions) = &body.permissions {
|
||||
updates.push("permissions = ?");
|
||||
params.push(Box::new(permissions.clone()));
|
||||
}
|
||||
|
||||
if updates.is_empty() {
|
||||
return (StatusCode::BAD_REQUEST, Json(json!({"error": "No fields to update"}))).into_response();
|
||||
}
|
||||
|
||||
updates.push("updated_at = datetime('now')");
|
||||
params.push(Box::new(username.clone()));
|
||||
|
||||
let sql = format!("UPDATE sftpgo_users SET {} WHERE username = ?", updates.join(", "));
|
||||
|
||||
match conn.execute(&sql, rusqlite::params_from_iter(params.iter().map(|p| p.as_ref()))) {
|
||||
Ok(0) => (StatusCode::NOT_FOUND, Json(json!({"error": "User not found"}))).into_response(),
|
||||
Ok(_) => (StatusCode::OK, Json(json!({"ok": true, "username": username}))).into_response(),
|
||||
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,14 +9,16 @@ pub enum WebCommand {
|
||||
port: u16,
|
||||
#[arg(short, long)]
|
||||
file: Option<String>,
|
||||
#[arg(short = 'H', long, help = "User home directory for data storage (default: current user's home)")]
|
||||
home: Option<PathBuf>,
|
||||
},
|
||||
}
|
||||
|
||||
pub async fn handle_web_command(cmd: WebCommand) -> anyhow::Result<()> {
|
||||
match cmd {
|
||||
WebCommand::Start { port, file } => {
|
||||
let home = dirs::home_dir()
|
||||
.ok_or_else(|| anyhow::anyhow!("Cannot determine home directory"))?;
|
||||
WebCommand::Start { port, file, home } => {
|
||||
let home = home.unwrap_or_else(|| dirs::home_dir().unwrap_or_else(|| PathBuf::from(".")));
|
||||
log::info!("Using home directory: {}", home.display());
|
||||
crate::server::run(port, file, home).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user