password-protected panel

4-update-check
plazmoid 4 years ago
parent 8c5e048b7c
commit 3c538b44ac
  1. 2
      bin/u_agent/Cargo.toml
  2. 3
      bin/u_agent/src/main.rs
  3. 2
      bin/u_panel/Cargo.toml
  4. 26
      bin/u_panel/src/main.rs
  5. 8
      bin/u_server/Cargo.toml
  6. 57
      bin/u_server/src/main.rs
  7. 3
      lib/u_lib/Cargo.toml
  8. 7
      lib/u_lib/src/client/client.rs
  9. 50
      lib/u_lib/src/client/network.rs
  10. 2
      lib/u_lib/src/config.rs
  11. 30
      lib/u_lib/src/contracts/datatypes.rs
  12. 2
      lib/u_lib/src/contracts/jobs.rs
  13. 4
      lib/u_lib/src/contracts/messaging.rs

@ -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"

@ -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));
}
}

@ -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"

@ -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<fn()> {
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(())
}

@ -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" }

@ -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<Extract = (Message<'static, ClientInfo>,),
body::content_length_limit(1024*64).and(body::json::<Message<ClientInfo>>())
}
async fn add_client(msg: Message<'_, ClientInfo>,
db: SharedStorage) -> Result<impl Reply, Rejection> {
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<impl Reply, Rejection> {
let clients = db.lock().await;
let mut result: Vec<ClientInfo> = 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::<Uuid, UClient>::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;

@ -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"

@ -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()
}
}
}

@ -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<String>
}
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::<Message<RawMsg>>()
.await
);
let msg = response
.json::<Message<RawMsg>>()
.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<ClientInfo> {
let response: Response = dbg!(self.build_get("/ls"))
.send()
.await
.unwrap();
let clients = response
let msg = response
.json::<Message<Vec<ClientInfo>>>()
.await
.unwrap();
println!("***********");
for cli in clients.item.iter() {
println!("{:?}", cli);
}
msg.into_item().into_owned()
}
}

@ -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! {

@ -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<Box<dyn Job>>;
//pub type JobPool = Vec<Box<dyn Job>>;
pub type JobPool = Vec<ShellJob>;
pub type JobResult = Result<Vec<u8>, Vec<u8>>;
pub type CliStorage = HashMap<Uuid, UClient>;
pub type SharedStorage = Arc<Mutex<CliStorage>>;
#[derive(Clone)]
pub struct Storage {
clients: Arc<Mutex<CliStorage>>
}
impl Storage {
pub fn new() -> Self {
Self {
clients: Arc::new(
Mutex::new(HashMap::<Uuid, UClient>::new())
)
}
}
pub async fn lock(&self) -> MutexGuard<'_, CliStorage> {
self.clients.lock().await
}
}

@ -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)

@ -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)]

Loading…
Cancel
Save