diff --git a/src/api/mod.rs b/src/api/mod.rs index b1e28ce..94b725e 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -45,6 +45,10 @@ pub fn new_rpc_module(state: RpcState) -> RpcModule { .register_method("system.get_users", system::get_users) .unwrap(); + module + .register_method("system.create_user", system::create_user) + .unwrap(); + module .register_method("network.get_static_routes", network::get_static_routes) .unwrap(); diff --git a/src/api/system.rs b/src/api/system.rs index 01ec35e..631255b 100644 --- a/src/api/system.rs +++ b/src/api/system.rs @@ -2,9 +2,46 @@ use std::collections::HashMap; use crate::{definitions::system::User, state::RpcState}; use jsonrpsee::types::Params; +use pwhash::sha512_crypt; +use serde::Deserialize; use super::ApiError; pub fn get_users(_: Params, state: &RpcState) -> Result, ApiError> { Ok(state.config_manager.get_pending_config().system.users) } + +#[derive(Deserialize)] +struct CreateUser { + name: String, + password: String, + comment: String, +} + +pub fn create_user(p: Params, state: &RpcState) -> Result<(), ApiError> { + let u: CreateUser = p.parse().unwrap(); + + let hash = sha512_crypt::hash(u.password).unwrap(); + + let mut cm = state.config_manager.clone(); + let mut tx = cm.start_transaction(); + + if tx + .changes + .system + .users + .insert( + u.name, + User { + comment: u.comment, + hash: hash, + }, + ) + .is_none() + { + return tx.commit().map_err(|source| ApiError::InvalidParams); + } else { + tx.revert(); + Err(ApiError::InvalidParams) + } +}