From 03c41b68332665b5e87f34d4f317e01a091af1b6 Mon Sep 17 00:00:00 2001 From: shockrah Date: Sat, 20 Mar 2021 19:47:59 -0700 Subject: [PATCH] - Removed joindate from members schema + Auth module now uses std::time for time based calculations ! All time notations are i64 and rounded to the Millisecond * Moving db pool to a lazy static to avoid constructing a whole pool on every request + Adding more logging per request, even if its lazy logging * Content-Types are now correctly written per type --- json-api/Makefile | 3 ++ .../2020-07-05-215114_members/up.sql | 1 - json-api/src/auth.rs | 6 ++- json-api/src/main.rs | 45 +++++++++++-------- json-api/src/messages.rs | 8 +++- 5 files changed, 41 insertions(+), 22 deletions(-) diff --git a/json-api/Makefile b/json-api/Makefile index 2fbf707..c4aae21 100644 --- a/json-api/Makefile +++ b/json-api/Makefile @@ -4,5 +4,8 @@ default: dep: cargo update +run: + cargo run --release -- -s + clean: cargo clean diff --git a/json-api/migrations/2020-07-05-215114_members/up.sql b/json-api/migrations/2020-07-05-215114_members/up.sql index 9715076..2c8c22c 100644 --- a/json-api/migrations/2020-07-05-215114_members/up.sql +++ b/json-api/migrations/2020-07-05-215114_members/up.sql @@ -4,7 +4,6 @@ CREATE TABLE IF NOT EXISTS `members`( `id` BIGINT UNSIGNED NOT NULL auto_increment, `secret` varchar(256) NOT NULL, `name` varchar(256) NOT NULL, - `joindate` bigint NOT NULL, `status` integer NOT NULL, `permissions` bigint UNSIGNED NOT NULL, PRIMARY KEY( `id` , `secret` ) diff --git a/json-api/src/auth.rs b/json-api/src/auth.rs index 5d13067..1ecc958 100644 --- a/json-api/src/auth.rs +++ b/json-api/src/auth.rs @@ -3,7 +3,7 @@ use bcrypt::{self, BcryptResult}; use mysql_async::Pool; use std::collections::HashMap; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; use crate::routes; use crate::qs_param; @@ -30,7 +30,9 @@ struct Claim { impl Claim { pub fn new(id: db::UBigInt) -> Claim { - let now = SystemTime::now() + + // JWT's expire every 48 hours + let now = (SystemTime::now() + Duration::from_secs(60 * 60 * 48)) .duration_since(UNIX_EPOCH) .expect("System time fetch failed") .as_millis() as i64; diff --git a/json-api/src/main.rs b/json-api/src/main.rs index 3bdf0ed..a17bd12 100644 --- a/json-api/src/main.rs +++ b/json-api/src/main.rs @@ -45,6 +45,12 @@ const NO_ERR: u16 = 0; const CONFIG_ERR: u16 = 1; const SHUTDOWN_ERR: u16 = 2; +lazy_static! { + static ref DB_POOL: Pool = { + Pool::new(&env::var("DATABASE_URL").unwrap()) + }; +} + async fn route_dispatcher( pool: &Pool, resp: &mut Response, @@ -82,7 +88,7 @@ async fn route_dispatcher( /* META ROUTE */ (GET, routes::META) => meta::server_meta(resp).await, _ => { - eprintln!("\tNOT FOUND: {}: {}", meth, path); + println!("\tNOT FOUND: {}: {}", meth, path); *resp.status_mut() = StatusCode::NOT_FOUND } } @@ -104,13 +110,21 @@ async fn main_responder(request: Request) -> Result, hyper: }; if let Some(params) = params_opt { - let mysql_pool = Pool::new(&env::var("DATABASE_URL").unwrap()); - match auth::wall_entry(path, &mysql_pool, ¶ms).await { - OpenAuth | Good => route_dispatcher(&mysql_pool, &mut response, &method, path, body, params, headers).await, - LoginValid => auth::login_get_jwt(&mysql_pool, &mut response, params).await, - NoKey | BadKey => *response.status_mut() = StatusCode::UNAUTHORIZED, + match auth::wall_entry(path, &DB_POOL, ¶ms).await { + OpenAuth | Good => { + // route dispatch has its own more comprehensive logging + route_dispatcher(&DB_POOL, &mut response, &method, path, body, params, headers).await; + }, + LoginValid => { + println!("LoginValid"); + auth::login_get_jwt(&DB_POOL, &mut response, params).await; + }, + NoKey | BadKey => { + println!("NoKey | BadKey"); + *response.status_mut() = StatusCode::UNAUTHORIZED; + }, ServerIssue(msg) => { - println!("\tAUTH : 500 [{}]", msg); + eprintln!("{}", msg); *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; } } @@ -158,8 +172,8 @@ async fn attempt_owner_creation(name: &str) { let p = Pool::new(&env::var("DATABASE_URL").unwrap()); let owner_secret = auth::generate_secret(); if let Ok(enc_secret) = auth::encrypt_secret(&owner_secret) { - if let Ok(response) = db::Member::add(&p, name, &enc_secret, perms::OWNER).await { - match response { + match db::Member::add(&p, name, &enc_secret, perms::OWNER).await { + Ok(response) => match response { db::Response::Row(mut owner) => { owner.secret = owner_secret; // giving the secret itself back to the user let server_config = serde_json::json!({ @@ -168,15 +182,10 @@ async fn attempt_owner_creation(name: &str) { }); println!("{}", serde_json::to_string_pretty(&server_config).unwrap()); }, - db::Response::Empty => { - eprintln!("SQL server failed to return owner data, check configs and also the members table to make sure there's nothing there by accident"); - }, - _ => {} - }; - } - else { - eprintln!("Could not communicate with the SQL server, check your configs!"); - } + _ => eprintln!("SQL server failed to return owner data, check configs and also the members table to make sure there's nothing there by accident") + }, + Err(e) => eprintln!("Error communicating with database : {}", e) + }; } else { eprintln!("Could not generate a proper secret"); diff --git a/json-api/src/messages.rs b/json-api/src/messages.rs index 03c2b12..0884526 100644 --- a/json-api/src/messages.rs +++ b/json-api/src/messages.rs @@ -68,6 +68,7 @@ pub async fn send_message(pool: &Pool, response: &mut Response, body: Body let uid = qs_param!(params, "id", u64).unwrap(); let ctype: Option<&str> = match headers.get("Content-Type") { Some(hval) => { + println!("{:?}", hval); match hval.to_str() { Ok(s) => Some(s), _ => None @@ -96,7 +97,12 @@ pub async fn send_message(pool: &Pool, response: &mut Response, body: Body *response.status_mut() = StatusCode::BAD_REQUEST; } else { // block away wrong content types - const CONTENT_TYPES: [&'static str;7] = ["text", "png", "jpeg", "jpg", "webm", "mp3", "mp4"]; + const CONTENT_TYPES: [&'static str;7] = [ + "text/plain", + "image/png", "image/jpeg", "image/jpg", + "application/webm", "application/mp4", + "application/mp3" + ]; if CONTENT_TYPES.contains(&ctype.unwrap()) == false { *response.status_mut() = StatusCode::BAD_REQUEST; }