trifid/tfcli/src/org.rs

55 lines
1.7 KiB
Rust
Raw Normal View History

2023-06-16 00:49:06 +00:00
use std::error::Error;
use std::fs;
use ipnet::Ipv4Net;
use serde::{Deserialize, Serialize};
use url::Url;
use crate::OrgCommands;
use crate::api::APIErrorResponse;
pub async fn org_main(command: OrgCommands, server: Url) -> Result<(), Box<dyn Error>> {
match command {
OrgCommands::Create { cidr } => create_org(cidr, server).await,
}
}
#[derive(Serialize)]
pub struct CreateOrgBody {
pub cidr: String
}
#[derive(Deserialize)]
pub struct OrgCreateResponse {
pub organization: String,
pub ca: String,
pub network: String
}
pub async fn create_org(cidr: Ipv4Net, server: Url) -> Result<(), Box<dyn Error>> {
let client = reqwest::Client::new();
let sess_token_store = dirs::config_dir().unwrap().join("tfcli-session.token");
let session_token = fs::read_to_string(&sess_token_store)?;
let auth_token_store = dirs::config_dir().unwrap().join("tfcli-auth.token");
let auth_token = fs::read_to_string(&auth_token_store)?;
let token = format!("{} {}", session_token, auth_token);
let res = client.post(server.join("/v1/organization")?).json(&CreateOrgBody { cidr: cidr.to_string() }).bearer_auth(token).send().await?;
if res.status().is_success() {
let resp: OrgCreateResponse = res.json().await?;
println!("Created organization successfully.");
println!("Organization: {}", resp.organization);
println!(" Signing CA: {}", resp.ca);
println!(" Network: {}", resp.network);
} else {
let resp: APIErrorResponse = res.json().await?;
eprintln!("[error] Error creating org: {} {}", resp.errors[0].code, resp.errors[0].message);
std::process::exit(1);
}
Ok(())
}