Skip to content

Commit

Permalink
chore: rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
ElaBosak233 committed Jul 29, 2024
1 parent 1534e7b commit a653ffe
Show file tree
Hide file tree
Showing 61 changed files with 331 additions and 1,074 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ reqwest = { version = "0.12", features = ["json", "rustls-tls"], default-feature
async-trait = { version = "0.1" }
ring = { version = "0.17" }
rustls = { version = "0.23", features = ["ring"] }
rust-embed = { version = "8.5" }

[build-dependencies]
chrono = { version = "0.4" }
Expand Down
10 changes: 10 additions & 0 deletions assets/banner.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
_ _ _ _
___/ | ___ _ _ __| |___ __| | __ _/ | ___
/ __| |/ _ \| | | |/ _` / __|/ _` |/ _` | |/ _ \
| (__| | (_) | |_| | (_| \__ \ (_| | (_| | | __/
\___|_|\___/ \__,_|\__,_|___/\__,_|\__,_|_|\___|
Version {{version}}

Commit: {{commit}}
Build At: {{build_at}}
GitHub: https://github.com/elabosak233/cloudsdale
7 changes: 1 addition & 6 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,5 @@ fn main() {
.trim()
);

println!(
"cargo:rustc-env=BUILD_AT={}",
chrono::Utc::now()
.format("%Y-%m-%d %H:%M:%S UTC")
.to_string()
);
println!("cargo:rustc-env=BUILD_AT={}", chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC").to_string());
}
12 changes: 12 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
merge_derives = true
fn_params_layout = "Compressed"
max_width = 160
tab_spaces = 4
reorder_imports = true

# unstable_features = true
# hex_literal_case = "Upper"
# condense_wildcard_suffixes = true
# imports_granularity = "Crate"
# brace_style = "PreferSameLine"
# group_imports = "StdExternalCrate"
5 changes: 5 additions & 0 deletions src/assets/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
use rust_embed::Embed;

#[derive(Embed)]
#[folder = "assets/"]
pub struct Assets;
19 changes: 3 additions & 16 deletions src/captcha/recaptcha.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,8 @@ struct RecaptchaRequest {
impl ICaptcha for Recaptcha {
fn new() -> Self {
return Recaptcha {
url: crate::config::get_app_config()
.captcha
.recaptcha
.url
.clone(),
secret_key: crate::config::get_app_config()
.captcha
.recaptcha
.secret_key
.clone(),
url: crate::config::get_app_config().captcha.recaptcha.url.clone(),
secret_key: crate::config::get_app_config().captcha.recaptcha.secret_key.clone(),
threshold: crate::config::get_app_config().captcha.recaptcha.threshold,
};
}
Expand All @@ -44,12 +36,7 @@ impl ICaptcha for Recaptcha {
};

let client = Client::new();
let resp = client
.post(&self.url)
.json(&request_body)
.send()
.await
.unwrap();
let resp = client.post(&self.url).json(&request_body).send().await.unwrap();

let response: serde_json::Value = resp.json().await.unwrap();

Expand Down
6 changes: 1 addition & 5 deletions src/captcha/traits.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
pub trait ICaptcha {
fn new() -> Self;
fn verify(
&self,
token: String,
client_ip: String,
) -> impl std::future::Future<Output = bool> + Send;
fn verify(&self, token: String, client_ip: String) -> impl std::future::Future<Output = bool> + Send;
}
19 changes: 3 additions & 16 deletions src/captcha/turnstile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,8 @@ struct TurnstileRequest {
impl ICaptcha for Turnstile {
fn new() -> Self {
return Turnstile {
url: crate::config::get_app_config()
.captcha
.turnstile
.url
.clone(),
secret_key: crate::config::get_app_config()
.captcha
.turnstile
.secret_key
.clone(),
url: crate::config::get_app_config().captcha.turnstile.url.clone(),
secret_key: crate::config::get_app_config().captcha.turnstile.secret_key.clone(),
};
}

Expand All @@ -42,12 +34,7 @@ impl ICaptcha for Turnstile {
};

let client = Client::new();
let resp = client
.post(&self.url)
.json(&request_body)
.send()
.await
.unwrap();
let resp = client.post(&self.url).json(&request_body).send().await.unwrap();

let response: serde_json::Value = resp.json().await.unwrap();

Expand Down
2 changes: 1 addition & 1 deletion src/config/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ pub mod path {
pub const MEDIA: &str = "./media";
pub const FRONTEND: &str = "./dist";
pub const CAPTURE: &str = "./captures";
}
}
4 changes: 1 addition & 3 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ pub async fn init() {
let target_path = Path::new("application.yml");
if target_path.exists() {
let content = fs::read_to_string("application.yml").await.unwrap();
APP_CONFIG
.set(serde_yaml::from_str(&content).unwrap())
.unwrap();
APP_CONFIG.set(serde_yaml::from_str(&content).unwrap()).unwrap();
} else {
error!("Configuration application.yml not found.");
process::exit(1);
Expand Down
42 changes: 9 additions & 33 deletions src/container/docker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,11 @@ async fn daemon() {
tokio::spawn(async {
let interval = time::Duration::from_secs(10);
loop {
let (pods, _) = repository::pod::find(None, None, None, None, None, None, Some(false))
.await
.unwrap();
let (pods, _) = repository::pod::find(None, None, None, None, None, None, Some(false)).await.unwrap();
for pod in pods {
let _ = get_docker_client()
.stop_container(pod.name.clone().as_str(), None)
.await;
let _ = get_docker_client()
.remove_container(pod.name.clone().as_str(), None)
.await;
crate::model::pod::Entity::delete_by_id(pod.id)
.exec(&get_db().await)
.await
.unwrap();
let _ = get_docker_client().stop_container(pod.name.clone().as_str(), None).await;
let _ = get_docker_client().remove_container(pod.name.clone().as_str(), None).await;
crate::model::pod::Entity::delete_by_id(pod.id).exec(&get_db().await).await.unwrap();
info!("Cleaned up expired container: {0}", pod.name);
}
tokio::time::sleep(interval).await;
Expand Down Expand Up @@ -72,10 +63,7 @@ impl Container for Docker {
}

async fn create(
&self,
name: String,
challenge: crate::model::challenge::Model,
injected_flag: crate::model::challenge::Flag,
&self, name: String, challenge: crate::model::challenge::Model, injected_flag: crate::model::challenge::Flag,
) -> Result<Vec<crate::model::pod::Nat>, Box<dyn Error>> {
let port_bindings: HashMap<String, Option<Vec<PortBinding>>> = challenge
.ports
Expand All @@ -91,17 +79,9 @@ impl Container for Docker {
})
.collect();

let mut env_bindings: Vec<String> = challenge
.envs
.into_iter()
.map(|env| format!("{}:{}", env.key, env.value))
.collect();
let mut env_bindings: Vec<String> = challenge.envs.into_iter().map(|env| format!("{}:{}", env.key, env.value)).collect();

env_bindings.push(format!(
"{}:{}",
injected_flag.env.unwrap_or("FLAG".to_string()),
injected_flag.value
));
env_bindings.push(format!("{}:{}", injected_flag.env.unwrap_or("FLAG".to_string()), injected_flag.value));

let cfg = Config {
image: challenge.image_name.clone(),
Expand Down Expand Up @@ -152,11 +132,7 @@ impl Container for Docker {
}

async fn delete(&self, name: String) {
let _ = get_docker_client()
.stop_container(name.clone().as_str(), None)
.await;
let _ = get_docker_client()
.remove_container(name.clone().as_str(), None)
.await;
let _ = get_docker_client().stop_container(name.clone().as_str(), None).await;
let _ = get_docker_client().remove_container(name.clone().as_str(), None).await;
}
}
10 changes: 2 additions & 8 deletions src/container/k8s.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,7 @@ impl Container for K8s {
daemon().await;
}
Err(e) => {
error!(
"Failed to create Kubernetes client from custom config: {:?}",
e
);
error!("Failed to create Kubernetes client from custom config: {:?}", e);
process::exit(1);
}
},
Expand All @@ -74,10 +71,7 @@ impl Container for K8s {
}

async fn create(
&self,
name: String,
challenge: crate::model::challenge::Model,
injected_flag: crate::model::challenge::Flag,
&self, name: String, challenge: crate::model::challenge::Model, injected_flag: crate::model::challenge::Flag,
) -> Result<Vec<crate::model::pod::Nat>, Box<dyn Error>> {
let client = get_k8s_client().clone();
let pods: Api<Pod> = Api::namespaced(client, "default");
Expand Down
5 changes: 1 addition & 4 deletions src/container/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@ use std::error::Error;
pub trait Container: Send + Sync {
async fn init(&self);
async fn create(
&self,
name: String,
challenge: crate::model::challenge::Model,
injected_flag: crate::model::challenge::Flag,
&self, name: String, challenge: crate::model::challenge::Model, injected_flag: crate::model::challenge::Flag,
) -> Result<Vec<crate::model::pod::Nat>, Box<dyn Error>>;
async fn delete(&self, name: String);
}
27 changes: 5 additions & 22 deletions src/database/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@ mod migration;

use bcrypt::{hash, DEFAULT_COST};
use once_cell::sync::Lazy;
use sea_orm::{
ActiveModelTrait, ConnectOptions, Database, DatabaseConnection, EntityTrait, PaginatorTrait,
Set,
};
use sea_orm::{ActiveModelTrait, ConnectOptions, Database, DatabaseConnection, EntityTrait, PaginatorTrait, Set};
use std::{process, time::Duration};
use tokio::sync::RwLock;
use tracing::{error, info};
Expand All @@ -15,16 +12,8 @@ use crate::config;
static DB: Lazy<RwLock<Option<DatabaseConnection>>> = Lazy::new(|| RwLock::new(None));

pub async fn init() {
let url = match crate::config::get_app_config()
.db
.provider
.to_lowercase()
.as_str()
{
"sqlite" => format!(
"sqlite://{}?mode=rwc",
crate::config::get_app_config().db.sqlite.path.clone()
),
let url = match crate::config::get_app_config().db.provider.to_lowercase().as_str() {
"sqlite" => format!("sqlite://{}?mode=rwc", crate::config::get_app_config().db.sqlite.path.clone()),
"mysql" => format!(
"mysql://{}:{}@{}:{}/{}",
crate::config::get_app_config().db.mysql.username,
Expand Down Expand Up @@ -74,10 +63,7 @@ pub async fn get_db() -> DatabaseConnection {
}

pub async fn init_admin() {
let total = crate::model::user::Entity::find()
.count(&get_db().await)
.await
.unwrap();
let total = crate::model::user::Entity::find().count(&get_db().await).await.unwrap();
if total == 0 {
let hashed_password = hash("123456".to_string(), DEFAULT_COST).unwrap();
let user = crate::model::user::ActiveModel {
Expand All @@ -94,10 +80,7 @@ pub async fn init_admin() {
}

pub async fn init_category() {
let total = crate::model::category::Entity::find()
.count(&get_db().await)
.await
.unwrap();
let total = crate::model::category::Entity::find().count(&get_db().await).await.unwrap();
if total == 0 {
let default_categories = vec![
crate::model::category::ActiveModel {
Expand Down
1 change: 1 addition & 0 deletions src/email/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

4 changes: 1 addition & 3 deletions src/logger/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ pub fn init() {
.add_directive(Level::DEBUG.into())
.add_directive("docker_api=info".parse().unwrap());

let fmt_layer = tracing_subscriber::fmt::layer()
.with_target(false)
.with_filter(filter);
let fmt_layer = tracing_subscriber::fmt::layer().with_target(false).with_filter(filter);

// let file_layer = tracing_subscriber::fmt::layer()
// .with_ansi(false)
Expand Down
18 changes: 4 additions & 14 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod assets;
mod captcha;
mod config;
mod container;
Expand All @@ -12,24 +13,13 @@ mod server;
mod traits;
mod util;

const BANNER: &str = r#"
_ _ _ _
___/ | ___ _ _ __| |___ __| | __ _/ | ___
/ __| |/ _ \| | | |/ _` / __|/ _` |/ _` | |/ _ \
| (__| | (_) | |_| | (_| \__ \ (_| | (_| | | __/
\___|_|\___/ \__,_|\__,_|___/\__,_|\__,_|_|\___|
Version {{version}}
Commit: {{commit}}
Build At: {{build_at}}
GitHub: https://github.com/elabosak233/cloudsdale
"#;

#[tokio::main]
async fn main() {
let banner = assets::Assets::get("banner.txt").unwrap();
println!(
"{}",
BANNER
std::str::from_utf8(banner.data.as_ref())
.unwrap()
.replace("{{version}}", env!("CARGO_PKG_VERSION"))
.replace("{{commit}}", env!("GIT_COMMIT_ID"))
.replace("{{build_at}}", env!("BUILD_AT"))
Expand Down
6 changes: 2 additions & 4 deletions src/media/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ use tokio::{
};

pub async fn get(path: String, filename: String) -> Result<Vec<u8>, Box<dyn Error>> {
let filepath =
PathBuf::from(crate::config::consts::path::MEDIA).join(format!("{}/{}", path, filename));
let filepath = PathBuf::from(crate::config::consts::path::MEDIA).join(format!("{}/{}", path, filename));

match File::open(&filepath).await {
Ok(mut file) => {
Expand Down Expand Up @@ -44,8 +43,7 @@ pub async fn scan_dir(path: String) -> Result<Vec<(String, u64)>, Box<dyn Error>
}

pub async fn save(path: String, filename: String, data: Vec<u8>) -> Result<(), Box<dyn Error>> {
let filepath =
PathBuf::from(crate::config::consts::path::MEDIA).join(format!("{}/{}", path, filename));
let filepath = PathBuf::from(crate::config::consts::path::MEDIA).join(format!("{}/{}", path, filename));
if let Some(parent) = filepath.parent() {
if metadata(parent).await.is_err() {
create_dir_all(parent).await?;
Expand Down
5 changes: 1 addition & 4 deletions src/model/game_team/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ pub struct FindRequest {

impl Default for FindRequest {
fn default() -> Self {
FindRequest {
game_id: None,
team_id: None,
}
FindRequest { game_id: None, team_id: None }
}
}

Expand Down
Loading

0 comments on commit a653ffe

Please sign in to comment.