From 8af75aef1754b4c2ce67a917182acc732051fc01 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Sun, 29 Jan 2023 19:34:59 -0500 Subject: [PATCH] refactor --- src/admin.rs | 48 ++++++++++++++++++++++++-------------------- src/api/admin.rs | 27 ++++++++++++++++--------- src/api/mod.rs | 2 +- src/api/pages.rs | 5 ++++- src/console.rs | 7 ++++--- src/database/mod.rs | 2 +- src/main.rs | 2 +- src/types/extract.rs | 8 ++++---- 8 files changed, 58 insertions(+), 43 deletions(-) diff --git a/src/admin.rs b/src/admin.rs index dec6b7d..344a953 100644 --- a/src/admin.rs +++ b/src/admin.rs @@ -3,7 +3,10 @@ use lazy_static::lazy_static; use rand::{distributions::Alphanumeric, Rng}; use tokio::sync::Mutex; -use crate::{types::{user::User, http::ResponseCode, post::Post, session::Session}, console::{self, sanatize}}; +use crate::{ + console::{self, sanatize}, + types::{http::ResponseCode, post::Post, session::Session, user::User}, +}; lazy_static! { static ref SECRET: Mutex = Mutex::new(String::new()); @@ -22,17 +25,16 @@ pub async fn get_secret() -> String { if secret.is_empty() { *secret = new_secret(); } - return secret.clone(); + secret.clone() } pub async fn regen_secret() -> String { let mut secret = SECRET.lock().await; *secret = new_secret(); - return secret.clone(); + secret.clone() } pub fn generate_users() -> Response { - let users = match User::reterieve_all() { Ok(users) => users, Err(err) => return err, @@ -51,7 +53,8 @@ pub fn generate_users() -> Response { Month Year - "#.to_string(); + "# + .to_string(); for user in users { html.push_str( @@ -66,7 +69,6 @@ pub fn generate_users() -> Response { } pub fn generate_posts() -> Response { - let posts = match Post::reterieve_all() { Ok(posts) => posts, Err(err) => return err, @@ -81,26 +83,28 @@ pub fn generate_posts() -> Response { Comments Date - "#.to_string(); + "# + .to_string(); for post in posts { - let Ok(likes) = serde_json::to_string(&post.likes) else { continue }; let Ok(comments) = serde_json::to_string(&post.comments) else { continue }; - html.push_str( - &format!("{}{}{}{}{}{}", - post.post_id, post.user_id, sanatize(post.content), console::beautify(likes), - console::beautify(comments), post.date - ) - ); + html.push_str(&format!( + "{}{}{}{}{}{}", + post.post_id, + post.user_id, + sanatize(post.content), + console::beautify(likes), + console::beautify(comments), + post.date + )); } ResponseCode::Success.text(&html) } pub fn generate_sessions() -> Response { - let sessions = match Session::reterieve_all() { Ok(sessions) => sessions, Err(err) => return err, @@ -111,15 +115,15 @@ pub fn generate_sessions() -> Response { User ID Token - "#.to_string(); + "# + .to_string(); for session in sessions { - html.push_str( - &format!("{}{}", - session.user_id, session.token - ) - ); + html.push_str(&format!( + "{}{}", + session.user_id, session.token + )); } ResponseCode::Success.text(&html) -} \ No newline at end of file +} diff --git a/src/api/admin.rs b/src/api/admin.rs index e654628..655e2e2 100644 --- a/src/api/admin.rs +++ b/src/api/admin.rs @@ -1,10 +1,16 @@ use std::env; -use axum::{response::Response, Router, routing::post}; +use axum::{response::Response, routing::post, Router}; use serde::Deserialize; -use tower_cookies::{Cookies, Cookie}; +use tower_cookies::{Cookie, Cookies}; -use crate::{types::{extract::{Check, CheckResult, Json, AdminUser, Log}, http::ResponseCode}, admin, database}; +use crate::{ + admin, database, + types::{ + extract::{AdminUser, Check, CheckResult, Json, Log}, + http::ResponseCode, + }, +}; #[derive(Deserialize)] struct AdminAuthRequest { @@ -17,11 +23,10 @@ impl Check for AdminAuthRequest { } } -async fn auth(cookies: Cookies, Json(body) : Json) -> Response { - - let check = env::var("SECRET").unwrap_or("admin".to_string()); +async fn auth(cookies: Cookies, Json(body): Json) -> Response { + let check = env::var("SECRET").unwrap_or_else(|_| "admin".to_string()); if check != body.secret { - return ResponseCode::BadRequest.text("Invalid admin secret") + return ResponseCode::BadRequest.text("Invalid admin secret"); } let mut cookie = Cookie::new("admin", admin::regen_secret().await); @@ -45,10 +50,12 @@ impl Check for QueryRequest { } } -async fn query(_: AdminUser, Json(body) : Json) -> Response { +async fn query(_: AdminUser, Json(body): Json) -> Response { match database::query(body.query) { - Ok(changes) => ResponseCode::Success.text(&format!("Query executed successfully. {} lines changed.", changes)), - Err(err) => ResponseCode::InternalServerError.text(&format!("{}", err)) + Ok(changes) => ResponseCode::Success.text(&format!( + "Query executed successfully. {changes} lines changed." + )), + Err(err) => ResponseCode::InternalServerError.text(&format!("{err}")), } } diff --git a/src/api/mod.rs b/src/api/mod.rs index ab857b1..c347207 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -1,5 +1,5 @@ +pub mod admin; pub mod auth; pub mod pages; pub mod posts; pub mod users; -pub mod admin; \ No newline at end of file diff --git a/src/api/pages.rs b/src/api/pages.rs index 87d0b8d..4ed2e49 100644 --- a/src/api/pages.rs +++ b/src/api/pages.rs @@ -6,7 +6,10 @@ use axum::{ use crate::{ console, - types::{extract::{AuthorizedUser, Log}, http::ResponseCode}, + types::{ + extract::{AuthorizedUser, Log}, + http::ResponseCode, + }, }; async fn root(user: Option, _: Log) -> Response { diff --git a/src/console.rs b/src/console.rs index 6e2649f..4148ded 100644 --- a/src/console.rs +++ b/src/console.rs @@ -46,7 +46,6 @@ lazy_static! { } pub async fn log(ip: IpAddr, method: Method, uri: Uri, path: Option, body: Option) { - let path = path.unwrap_or_default(); let body = body.unwrap_or_default(); @@ -202,11 +201,13 @@ impl Formatter for HtmlFormatter { } pub fn sanatize(input: String) -> String { - input.replace("&", "&").replace("<", "<").replace(">", ">") + input + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") } pub fn beautify(body: String) -> String { - let body = sanatize(body); if body.is_empty() { diff --git a/src/database/mod.rs b/src/database/mod.rs index b24c1e1..55cbe4f 100644 --- a/src/database/mod.rs +++ b/src/database/mod.rs @@ -20,4 +20,4 @@ pub fn query(query: String) -> Result { tracing::trace!("Running custom query"); let conn = connect()?; conn.execute(&query, []) -} \ No newline at end of file +} diff --git a/src/main.rs b/src/main.rs index b3f5cd2..bee40d7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,11 +19,11 @@ use crate::{ types::extract::RouterURI, }; +mod admin; mod api; mod console; mod database; mod types; -mod admin; async fn serve(req: Request, next: Next) -> Response where diff --git a/src/types/extract.rs b/src/types/extract.rs index 64a3e73..af30d3f 100644 --- a/src/types/extract.rs +++ b/src/types/extract.rs @@ -14,12 +14,12 @@ use bytes::Bytes; use serde::de::DeserializeOwned; use crate::{ - console, + admin, console, types::{ http::{ResponseCode, Result}, session::Session, user::User, - }, admin, + }, }; pub struct AuthorizedUser(pub User); @@ -71,12 +71,12 @@ where return Err(ResponseCode::Forbidden.text("No admin secret provided")) }; - println!("{}", secret); + println!("{secret}"); let check = admin::get_secret().await; if check != secret { - return Err(ResponseCode::Unauthorized.text("Auth token invalid")) + return Err(ResponseCode::Unauthorized.text("Auth token invalid")); } Ok(Self)