From 0469f9b933386a0d6b44ce0401ad083d395faef6 Mon Sep 17 00:00:00 2001 From: SinTan1729 Date: Tue, 2 Apr 2024 17:43:36 -0500 Subject: [PATCH] chg: Get rid of naked unwraps and improve code flow --- actix/src/auth.rs | 7 +++++-- actix/src/database.rs | 33 ++++++++++++++++++++++----------- actix/src/main.rs | 17 ++++++++++------- actix/src/utils.rs | 25 ++++++++++++++++--------- 4 files changed, 53 insertions(+), 29 deletions(-) diff --git a/actix/src/auth.rs b/actix/src/auth.rs index 25a56bd..1aacd98 100644 --- a/actix/src/auth.rs +++ b/actix/src/auth.rs @@ -7,8 +7,11 @@ pub fn validate(session: Session) -> bool { return true; } - let token = session.get::("session-token"); - token.is_ok() && check(token.unwrap()) + if let Ok(token) = session.get::("session-token") { + check(token) + } else { + false + } } fn check(token: Option) -> bool { diff --git a/actix/src/database.rs b/actix/src/database.rs index 14c5ff5..020c92c 100644 --- a/actix/src/database.rs +++ b/actix/src/database.rs @@ -11,7 +11,7 @@ pub struct DBRow { pub fn find_url(shortlink: &str, db: &Connection) -> Option { let mut statement = db .prepare_cached("SELECT long_url FROM urls WHERE short_url = ?1") - .unwrap(); + .expect("Error preparing SQL statement for find_url."); statement .query_row([shortlink], |row| row.get("long_url")) @@ -19,16 +19,24 @@ pub fn find_url(shortlink: &str, db: &Connection) -> Option { } pub fn getall(db: &Connection) -> Vec { - let mut statement = db.prepare_cached("SELECT * FROM urls").unwrap(); + let mut statement = db + .prepare_cached("SELECT * FROM urls") + .expect("Error preparing SQL statement for getall."); - let mut data = statement.query([]).unwrap(); + let mut data = statement + .query([]) + .expect("Error executing query for getall."); let mut links: Vec = Vec::new(); - while let Some(row) = data.next().unwrap() { + while let Some(row) = data.next().expect("Error reading fetched rows.") { let row_struct = DBRow { - shortlink: row.get("short_url").unwrap(), - longlink: row.get("long_url").unwrap(), - hits: row.get("hits").unwrap(), + shortlink: row + .get("short_url") + .expect("Error reading shortlink from row."), + longlink: row + .get("long_url") + .expect("Error reading shortlink from row."), + hits: row.get("hits").expect("Error reading shortlink from row."), }; links.push(row_struct); } @@ -41,7 +49,7 @@ pub fn add_hit(shortlink: &str, db: &Connection) { "UPDATE urls SET hits = hits + 1 WHERE short_url = ?1", [shortlink], ) - .unwrap(); + .expect("Error updating hit count."); } pub fn add_link(shortlink: String, longlink: String, db: &Connection) -> bool { @@ -53,8 +61,11 @@ pub fn add_link(shortlink: String, longlink: String, db: &Connection) -> bool { } pub fn delete_link(shortlink: String, db: &Connection) -> bool { - let out = db.execute("DELETE FROM urls WHERE short_url = ?1", [shortlink]); - out.is_ok() && (out.unwrap() > 0) + if let Ok(delta) = db.execute("DELETE FROM urls WHERE short_url = ?1", [shortlink]) { + delta > 0 + } else { + false + } } pub fn open_db(path: String) -> Connection { @@ -69,6 +80,6 @@ pub fn open_db(path: String) -> Connection { )", [], ) - .unwrap(); + .expect("Unable to initialize empty database."); db } diff --git a/actix/src/main.rs b/actix/src/main.rs index 7620ca4..8c64a76 100644 --- a/actix/src/main.rs +++ b/actix/src/main.rs @@ -100,14 +100,17 @@ async fn link_handler(shortlink: web::Path, data: web::Data) - // Handle login #[post("/api/login")] async fn login(req: String, session: Session) -> HttpResponse { - if req == env::var("password").unwrap_or(req.clone()) { - // If no password was provided, match any password - session.insert("session-token", auth::gen_token()).unwrap(); - HttpResponse::Ok().body("Correct password!") - } else { - eprintln!("Failed login attempt!"); - HttpResponse::Forbidden().body("Wrong password!") + if let Ok(password) = env::var("password") { + if password != req { + eprintln!("Failed login attempt!"); + return HttpResponse::Forbidden().body("Wrong password!"); + } } + // Return Ok if no password was set on the server side + session + .insert("session-token", auth::gen_token()) + .expect("Error inserting session-token."); + HttpResponse::Ok().body("Correct password!") } // Delete a given shortlink diff --git a/actix/src/utils.rs b/actix/src/utils.rs index 900f744..5a4f9c2 100644 --- a/actix/src/utils.rs +++ b/actix/src/utils.rs @@ -22,25 +22,28 @@ pub fn get_longurl(shortlink: String, db: &Connection) -> Option { } fn validate_link(link: &str) -> bool { - let re = Regex::new("^[a-z0-9-_]+$").unwrap(); + let re = Regex::new("^[a-z0-9-_]+$").expect("Regex generation failed."); re.is_match(link) } pub fn getall(db: &Connection) -> String { let links = database::getall(db); - serde_json::to_string(&links).unwrap() + serde_json::to_string(&links).expect("Failure during creation of json from db.") } pub fn add_link(req: String, db: &Connection) -> (bool, String) { - let mut chunks: URLPair = serde_json::from_str(&req).unwrap_or_default(); - - if chunks == URLPair::default() { + let mut chunks: URLPair; + if let Ok(json) = serde_json::from_str(&req) { + chunks = json; + } else { return (false, String::from("Invalid request!")); } let style = env::var("slug_style").unwrap_or(String::from("Pair")); - let len_str = env::var("slug_length").unwrap_or(String::from("8")); - let mut len: usize = len_str.parse().unwrap_or(8); + let mut len = env::var("slug_style") + .ok() + .and_then(|s| s.parse::().ok()) + .unwrap_or(8); if len < 4 { len = 4; } @@ -110,8 +113,12 @@ fn gen_link(style: String, len: usize) -> String { } else { format!( "{0}-{1}", - ADJECTIVES.choose(&mut rand::thread_rng()).unwrap(), - NAMES.choose(&mut rand::thread_rng()).unwrap() + ADJECTIVES + .choose(&mut rand::thread_rng()) + .expect("Error choosing random adjective."), + NAMES + .choose(&mut rand::thread_rng()) + .expect("Error choosing random name.") ) } }