mirror of
https://github.com/minoplhy/chhoto-url.git
synced 2024-11-25 10:16:46 +00:00
chg: Get rid of naked unwraps and improve code flow
This commit is contained in:
parent
f27984a63f
commit
0469f9b933
@ -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 {
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -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 {
|
||||
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
|
||||
|
@ -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.")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user