From 3c538b44acfc9c16d22b0ae4c0bb780accb3cbae Mon Sep 17 00:00:00 2001 From: plazmoid Date: Mon, 17 Aug 2020 02:22:17 +0500 Subject: [PATCH] password-protected panel --- bin/u_agent/Cargo.toml | 2 +- bin/u_agent/src/main.rs | 3 +- bin/u_panel/Cargo.toml | 2 +- bin/u_panel/src/main.rs | 26 ++++++------- bin/u_server/Cargo.toml | 8 ++-- bin/u_server/src/main.rs | 57 ++++++---------------------- lib/u_lib/Cargo.toml | 3 +- lib/u_lib/src/client/client.rs | 7 +--- lib/u_lib/src/client/network.rs | 50 ++++++++++++++---------- lib/u_lib/src/config.rs | 2 +- lib/u_lib/src/contracts/datatypes.rs | 30 +++++++++++++-- lib/u_lib/src/contracts/jobs.rs | 2 +- lib/u_lib/src/contracts/messaging.rs | 4 ++ 13 files changed, 98 insertions(+), 98 deletions(-) diff --git a/bin/u_agent/Cargo.toml b/bin/u_agent/Cargo.toml index a1cc023..c6dcc20 100644 --- a/bin/u_agent/Cargo.toml +++ b/bin/u_agent/Cargo.toml @@ -7,7 +7,7 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -tokio = { version = "*", features = ["macros", "rt-core", "process", "blocking"] } +tokio = { version = "0.2.22", features = ["macros", "rt-core", "process", "blocking"] } sysinfo = "0.10.5" log = "^0.4" env_logger = "0.7.1" diff --git a/bin/u_agent/src/main.rs b/bin/u_agent/src/main.rs index 031de83..5ec5a77 100644 --- a/bin/u_agent/src/main.rs +++ b/bin/u_agent/src/main.rs @@ -15,7 +15,7 @@ use { u_lib::client::* }; -mod executor; +//mod executor; use network::ClientHandler; @@ -25,7 +25,6 @@ async fn main() { let instance = ClientHandler::new(); instance.init().await; loop { - instance.list().await; sleep(Duration::from_secs(2)); } } diff --git a/bin/u_panel/Cargo.toml b/bin/u_panel/Cargo.toml index c28bc03..d9a4b71 100644 --- a/bin/u_panel/Cargo.toml +++ b/bin/u_panel/Cargo.toml @@ -7,7 +7,7 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -tokio = { version = "*", features = ["macros", "rt-core", "process", "blocking"] } +tokio = { version = "0.2.22", features = ["macros", "rt-core", "process", "blocking"] } log = "^0.4" env_logger = "0.7.1" uuid = "0.8.1" diff --git a/bin/u_panel/src/main.rs b/bin/u_panel/src/main.rs index 9a05098..e427fb7 100644 --- a/bin/u_panel/src/main.rs +++ b/bin/u_panel/src/main.rs @@ -1,13 +1,9 @@ use std::env::args; -use std::future::Future; -use u_lib::client::network::ClientHandler; +use u_lib::{ + client::network::ClientHandler, + //client::* +}; -fn get_cmd_handler(cli_handler: &ClientHandler, method: &str) -> Option { - match method { - "ls" => Some(cli_handler.list()), - _ => None - } -} #[tokio::main] async fn main() -> Result<(), &'static str> { @@ -17,11 +13,15 @@ async fn main() -> Result<(), &'static str> { Some(m) => m, None => return Err("Method required") }; - let instance = ClientHandler::new(); - let future = match get_cmd_handler(&instance, &method) { - Some(c) => c, - None => return Err("Unknown method") + let cli_handler = ClientHandler::new_pwd("123qwe".to_string()); + match method.as_str() { + "ls" => { + let result = cli_handler.list().await; + for cli in result.iter() { + println!("{:?}", cli) + } + }, + _ => return Err("Unknown method") }; - future.await; Ok(()) } diff --git a/bin/u_server/Cargo.toml b/bin/u_server/Cargo.toml index 74e56ef..816b2ab 100644 --- a/bin/u_server/Cargo.toml +++ b/bin/u_server/Cargo.toml @@ -7,10 +7,10 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -warp = "*" +warp = "0.2.4" serde = { version = "1.0.114", features = ["derive"] } -tokio = { version = "*", features = ["macros"] } -log = "*" -env_logger = "*" +tokio = { version = "0.2.22", features = ["macros"] } +log = "0.4.11" +env_logger = "0.7.1" uuid = "0.8.1" u_lib = { version = "*", path = "../../lib/u_lib" } \ No newline at end of file diff --git a/bin/u_server/src/main.rs b/bin/u_server/src/main.rs index bf8b2e6..00ed177 100644 --- a/bin/u_server/src/main.rs +++ b/bin/u_server/src/main.rs @@ -1,21 +1,15 @@ +mod handlers; + use warp::{ Filter, Rejection, Reply, body }; -use std::{ - collections::HashMap, - sync::Arc -}; use env_logger; -use tokio::sync::Mutex; -use uuid::Uuid; -use tokio::join; use u_lib::{ MASTER_PORT, contracts::*, - client::* }; @@ -24,58 +18,31 @@ fn get_content() -> impl Filter,), body::content_length_limit(1024*64).and(body::json::>()) } -async fn add_client(msg: Message<'_, ClientInfo>, - db: SharedStorage) -> Result { - let new_cli = msg.item; - let mut clients = db.lock().await; - if clients.contains_key(&new_cli.id) { - Ok(warp::reply::json( - &RawMsg("Already exist".to_string()).into_message() - )) - } else { - clients.insert( - new_cli.id.clone(), - UClient::new(new_cli.into_owned()) - ); - Ok(warp::reply::json( - &RawMsg("Added".to_string()).into_message() - )) - } -} - -async fn listing(db: SharedStorage) -> Result { - let clients = db.lock().await; - let mut result: Vec = Vec::with_capacity(clients.len()); - for cli in clients.values() { - result.push(cli.client_info.clone()); - } - Ok(warp::reply::json( - &Message::new_owned(result) - )) -} - #[tokio::main] async fn main() { env_logger::init(); - let base_db: SharedStorage = Arc::new( - Mutex::new(HashMap::::new()) - ); - let db = warp::any().map(move || Arc::clone(&base_db)); + let base_db = Storage::new(); + let db = warp::any().map(move || base_db.clone()); let new_client = warp::post() .and(warp::path("new")) .and(get_content()) .and(db.clone()) - .and_then(add_client); + .and_then(handlers::add_client); let ls = warp::get() .and(warp::path("ls")) .and(db.clone()) - .and_then(listing); + .and_then(handlers::listing); + + let auth_token = warp::header::exact("authorization", "Bearer 123qwe"); + //.and_then(handlers::check_token); + + let auth_zone = auth_token.and(ls); let routes = new_client - .or(ls) + .or(auth_zone) .with(warp::log("warp")); warp::serve(routes) .run(([0,0,0,0], MASTER_PORT)).await; diff --git a/lib/u_lib/Cargo.toml b/lib/u_lib/Cargo.toml index 580c247..fc16abc 100644 --- a/lib/u_lib/Cargo.toml +++ b/lib/u_lib/Cargo.toml @@ -12,5 +12,6 @@ uuid = { version = "^0.8.1", features = ["serde", "v4"] } nix = "0.17" libc = "^0.2" lazy_static = "1.4.0" -tokio = { version = "*", features = ["macros", "process"] } +tokio = { version = "0.2.22", features = ["macros", "process"] } reqwest = { version = "0.10.7", features = ["json"] } +bytes = "0.5.6" diff --git a/lib/u_lib/src/client/client.rs b/lib/u_lib/src/client/client.rs index b62b74f..1b28cdc 100644 --- a/lib/u_lib/src/client/client.rs +++ b/lib/u_lib/src/client/client.rs @@ -2,9 +2,6 @@ use serde::{ Deserialize, Serialize }; -use std::{ - collections::HashMap -}; use uuid::Uuid; use crate::{ contracts::*, @@ -15,15 +12,13 @@ use crate::{ pub struct UClient { pub client_info: ClientInfo, pub jobs: JobPool, // TODO: to futures - pub is_admin: bool, } impl UClient { pub fn new(client_info: ClientInfo) -> Self { Self { client_info, - jobs: Vec::new(), - is_admin: false + jobs: Vec::new() } } } diff --git a/lib/u_lib/src/client/network.rs b/lib/u_lib/src/client/network.rs index ce85107..ddd3681 100644 --- a/lib/u_lib/src/client/network.rs +++ b/lib/u_lib/src/client/network.rs @@ -2,7 +2,6 @@ use crate::{ MASTER_SERVER, MASTER_PORT, contracts::*, - client::* }; use reqwest::{ Client, @@ -15,7 +14,8 @@ use reqwest::{ pub struct ClientHandler { base_url: Url, client: Client, - cli_info: ClientInfo + cli_info: ClientInfo, + password: Option } impl ClientHandler { @@ -25,44 +25,56 @@ impl ClientHandler { cli_info: ClientInfo::gather(), base_url: Url::parse( &format!("http://{}:{}", MASTER_SERVER, MASTER_PORT) - ).unwrap() + ).unwrap(), + password: None + } + } + + pub fn new_pwd(password: String) -> Self { + let mut instance = Self::new(); + instance.password = Some(password); + instance + } + + fn set_pwd(&self, rb: RequestBuilder) -> RequestBuilder { + match &self.password { + Some(p) => rb.bearer_auth(p), + None => rb } } fn build_get(&self, url: &str) -> RequestBuilder { - self.client.get(self.base_url.join(url).unwrap()) + let rb = self.client.get(self.base_url.join(url).unwrap()); + self.set_pwd(rb) } fn build_post(&self, url: &str) -> RequestBuilder { - self.client.post(self.base_url.join(url).unwrap()) + let rb = self.client.post(self.base_url.join(url).unwrap()); + self.set_pwd(rb) } - pub async fn init(&self) { + pub async fn init(&self) -> RawMsg { let response: Response = self.build_post("/new") .json(&self.cli_info.as_message()) .send() .await .unwrap(); - println!("{}: {:?}", - response.status(), - response - .json::>() - .await - ); + let msg = response + .json::>() + .await + .unwrap(); + msg.into_item().into_owned() } - pub async fn list(&self) { - let response: Response = self.build_get("/ls") + pub async fn list(&self) -> Vec { + let response: Response = dbg!(self.build_get("/ls")) .send() .await .unwrap(); - let clients = response + let msg = response .json::>>() .await .unwrap(); - println!("***********"); - for cli in clients.item.iter() { - println!("{:?}", cli); - } + msg.into_item().into_owned() } } diff --git a/lib/u_lib/src/config.rs b/lib/u_lib/src/config.rs index 382840a..7db464c 100644 --- a/lib/u_lib/src/config.rs +++ b/lib/u_lib/src/config.rs @@ -1,7 +1,7 @@ use std::net::Ipv4Addr; use uuid::Uuid; -pub const MASTER_SERVER: Ipv4Addr = Ipv4Addr::new(3,9,16,40); //Ipv4Addr::LOCALHOST; +pub const MASTER_SERVER: Ipv4Addr = Ipv4Addr::LOCALHOST; //Ipv4Addr::new(3,9,16,40) pub const MASTER_PORT: u16 = 63714; lazy_static! { diff --git a/lib/u_lib/src/contracts/datatypes.rs b/lib/u_lib/src/contracts/datatypes.rs index 316bb78..e865794 100644 --- a/lib/u_lib/src/contracts/datatypes.rs +++ b/lib/u_lib/src/contracts/datatypes.rs @@ -1,15 +1,37 @@ use { super::*, - tokio::sync::Mutex, + tokio::sync::{ + Mutex, + MutexGuard + }, std::sync::Arc, std::collections::HashMap, uuid::Uuid, - crate::client::* }; -pub type JobPool = Vec>; +//pub type JobPool = Vec>; +pub type JobPool = Vec; pub type JobResult = Result, Vec>; pub type CliStorage = HashMap; -pub type SharedStorage = Arc>; \ No newline at end of file + + +#[derive(Clone)] +pub struct Storage { + clients: Arc> +} + +impl Storage { + pub fn new() -> Self { + Self { + clients: Arc::new( + Mutex::new(HashMap::::new()) + ) + } + } + + pub async fn lock(&self) -> MutexGuard<'_, CliStorage> { + self.clients.lock().await + } +} \ No newline at end of file diff --git a/lib/u_lib/src/contracts/jobs.rs b/lib/u_lib/src/contracts/jobs.rs index e1d064a..1c8320b 100644 --- a/lib/u_lib/src/contracts/jobs.rs +++ b/lib/u_lib/src/contracts/jobs.rs @@ -30,7 +30,7 @@ impl ShellJob { } } -impl Job for ShellJob{ +impl Job for ShellJob { fn run(&mut self) { let result = Command::new(&self.cmd) .args(&self.args) diff --git a/lib/u_lib/src/contracts/messaging.rs b/lib/u_lib/src/contracts/messaging.rs index 332096e..0b27f4a 100644 --- a/lib/u_lib/src/contracts/messaging.rs +++ b/lib/u_lib/src/contracts/messaging.rs @@ -45,6 +45,10 @@ where I: Clone { item: Cow::Owned(item) } } + + pub fn into_item(self) -> Cow<'cow, I> { + self.item + } } #[derive(Serialize, Deserialize, Debug, Clone)]