1
0
Fork 0
mirror of https://github.com/SinTan1729/chhoto-url synced 2024-12-26 23:58:35 -06:00

chg: Get rid of naked unwraps and improve code flow

This commit is contained in:
Sayantan Santra 2024-04-02 17:43:36 -05:00
parent f27984a63f
commit 0469f9b933
Signed by: SinTan1729
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; return true;
} }
let token = session.get::<String>("session-token"); if let Ok(token) = session.get::<String>("session-token") {
token.is_ok() && check(token.unwrap()) check(token)
} else {
false
}
} }
fn check(token: Option<String>) -> bool { 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> { pub fn find_url(shortlink: &str, db: &Connection) -> Option<String> {
let mut statement = db let mut statement = db
.prepare_cached("SELECT long_url FROM urls WHERE short_url = ?1") .prepare_cached("SELECT long_url FROM urls WHERE short_url = ?1")
.unwrap(); .expect("Error preparing SQL statement for find_url.");
statement statement
.query_row([shortlink], |row| row.get("long_url")) .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> { 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(); 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 { let row_struct = DBRow {
shortlink: row.get("short_url").unwrap(), shortlink: row
longlink: row.get("long_url").unwrap(), .get("short_url")
hits: row.get("hits").unwrap(), .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); 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", "UPDATE urls SET hits = hits + 1 WHERE short_url = ?1",
[shortlink], [shortlink],
) )
.unwrap(); .expect("Error updating hit count.");
} }
pub fn add_link(shortlink: String, longlink: String, db: &Connection) -> bool { 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 { pub fn delete_link(shortlink: String, db: &Connection) -> bool {
let out = db.execute("DELETE FROM urls WHERE short_url = ?1", [shortlink]); if let Ok(delta) = db.execute("DELETE FROM urls WHERE short_url = ?1", [shortlink]) {
out.is_ok() && (out.unwrap() > 0) delta > 0
} else {
false
}
} }
pub fn open_db(path: String) -> Connection { 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 db
} }

View file

@ -100,14 +100,17 @@ async fn link_handler(shortlink: web::Path<String>, data: web::Data<AppState>) -
// Handle login // Handle login
#[post("/api/login")] #[post("/api/login")]
async fn login(req: String, session: Session) -> HttpResponse { async fn login(req: String, session: Session) -> HttpResponse {
if req == env::var("password").unwrap_or(req.clone()) { if let Ok(password) = env::var("password") {
// If no password was provided, match any password if password != req {
session.insert("session-token", auth::gen_token()).unwrap(); eprintln!("Failed login attempt!");
HttpResponse::Ok().body("Correct password!") return HttpResponse::Forbidden().body("Wrong password!");
} else { }
eprintln!("Failed login attempt!");
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 // 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 { 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) re.is_match(link)
} }
pub fn getall(db: &Connection) -> String { pub fn getall(db: &Connection) -> String {
let links = database::getall(db); 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) { pub fn add_link(req: String, db: &Connection) -> (bool, String) {
let mut chunks: URLPair = serde_json::from_str(&req).unwrap_or_default(); let mut chunks: URLPair;
if let Ok(json) = serde_json::from_str(&req) {
if chunks == URLPair::default() { chunks = json;
} else {
return (false, String::from("Invalid request!")); return (false, String::from("Invalid request!"));
} }
let style = env::var("slug_style").unwrap_or(String::from("Pair")); 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 = env::var("slug_style")
let mut len: usize = len_str.parse().unwrap_or(8); .ok()
.and_then(|s| s.parse::<usize>().ok())
.unwrap_or(8);
if len < 4 { if len < 4 {
len = 4; len = 4;
} }
@ -110,8 +113,12 @@ fn gen_link(style: String, len: usize) -> String {
} else { } else {
format!( format!(
"{0}-{1}", "{0}-{1}",
ADJECTIVES.choose(&mut rand::thread_rng()).unwrap(), ADJECTIVES
NAMES.choose(&mut rand::thread_rng()).unwrap() .choose(&mut rand::thread_rng())
.expect("Error choosing random adjective."),
NAMES
.choose(&mut rand::thread_rng())
.expect("Error choosing random name.")
) )
} }
} }