chg: Get rid of naked unwraps and improve code flow

This commit is contained in:
SinTan1729 2024-04-02 17:43:36 -05:00
parent f27984a63f
commit 0469f9b933
No known key found for this signature in database
GPG Key ID: EB3E68BFBA25C85F
4 changed files with 53 additions and 29 deletions

View File

@ -7,8 +7,11 @@ pub fn validate(session: Session) -> bool {
return true;
}
let token = session.get::<String>("session-token");
token.is_ok() && check(token.unwrap())
if let Ok(token) = session.get::<String>("session-token") {
check(token)
} else {
false
}
}
fn check(token: Option<String>) -> bool {

View File

@ -11,7 +11,7 @@ pub struct DBRow {
pub fn find_url(shortlink: &str, db: &Connection) -> Option<String> {
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<String> {
}
pub fn getall(db: &Connection) -> Vec<DBRow> {
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<DBRow> = 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
}

View File

@ -100,14 +100,17 @@ async fn link_handler(shortlink: web::Path<String>, data: web::Data<AppState>) -
// 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 {
if let Ok(password) = env::var("password") {
if password != req {
eprintln!("Failed login attempt!");
HttpResponse::Forbidden().body("Wrong password!")
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

View File

@ -22,25 +22,28 @@ pub fn get_longurl(shortlink: String, db: &Connection) -> Option<String> {
}
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::<usize>().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.")
)
}
}