From 7e07687b5ec14bd788b8d2dd3f0a7ead83842fd4 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Sat, 28 Jan 2023 14:22:29 -0500 Subject: [PATCH] clippy my beloved --- src/api/auth.rs | 22 +++++++++++----------- src/api/pages.rs | 20 ++++++++++---------- src/console.rs | 12 ++++++------ src/database/mod.rs | 2 +- src/database/posts.rs | 20 ++++++++++++++++---- src/database/users.rs | 29 ++++++++++++++++++++++------- src/main.rs | 4 ++-- src/types/extract.rs | 10 +++++----- src/types/response.rs | 2 +- src/types/session.rs | 8 ++++---- src/types/user.rs | 15 ++++++++------- 11 files changed, 86 insertions(+), 58 deletions(-) diff --git a/src/api/auth.rs b/src/api/auth.rs index 253e982..410b643 100644 --- a/src/api/auth.rs +++ b/src/api/auth.rs @@ -5,16 +5,16 @@ use tower_cookies::{Cookies, Cookie}; use crate::types::{user::User, response::ResponseCode, session::Session, extract::{Json, AuthorizedUser, Check, CheckResult, Log}}; -#[derive(Deserialize)] -struct RegistrationRequet { - firstname: String, - lastname: String, - email: String, - password: String, - gender: String, - day: u8, - month: u8, - year: u32 +#[derive(Deserialize, Debug)] +pub struct RegistrationRequet { + pub firstname: String, + pub lastname: String, + pub email: String, + pub password: String, + pub gender: String, + pub day: u8, + pub month: u8, + pub year: u32 } impl Check for RegistrationRequet { @@ -34,7 +34,7 @@ impl Check for RegistrationRequet { async fn register(cookies: Cookies, Json(body): Json) -> Response { - let user = match User::new(body.firstname, body.lastname, body.email, body.password, body.gender, body.day, body.month, body.year) { + let user = match User::new(body) { Ok(user) => user, Err(err) => return err }; diff --git a/src/api/pages.rs b/src/api/pages.rs index 7f5bfc3..f4f0f42 100644 --- a/src/api/pages.rs +++ b/src/api/pages.rs @@ -4,41 +4,41 @@ use crate::{types::{extract::AuthorizedUser, response::ResponseCode}, console}; async fn root(user: Option) -> Response { if user.is_some() { - return Redirect::to("/home").into_response() + Redirect::to("/home").into_response() } else { - return Redirect::to("/login").into_response() + Redirect::to("/login").into_response() } } async fn login(user: Option) -> Response { if user.is_some() { - return Redirect::to("/home").into_response() + Redirect::to("/home").into_response() } else { - return ResponseCode::Success.file("/login.html").await + ResponseCode::Success.file("/login.html").await } } async fn home(user: Option) -> Response { if user.is_none() { - return Redirect::to("/login").into_response() + Redirect::to("/login").into_response() } else { - return ResponseCode::Success.file("/home.html").await + ResponseCode::Success.file("/home.html").await } } async fn people(user: Option) -> Response { if user.is_none() { - return Redirect::to("/login").into_response() + Redirect::to("/login").into_response() } else { - return ResponseCode::Success.file("/people.html").await + ResponseCode::Success.file("/people.html").await } } async fn profile(user: Option) -> Response { if user.is_none() { - return Redirect::to("/login").into_response() + Redirect::to("/login").into_response() } else { - return ResponseCode::Success.file("/profile.html").await + ResponseCode::Success.file("/profile.html").await } } diff --git a/src/console.rs b/src/console.rs index 756bf56..019ae2c 100644 --- a/src/console.rs +++ b/src/console.rs @@ -51,10 +51,10 @@ pub async fn log(ip: IpAddr, method: Method, uri: Uri, path: Option, bod tracing::info!("{} {} {}{} {}", &ip, &method, &path, &uri, &body); let message = LogMessage { - ip: ip, - method: method, - uri: uri, - path: path, + ip, + method, + uri, + path, body: beautify(body) }; @@ -153,7 +153,7 @@ impl Formatter for HtmlFormatter { } fn beautify(body: String) -> String { - if body.len() < 1 { + if body.is_empty() { return "".to_string() } let Ok(mut json) = serde_json::from_str::(&body) else { @@ -164,7 +164,7 @@ fn beautify(body: String) -> String { } let mut writer: Vec = Vec::with_capacity(128); let mut serializer = serde_json::Serializer::with_formatter(&mut writer, HtmlFormatter); - if let Err(_) = json.serialize(&mut serializer) { + if json.serialize(&mut serializer).is_err() { return body } String::from_utf8_lossy(&writer).to_string() diff --git a/src/database/mod.rs b/src/database/mod.rs index 7227074..19e4203 100644 --- a/src/database/mod.rs +++ b/src/database/mod.rs @@ -5,7 +5,7 @@ pub mod users; pub mod sessions; pub fn connect() -> Result { - return rusqlite::Connection::open("xssbook.db"); + rusqlite::Connection::open("xssbook.db") } pub fn init() -> Result<()> { diff --git a/src/database/posts.rs b/src/database/posts.rs index 6ee5e0f..7892683 100644 --- a/src/database/posts.rs +++ b/src/database/posts.rs @@ -48,7 +48,10 @@ pub fn get_post(post_id: u64) -> Result, rusqlite::Error> { tracing::trace!("Retrieving post"); let conn = database::connect()?; let mut stmt = conn.prepare("SELECT * FROM posts WHERE post_id = ?")?; - let row = stmt.query_row([post_id], |row| Ok(post_from_row(row)?)).optional()?; + let row = stmt.query_row([post_id], |row| { + let row = post_from_row(row)?; + Ok(row) + }).optional()?; Ok(row) } @@ -58,7 +61,10 @@ pub fn get_post_page(page: u64) -> Result, rusqlite::Error> { let page_size = 10; let conn = database::connect()?; let mut stmt = conn.prepare("SELECT * FROM posts ORDER BY post_id DESC LIMIT ? OFFSET ?")?; - let row = stmt.query_map([page_size, page_size * page], |row| Ok(post_from_row(row)?))?; + let row = stmt.query_map([page_size, page_size * page], |row| { + let row = post_from_row(row)?; + Ok(row) + })?; Ok(row.into_iter().flatten().collect()) } @@ -67,7 +73,10 @@ pub fn get_users_posts(user_id: u64) -> Result, rusqlite::Error> { tracing::trace!("Retrieving users posts"); let conn = database::connect()?; let mut stmt = conn.prepare("SELECT * FROM posts WHERE user_id = ? ORDER BY post_id DESC")?; - let row = stmt.query_map([user_id], |row| Ok(post_from_row(row)?))?; + let row = stmt.query_map([user_id], |row| { + let row = post_from_row(row)?; + Ok(row) + })?; Ok(row.into_iter().flatten().collect()) } @@ -85,7 +94,10 @@ pub fn add_post(user_id: u64, content: &str) -> Result { let date = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64; let conn = database::connect()?; let mut stmt = conn.prepare("INSERT INTO posts (user_id, content, likes, comments, date) VALUES(?,?,?,?,?) RETURNING *;")?; - let post = stmt.query_row((user_id, content, likes_json, comments_json, date), |row| Ok(post_from_row(row)?))?; + let post = stmt.query_row((user_id, content, likes_json, comments_json, date), |row| { + let row = post_from_row(row)?; + Ok(row) + })?; Ok(post) } diff --git a/src/database/users.rs b/src/database/users.rs index 56b8814..d9e35b1 100644 --- a/src/database/users.rs +++ b/src/database/users.rs @@ -2,7 +2,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; use rusqlite::{OptionalExtension, Row}; use tracing::instrument; -use crate::{database, types::user::User}; +use crate::{database, types::user::User, api::auth::RegistrationRequet}; pub fn init() -> Result<(), rusqlite::Error> { let sql = " @@ -46,7 +46,10 @@ pub fn get_user_by_id(user_id: u64, hide_password: bool) -> Result, tracing::trace!("Retrieving user by id"); let conn = database::connect()?; let mut stmt = conn.prepare("SELECT * FROM users WHERE user_id = ?")?; - let row = stmt.query_row([user_id], |row| Ok(user_from_row(row, hide_password)?)).optional()?; + let row = stmt.query_row([user_id], |row| { + let row = user_from_row(row, hide_password)?; + Ok(row) + }).optional()?; Ok(row) } @@ -55,7 +58,10 @@ pub fn get_user_by_email(email: &str, hide_password: bool) -> Result Result Result, rusqli let page_size = 5; let conn = database::connect()?; let mut stmt = conn.prepare("SELECT * FROM users ORDER BY user_id DESC LIMIT ? OFFSET ?")?; - let row = stmt.query_map([page_size, page_size * page], |row| Ok(user_from_row(row, hide_password)?))?; + let row = stmt.query_map([page_size, page_size * page], |row| { + let row = user_from_row(row, hide_password)?; + Ok(row) + })?; Ok(row.into_iter().flatten().collect()) } #[instrument()] -pub fn add_user(firstname: &str, lastname: &str, email: &str, password: &str, gender: &str, day: u8, month: u8, year: u32) -> Result { +pub fn add_user(request: RegistrationRequet) -> Result { tracing::trace!("Adding new user"); let date = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64; let conn = database::connect()?; let mut stmt = conn.prepare("INSERT INTO users (firstname, lastname, email, password, gender, date, day, month, year) VALUES(?,?,?,?,?,?,?,?,?) RETURNING *;")?; - let user = stmt.query_row((firstname, lastname, email, password, gender, date, day, month, year), |row| Ok(user_from_row(row, false)?))?; + let user = stmt.query_row((request.firstname, request.lastname, request.email, request.password, request.gender, date, request.day, request.month, request.year), |row| { + let row = user_from_row(row, false)?; + Ok(row) + })?; Ok(user) } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index ebce57e..9ccc45b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,9 +28,9 @@ async fn log(mut req: Request, next: Next) -> Response where return next.run(req).await }; - console::log(info.ip().clone(), req.method().clone(), req.uri().clone(), None, None).await; + console::log(info.ip(), req.method().clone(), req.uri().clone(), None, None).await; - return next.run(req).await + next.run(req).await } async fn not_found() -> Response { diff --git a/src/types/extract.rs b/src/types/extract.rs index 69c6ed8..7dbf386 100644 --- a/src/types/extract.rs +++ b/src/types/extract.rs @@ -22,7 +22,7 @@ impl FromRequestParts for AuthorizedUser where S: Send + Sync { return Err(ResponseCode::Forbidden.text("No auth token provided")) }; - let Ok(session) = Session::from_token(&token) else { + let Ok(session) = Session::from_token(token) else { return Err(ResponseCode::Unauthorized.text("Auth token invalid")) }; @@ -55,16 +55,16 @@ impl FromRequest for Log where let uri = req.uri().clone(); let Ok(bytes) = Bytes::from_request(req, state).await else { - console::log(info.ip().clone(), method.clone(), uri.clone(), Some(path.to_string()), None).await; + console::log(info.ip(), method.clone(), uri.clone(), Some(path.to_string()), None).await; return Ok(Log) }; let Ok(body) = String::from_utf8(bytes.bytes().flatten().collect()) else { - console::log(info.ip().clone(), method.clone(), uri.clone(), Some(path.to_string()), None).await; + console::log(info.ip(), method.clone(), uri.clone(), Some(path.to_string()), None).await; return Ok(Log) }; - console::log(info.ip().clone(), method.clone(), uri.clone(), Some(path.to_string()), Some(body.to_string())).await; + console::log(info.ip(), method.clone(), uri.clone(), Some(path.to_string()), Some(body.to_string())).await; Ok(Log) } @@ -101,7 +101,7 @@ impl FromRequest for Json where return Err(ResponseCode::BadRequest.text("Invalid utf8 body")) }; - console::log(info.ip().clone(), method.clone(), uri.clone(), Some(path.to_string()), Some(body.to_string())).await; + console::log(info.ip(), method.clone(), uri.clone(), Some(path.to_string()), Some(body.to_string())).await; let Ok(value) = serde_json::from_str::(&body) else { return Err(ResponseCode::BadRequest.text("Invalid request body")) diff --git a/src/types/response.rs b/src/types/response.rs index d10bce9..0c5a78c 100644 --- a/src/types/response.rs +++ b/src/types/response.rs @@ -55,7 +55,7 @@ impl ResponseCode { #[instrument()] pub async fn file(self, path: &str) -> Response { - if path.chars().position(|c| c == '.' ).is_none() { + if !path.chars().any(|c| c == '.' ) { return ResponseCode::BadRequest.text("Folders cannot be served"); } let path = format!("public{}", path); diff --git a/src/types/session.rs b/src/types/session.rs index e05dc49..30e430e 100644 --- a/src/types/session.rs +++ b/src/types/session.rs @@ -26,14 +26,14 @@ impl Session { pub fn new(user_id: u64) -> Result { let token: String = rand::thread_rng().sample_iter(&Alphanumeric).take(32).map(char::from).collect(); match database::sessions::set_session(user_id, &token) { - Err(_) => return Err(ResponseCode::BadRequest.text("Failed to create session")), - Ok(_) => return Ok(Session {user_id, token}) - }; + Err(_) => Err(ResponseCode::BadRequest.text("Failed to create session")), + Ok(_) => Ok(Session {user_id, token}) + } } #[instrument()] pub fn delete(user_id: u64) -> Result<()> { - if let Err(_) = database::sessions::delete_session(user_id) { + if database::sessions::delete_session(user_id).is_err() { tracing::error!("Failed to logout user"); return Err(ResponseCode::InternalServerError.text("Failed to logout")); }; diff --git a/src/types/user.rs b/src/types/user.rs index 031946a..b26cfd7 100644 --- a/src/types/user.rs +++ b/src/types/user.rs @@ -1,6 +1,7 @@ use serde::{Serialize, Deserialize}; use tracing::instrument; +use crate::api::auth::RegistrationRequet; use crate::database; use crate::types::response::{Result, ResponseCode}; @@ -32,12 +33,12 @@ impl User { #[instrument()] pub fn from_user_ids(user_ids: Vec) -> Vec { - user_ids.iter().map(|user_id| { + user_ids.iter().filter_map(|user_id| { let Ok(Some(user)) = database::users::get_user_by_id(*user_id, true) else { return None; }; Some(user) - }).flatten().collect() + }).collect() } #[instrument()] @@ -67,16 +68,16 @@ impl User { } #[instrument()] - pub fn new(firstname: String, lastname: String, email: String, password: String, gender: String, day: u8, month: u8, year: u32) -> Result { - if let Ok(_) = User::from_email(&email) { - return Err(ResponseCode::BadRequest.text(&format!("Email is already in use by {}", &email))) + pub fn new(request: RegistrationRequet) -> Result { + if User::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(&password) { + if let Ok(user) = User::from_password(&request.password) { return Err(ResponseCode::BadRequest.text(&format!("Password is already in use by {}", user.email))) } - let Ok(user) = database::users::add_user(&firstname, &lastname, &email, &password, &gender, day, month, year) else { + let Ok(user) = database::users::add_user(request) else { tracing::error!("Failed to create new user"); return Err(ResponseCode::InternalServerError.text("Failed to create new uesr")) };