From 0fbecaba3dd4782e2b041fbc70c8651f4398b7bd Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Sat, 28 Jan 2023 17:57:52 -0500 Subject: new rust, clippy --- src/types/extract.rs | 18 ++++++------- src/types/http.rs | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/types/mod.rs | 2 +- src/types/post.rs | 2 +- src/types/response.rs | 75 --------------------------------------------------- src/types/session.rs | 4 +-- src/types/user.rs | 6 ++--- 7 files changed, 91 insertions(+), 91 deletions(-) create mode 100644 src/types/http.rs delete mode 100644 src/types/response.rs (limited to 'src/types') diff --git a/src/types/extract.rs b/src/types/extract.rs index 7dbf386..b4a6cfc 100644 --- a/src/types/extract.rs +++ b/src/types/extract.rs @@ -4,7 +4,7 @@ use axum::{extract::{FromRequestParts, FromRequest, ConnectInfo}, async_trait, r use bytes::Bytes; use serde::de::DeserializeOwned; -use crate::{types::{user::User, response::{ResponseCode, Result}, session::Session}, console}; +use crate::{types::{user::User, http::{ResponseCode, Result}, session::Session}, console}; pub struct AuthorizedUser(pub User); @@ -31,7 +31,7 @@ impl FromRequestParts for AuthorizedUser where S: Send + Sync { return Err(ResponseCode::InternalServerError.text("Valid token but no valid user")) }; - Ok(AuthorizedUser(user)) + Ok(Self(user)) } } @@ -48,25 +48,25 @@ impl FromRequest for Log where async fn from_request(mut req: Request, state: &S) -> Result { let Ok(ConnectInfo(info)) = req.extract_parts::>().await else { - return Ok(Log) + return Ok(Self) }; let method = req.method().clone(); - let path = req.extensions().get::().unwrap().0; + let path = req.extensions().get::().map_or("", |path| path.0); let uri = req.uri().clone(); let Ok(bytes) = Bytes::from_request(req, state).await else { console::log(info.ip(), method.clone(), uri.clone(), Some(path.to_string()), None).await; - return Ok(Log) + return Ok(Self) }; let Ok(body) = String::from_utf8(bytes.bytes().flatten().collect()) else { console::log(info.ip(), method.clone(), uri.clone(), Some(path.to_string()), None).await; - return Ok(Log) + return Ok(Self) }; console::log(info.ip(), method.clone(), uri.clone(), Some(path.to_string()), Some(body.to_string())).await; - Ok(Log) + Ok(Self) } } @@ -89,7 +89,7 @@ impl FromRequest for Json where return Err(ResponseCode::InternalServerError.text("Failed to read connection info")); }; let method = req.method().clone(); - let path = req.extensions().get::().unwrap().0; + let path = req.extensions().get::().map_or("", |path| path.0); let uri = req.uri().clone(); let Ok(bytes) = Bytes::from_request(req, state).await else { @@ -111,7 +111,7 @@ impl FromRequest for Json where return Err(ResponseCode::BadRequest.text(&msg)); } - Ok(Json(value)) + Ok(Self(value)) } } diff --git a/src/types/http.rs b/src/types/http.rs new file mode 100644 index 0000000..0e7b703 --- /dev/null +++ b/src/types/http.rs @@ -0,0 +1,75 @@ +use axum::{response::{IntoResponse, Response}, http::{StatusCode, Request, HeaderValue}, body::Body, headers::HeaderName}; +use tower::ServiceExt; +use tower_http::services::ServeFile; +use tracing::instrument; + +#[derive(Debug)] +pub enum ResponseCode { + Success, + Created, + BadRequest, + Unauthorized, + Forbidden, + NotFound, + ImATeapot, + InternalServerError +} + +impl ResponseCode { + + const fn code(self) -> StatusCode { + match self { + Self::Success => StatusCode::OK, + Self::Created => StatusCode::CREATED, + Self::BadRequest => StatusCode::BAD_REQUEST, + Self::Unauthorized => StatusCode::UNAUTHORIZED, + Self::Forbidden => StatusCode::FORBIDDEN, + Self::NotFound => StatusCode::NOT_FOUND, + Self::ImATeapot => StatusCode::IM_A_TEAPOT, + Self::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR + } + } + + #[instrument()] + pub fn text(self, msg: &str) -> Response { + (self.code(), msg.to_owned()).into_response() + } + + #[instrument()] + pub fn json(self, json: &str) -> Response { + let mut res = (self.code(), json.to_owned()).into_response(); + res.headers_mut().insert( + HeaderName::from_static("content-type"), HeaderValue::from_static("application/json"), + ); + res + } + + #[instrument()] + pub fn html(self, json: &str) -> Response { + let mut res = (self.code(), json.to_owned()).into_response(); + res.headers_mut().insert( + HeaderName::from_static("content-type"), HeaderValue::from_static("text/html"), + ); + res + } + + #[instrument()] + pub async fn file(self, path: &str) -> Response { + if !path.chars().any(|c| c == '.' ) { + return Self::BadRequest.text("Folders cannot be served"); + } + let path = format!("public{path}"); + let svc = ServeFile::new(path); + let Ok(mut res) = svc.oneshot(Request::new(Body::empty())).await else { + tracing::error!("Error while fetching file"); + return Self::InternalServerError.text("Error while fetching file"); + }; + if res.status() != StatusCode::OK { + return Self::NotFound.text("File not found"); + } + *res.status_mut() = self.code(); + res.into_response() + } +} + +pub type Result = std::result::Result; \ No newline at end of file diff --git a/src/types/mod.rs b/src/types/mod.rs index 089885e..0ab104c 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -2,4 +2,4 @@ pub mod user; pub mod post; pub mod session; pub mod extract; -pub mod response; \ No newline at end of file +pub mod http; \ No newline at end of file diff --git a/src/types/post.rs b/src/types/post.rs index 7ca0a3c..95aed0e 100644 --- a/src/types/post.rs +++ b/src/types/post.rs @@ -4,7 +4,7 @@ use serde::Serialize; use tracing::instrument; use crate::database; -use crate::types::response::{Result, ResponseCode}; +use crate::types::http::{Result, ResponseCode}; #[derive(Serialize)] pub struct Post { diff --git a/src/types/response.rs b/src/types/response.rs deleted file mode 100644 index 0c5a78c..0000000 --- a/src/types/response.rs +++ /dev/null @@ -1,75 +0,0 @@ -use axum::{response::{IntoResponse, Response}, http::{StatusCode, Request, HeaderValue}, body::Body, headers::HeaderName}; -use tower::ServiceExt; -use tower_http::services::ServeFile; -use tracing::instrument; - -#[derive(Debug)] -pub enum ResponseCode { - Success, - Created, - BadRequest, - Unauthorized, - Forbidden, - NotFound, - ImATeapot, - InternalServerError -} - -impl ResponseCode { - - pub fn code(self) -> StatusCode { - match self { - Self::Success => StatusCode::OK, - Self::Created => StatusCode::CREATED, - Self::BadRequest => StatusCode::BAD_REQUEST, - Self::Unauthorized => StatusCode::UNAUTHORIZED, - Self::Forbidden => StatusCode::FORBIDDEN, - Self::NotFound => StatusCode::NOT_FOUND, - Self::ImATeapot => StatusCode::IM_A_TEAPOT, - Self::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR - } - } - - #[instrument()] - pub fn text(self, msg: &str) -> Response { - (self.code(), msg.to_owned()).into_response() - } - - #[instrument()] - pub fn json(self, json: &str) -> Response { - let mut res = (self.code(), json.to_owned()).into_response(); - res.headers_mut().insert( - HeaderName::from_static("content-type"), HeaderValue::from_static("application/json"), - ); - res - } - - #[instrument()] - pub fn html(self, json: &str) -> Response { - let mut res = (self.code(), json.to_owned()).into_response(); - res.headers_mut().insert( - HeaderName::from_static("content-type"), HeaderValue::from_static("text/html"), - ); - res - } - - #[instrument()] - pub async fn file(self, path: &str) -> Response { - if !path.chars().any(|c| c == '.' ) { - return ResponseCode::BadRequest.text("Folders cannot be served"); - } - let path = format!("public{}", path); - let svc = ServeFile::new(path); - let Ok(mut res) = svc.oneshot(Request::new(Body::empty())).await else { - tracing::error!("Error while fetching file"); - return ResponseCode::InternalServerError.text("Error while fetching file"); - }; - if res.status() != StatusCode::OK { - return ResponseCode::NotFound.text("File not found"); - } - *res.status_mut() = self.code(); - res.into_response() - } -} - -pub type Result = std::result::Result; \ No newline at end of file diff --git a/src/types/session.rs b/src/types/session.rs index 30e430e..176e389 100644 --- a/src/types/session.rs +++ b/src/types/session.rs @@ -3,7 +3,7 @@ use serde::Serialize; use tracing::instrument; use crate::database; -use crate::types::response::{Result, ResponseCode}; +use crate::types::http::{Result, ResponseCode}; #[derive(Serialize)] pub struct Session { @@ -27,7 +27,7 @@ impl Session { let token: String = rand::thread_rng().sample_iter(&Alphanumeric).take(32).map(char::from).collect(); match database::sessions::set_session(user_id, &token) { Err(_) => Err(ResponseCode::BadRequest.text("Failed to create session")), - Ok(_) => Ok(Session {user_id, token}) + Ok(_) => Ok(Self {user_id, token}) } } diff --git a/src/types/user.rs b/src/types/user.rs index b26cfd7..0013d7d 100644 --- a/src/types/user.rs +++ b/src/types/user.rs @@ -3,7 +3,7 @@ use tracing::instrument; use crate::api::auth::RegistrationRequet; use crate::database; -use crate::types::response::{Result, ResponseCode}; +use crate::types::http::{Result, ResponseCode}; #[derive(Serialize, Deserialize, Debug)] @@ -69,11 +69,11 @@ impl User { #[instrument()] pub fn new(request: RegistrationRequet) -> Result { - if User::from_email(&request.email).is_ok() { + if Self::from_email(&request.email).is_ok() { return Err(ResponseCode::BadRequest.text(&format!("Email is already in use by {}", &request.email))) } - if let Ok(user) = User::from_password(&request.password) { + if let Ok(user) = Self::from_password(&request.password) { return Err(ResponseCode::BadRequest.text(&format!("Password is already in use by {}", user.email))) } -- cgit v1.2.3-freya