clippy my beloved

This commit is contained in:
Tyler Murphy 2023-01-28 14:22:29 -05:00
parent f3f5e03651
commit 7e07687b5e
11 changed files with 86 additions and 58 deletions

View file

@ -5,16 +5,16 @@ use tower_cookies::{Cookies, Cookie};
use crate::types::{user::User, response::ResponseCode, session::Session, extract::{Json, AuthorizedUser, Check, CheckResult, Log}}; use crate::types::{user::User, response::ResponseCode, session::Session, extract::{Json, AuthorizedUser, Check, CheckResult, Log}};
#[derive(Deserialize)] #[derive(Deserialize, Debug)]
struct RegistrationRequet { pub struct RegistrationRequet {
firstname: String, pub firstname: String,
lastname: String, pub lastname: String,
email: String, pub email: String,
password: String, pub password: String,
gender: String, pub gender: String,
day: u8, pub day: u8,
month: u8, pub month: u8,
year: u32 pub year: u32
} }
impl Check for RegistrationRequet { impl Check for RegistrationRequet {
@ -34,7 +34,7 @@ impl Check for RegistrationRequet {
async fn register(cookies: Cookies, Json(body): Json<RegistrationRequet>) -> Response { async fn register(cookies: Cookies, Json(body): Json<RegistrationRequet>) -> 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, Ok(user) => user,
Err(err) => return err Err(err) => return err
}; };

View file

@ -4,41 +4,41 @@ use crate::{types::{extract::AuthorizedUser, response::ResponseCode}, console};
async fn root(user: Option<AuthorizedUser>) -> Response { async fn root(user: Option<AuthorizedUser>) -> Response {
if user.is_some() { if user.is_some() {
return Redirect::to("/home").into_response() Redirect::to("/home").into_response()
} else { } else {
return Redirect::to("/login").into_response() Redirect::to("/login").into_response()
} }
} }
async fn login(user: Option<AuthorizedUser>) -> Response { async fn login(user: Option<AuthorizedUser>) -> Response {
if user.is_some() { if user.is_some() {
return Redirect::to("/home").into_response() Redirect::to("/home").into_response()
} else { } else {
return ResponseCode::Success.file("/login.html").await ResponseCode::Success.file("/login.html").await
} }
} }
async fn home(user: Option<AuthorizedUser>) -> Response { async fn home(user: Option<AuthorizedUser>) -> Response {
if user.is_none() { if user.is_none() {
return Redirect::to("/login").into_response() Redirect::to("/login").into_response()
} else { } else {
return ResponseCode::Success.file("/home.html").await ResponseCode::Success.file("/home.html").await
} }
} }
async fn people(user: Option<AuthorizedUser>) -> Response { async fn people(user: Option<AuthorizedUser>) -> Response {
if user.is_none() { if user.is_none() {
return Redirect::to("/login").into_response() Redirect::to("/login").into_response()
} else { } else {
return ResponseCode::Success.file("/people.html").await ResponseCode::Success.file("/people.html").await
} }
} }
async fn profile(user: Option<AuthorizedUser>) -> Response { async fn profile(user: Option<AuthorizedUser>) -> Response {
if user.is_none() { if user.is_none() {
return Redirect::to("/login").into_response() Redirect::to("/login").into_response()
} else { } else {
return ResponseCode::Success.file("/profile.html").await ResponseCode::Success.file("/profile.html").await
} }
} }

View file

@ -51,10 +51,10 @@ pub async fn log(ip: IpAddr, method: Method, uri: Uri, path: Option<String>, bod
tracing::info!("{} {} {}{} {}", &ip, &method, &path, &uri, &body); tracing::info!("{} {} {}{} {}", &ip, &method, &path, &uri, &body);
let message = LogMessage { let message = LogMessage {
ip: ip, ip,
method: method, method,
uri: uri, uri,
path: path, path,
body: beautify(body) body: beautify(body)
}; };
@ -153,7 +153,7 @@ impl Formatter for HtmlFormatter {
} }
fn beautify(body: String) -> String { fn beautify(body: String) -> String {
if body.len() < 1 { if body.is_empty() {
return "".to_string() return "".to_string()
} }
let Ok(mut json) = serde_json::from_str::<Value>(&body) else { let Ok(mut json) = serde_json::from_str::<Value>(&body) else {
@ -164,7 +164,7 @@ fn beautify(body: String) -> String {
} }
let mut writer: Vec<u8> = Vec::with_capacity(128); let mut writer: Vec<u8> = Vec::with_capacity(128);
let mut serializer = serde_json::Serializer::with_formatter(&mut writer, HtmlFormatter); 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 return body
} }
String::from_utf8_lossy(&writer).to_string() String::from_utf8_lossy(&writer).to_string()

View file

@ -5,7 +5,7 @@ pub mod users;
pub mod sessions; pub mod sessions;
pub fn connect() -> Result<rusqlite::Connection, rusqlite::Error> { pub fn connect() -> Result<rusqlite::Connection, rusqlite::Error> {
return rusqlite::Connection::open("xssbook.db"); rusqlite::Connection::open("xssbook.db")
} }
pub fn init() -> Result<()> { pub fn init() -> Result<()> {

View file

@ -48,7 +48,10 @@ pub fn get_post(post_id: u64) -> Result<Option<Post>, rusqlite::Error> {
tracing::trace!("Retrieving post"); tracing::trace!("Retrieving post");
let conn = database::connect()?; let conn = database::connect()?;
let mut stmt = conn.prepare("SELECT * FROM posts WHERE post_id = ?")?; 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) Ok(row)
} }
@ -58,7 +61,10 @@ pub fn get_post_page(page: u64) -> Result<Vec<Post>, rusqlite::Error> {
let page_size = 10; let page_size = 10;
let conn = database::connect()?; let conn = database::connect()?;
let mut stmt = conn.prepare("SELECT * FROM posts ORDER BY post_id DESC LIMIT ? OFFSET ?")?; 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()) Ok(row.into_iter().flatten().collect())
} }
@ -67,7 +73,10 @@ pub fn get_users_posts(user_id: u64) -> Result<Vec<Post>, rusqlite::Error> {
tracing::trace!("Retrieving users posts"); tracing::trace!("Retrieving users posts");
let conn = database::connect()?; let conn = database::connect()?;
let mut stmt = conn.prepare("SELECT * FROM posts WHERE user_id = ? ORDER BY post_id DESC")?; 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()) Ok(row.into_iter().flatten().collect())
} }
@ -85,7 +94,10 @@ pub fn add_post(user_id: u64, content: &str) -> Result<Post, rusqlite::Error> {
let date = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64; let date = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64;
let conn = database::connect()?; let conn = database::connect()?;
let mut stmt = conn.prepare("INSERT INTO posts (user_id, content, likes, comments, date) VALUES(?,?,?,?,?) RETURNING *;")?; 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) Ok(post)
} }

View file

@ -2,7 +2,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use rusqlite::{OptionalExtension, Row}; use rusqlite::{OptionalExtension, Row};
use tracing::instrument; use tracing::instrument;
use crate::{database, types::user::User}; use crate::{database, types::user::User, api::auth::RegistrationRequet};
pub fn init() -> Result<(), rusqlite::Error> { pub fn init() -> Result<(), rusqlite::Error> {
let sql = " let sql = "
@ -46,7 +46,10 @@ pub fn get_user_by_id(user_id: u64, hide_password: bool) -> Result<Option<User>,
tracing::trace!("Retrieving user by id"); tracing::trace!("Retrieving user by id");
let conn = database::connect()?; let conn = database::connect()?;
let mut stmt = conn.prepare("SELECT * FROM users WHERE user_id = ?")?; 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) Ok(row)
} }
@ -55,7 +58,10 @@ pub fn get_user_by_email(email: &str, hide_password: bool) -> Result<Option<User
tracing::trace!("Retrieving user by email"); tracing::trace!("Retrieving user by email");
let conn = database::connect()?; let conn = database::connect()?;
let mut stmt = conn.prepare("SELECT * FROM users WHERE email = ?")?; let mut stmt = conn.prepare("SELECT * FROM users WHERE email = ?")?;
let row = stmt.query_row([email], |row| Ok(user_from_row(row, hide_password)?)).optional()?; let row = stmt.query_row([email], |row| {
let row = user_from_row(row, hide_password)?;
Ok(row)
}).optional()?;
Ok(row) Ok(row)
} }
@ -64,7 +70,10 @@ pub fn get_user_by_password(password: &str, hide_password: bool) -> Result<Optio
tracing::trace!("Retrieving user by password"); tracing::trace!("Retrieving user by password");
let conn = database::connect()?; let conn = database::connect()?;
let mut stmt = conn.prepare("SELECT * FROM users WHERE password = ?")?; let mut stmt = conn.prepare("SELECT * FROM users WHERE password = ?")?;
let row = stmt.query_row([password], |row| Ok(user_from_row(row, hide_password)?)).optional()?; let row = stmt.query_row([password], |row| {
let row = user_from_row(row, hide_password)?;
Ok(row)
}).optional()?;
Ok(row) Ok(row)
} }
@ -74,17 +83,23 @@ pub fn get_user_page(page: u64, hide_password: bool) -> Result<Vec<User>, rusqli
let page_size = 5; let page_size = 5;
let conn = database::connect()?; let conn = database::connect()?;
let mut stmt = conn.prepare("SELECT * FROM users ORDER BY user_id DESC LIMIT ? OFFSET ?")?; 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()) Ok(row.into_iter().flatten().collect())
} }
#[instrument()] #[instrument()]
pub fn add_user(firstname: &str, lastname: &str, email: &str, password: &str, gender: &str, day: u8, month: u8, year: u32) -> Result<User, rusqlite::Error> { pub fn add_user(request: RegistrationRequet) -> Result<User, rusqlite::Error> {
tracing::trace!("Adding new user"); tracing::trace!("Adding new user");
let date = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64; let date = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64;
let conn = database::connect()?; let conn = database::connect()?;
let mut stmt = conn.prepare("INSERT INTO users (firstname, lastname, email, password, gender, date, day, month, year) VALUES(?,?,?,?,?,?,?,?,?) RETURNING *;")?; 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) Ok(user)
} }

View file

@ -28,9 +28,9 @@ async fn log<B>(mut req: Request<B>, next: Next<B>) -> Response where
return next.run(req).await 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 { async fn not_found() -> Response {

View file

@ -22,7 +22,7 @@ impl<S> FromRequestParts<S> for AuthorizedUser where S: Send + Sync {
return Err(ResponseCode::Forbidden.text("No auth token provided")) 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")) return Err(ResponseCode::Unauthorized.text("Auth token invalid"))
}; };
@ -55,16 +55,16 @@ impl<S, B> FromRequest<S, B> for Log where
let uri = req.uri().clone(); let uri = req.uri().clone();
let Ok(bytes) = Bytes::from_request(req, state).await else { 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) return Ok(Log)
}; };
let Ok(body) = String::from_utf8(bytes.bytes().flatten().collect()) else { 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) 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) Ok(Log)
} }
@ -101,7 +101,7 @@ impl<T, S, B> FromRequest<S, B> for Json<T> where
return Err(ResponseCode::BadRequest.text("Invalid utf8 body")) 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::<T>(&body) else { let Ok(value) = serde_json::from_str::<T>(&body) else {
return Err(ResponseCode::BadRequest.text("Invalid request body")) return Err(ResponseCode::BadRequest.text("Invalid request body"))

View file

@ -55,7 +55,7 @@ impl ResponseCode {
#[instrument()] #[instrument()]
pub async fn file(self, path: &str) -> Response { 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"); return ResponseCode::BadRequest.text("Folders cannot be served");
} }
let path = format!("public{}", path); let path = format!("public{}", path);

View file

@ -26,14 +26,14 @@ impl Session {
pub fn new(user_id: u64) -> Result<Self> { pub fn new(user_id: u64) -> Result<Self> {
let token: String = rand::thread_rng().sample_iter(&Alphanumeric).take(32).map(char::from).collect(); let token: String = rand::thread_rng().sample_iter(&Alphanumeric).take(32).map(char::from).collect();
match database::sessions::set_session(user_id, &token) { match database::sessions::set_session(user_id, &token) {
Err(_) => return Err(ResponseCode::BadRequest.text("Failed to create session")), Err(_) => Err(ResponseCode::BadRequest.text("Failed to create session")),
Ok(_) => return Ok(Session {user_id, token}) Ok(_) => Ok(Session {user_id, token})
}; }
} }
#[instrument()] #[instrument()]
pub fn delete(user_id: u64) -> Result<()> { 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"); tracing::error!("Failed to logout user");
return Err(ResponseCode::InternalServerError.text("Failed to logout")); return Err(ResponseCode::InternalServerError.text("Failed to logout"));
}; };

View file

@ -1,6 +1,7 @@
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use tracing::instrument; use tracing::instrument;
use crate::api::auth::RegistrationRequet;
use crate::database; use crate::database;
use crate::types::response::{Result, ResponseCode}; use crate::types::response::{Result, ResponseCode};
@ -32,12 +33,12 @@ impl User {
#[instrument()] #[instrument()]
pub fn from_user_ids(user_ids: Vec<u64>) -> Vec<Self> { pub fn from_user_ids(user_ids: Vec<u64>) -> Vec<Self> {
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 { let Ok(Some(user)) = database::users::get_user_by_id(*user_id, true) else {
return None; return None;
}; };
Some(user) Some(user)
}).flatten().collect() }).collect()
} }
#[instrument()] #[instrument()]
@ -67,16 +68,16 @@ impl User {
} }
#[instrument()] #[instrument()]
pub fn new(firstname: String, lastname: String, email: String, password: String, gender: String, day: u8, month: u8, year: u32) -> Result<Self> { pub fn new(request: RegistrationRequet) -> Result<Self> {
if let Ok(_) = User::from_email(&email) { if User::from_email(&request.email).is_ok() {
return Err(ResponseCode::BadRequest.text(&format!("Email is already in use by {}", &email))) 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))) 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"); tracing::error!("Failed to create new user");
return Err(ResponseCode::InternalServerError.text("Failed to create new uesr")) return Err(ResponseCode::InternalServerError.text("Failed to create new uesr"))
}; };