Commit ff304659 authored by Robert Czechowski's avatar Robert Czechowski
Browse files

Add debug logging feature, remove BadRequest modifier from iexpect (is already...

Add debug logging feature, remove BadRequest modifier from iexpect (is already default), shorten overriding config with options
parent 6a88ea35
Pipeline #202 failed with stage
in 3 minutes and 34 seconds
...@@ -17,6 +17,7 @@ server = ["rusqlite", "postgres"] ...@@ -17,6 +17,7 @@ server = ["rusqlite", "postgres"]
desktop = ["rusqlite", "webbrowser"] desktop = ["rusqlite", "webbrowser"]
watch = ["handlebars-iron/watch"] watch = ["handlebars-iron/watch"]
strict = [] # Treat warnings as a build error strict = [] # Treat warnings as a build error
debug = []
[dependencies] [dependencies]
time = "0.1.40" time = "0.1.40"
......
debug: debug:
RUST_BACKTRACE=1 cargo run --features 'watch' -- -a RUST_BACKTRACE=1 cargo run --features 'watch debug' -- -a
test: test:
RUST_BACKTRACE=1 cargo test --features 'watch complete' RUST_BACKTRACE=1 cargo test --features 'complete debug'
release: release:
env OPENSSL_LIB_DIR=/usr/lib/x86_64-linux-gnu/ OPENSSL_INCLUDE_DIR=/usr/local/include OPENSSL_STATIC=yes cargo build --release --features 'server' env OPENSSL_LIB_DIR=/usr/lib/x86_64-linux-gnu/ OPENSSL_INCLUDE_DIR=/usr/local/include OPENSSL_STATIC=yes cargo build --release --features 'server'
......
...@@ -12,18 +12,19 @@ extern crate iron_sessionstorage; ...@@ -12,18 +12,19 @@ extern crate iron_sessionstorage;
extern crate mount; extern crate mount;
extern crate params; extern crate params;
extern crate persistent; extern crate persistent;
#[cfg(feature = "postgres")]
extern crate postgres;
extern crate rand; extern crate rand;
extern crate reqwest; extern crate reqwest;
#[cfg(feature = "rusqlite")]
extern crate rusqlite;
extern crate serde_json; extern crate serde_json;
extern crate serde_yaml; extern crate serde_yaml;
extern crate staticfile; extern crate staticfile;
extern crate structopt; extern crate structopt;
extern crate time; extern crate time;
extern crate urlencoded; extern crate urlencoded;
#[cfg(feature = "postgres")]
extern crate postgres;
#[cfg(feature = "rusqlite")]
extern crate rusqlite;
#[cfg(feature = "webbrowser")] #[cfg(feature = "webbrowser")]
extern crate webbrowser; extern crate webbrowser;
...@@ -42,7 +43,7 @@ mod webfw_iron; ...@@ -42,7 +43,7 @@ mod webfw_iron;
use db_conn::{MedalConnection, MedalObject}; use db_conn::{MedalConnection, MedalObject};
use db_objects::*; use db_objects::*;
use helpers::SetPassword; // TODO: Refactor, so we don't need to take this from there! use helpers::SetPassword;
use webfw_iron::start_server; use webfw_iron::start_server;
use config::Config; use config::Config;
...@@ -186,28 +187,27 @@ fn open_browser_window(self_url: &str) { ...@@ -186,28 +187,27 @@ fn open_browser_window(self_url: &str) {
fn main() { fn main() {
let opt = config::Opt::from_args(); let opt = config::Opt::from_args();
//println!("{:?}", opt); // Show in different debug level?
#[cfg(feature = "debug")]
println!("Options: {:#?}", opt);
let mut config = config::read_config_from_file(&opt.configfile); let mut config = config::read_config_from_file(&opt.configfile);
if opt.databasefile.is_some() { #[cfg(feature = "debug")]
config.database_file = opt.databasefile; println!("Config: {:#?}", config);
}
if config.database_file.is_none() { // Let options override config values
config.database_file = Some(Path::new("medal.db").to_owned()) opt.databasefile.map(|x| config.database_file = Some(x));
} opt.databaseurl.map(|x| config.database_url = Some(x));
if opt.databaseurl.is_some() { opt.port.map(|x| config.port = Some(x));
config.database_url = opt.databaseurl; config.no_contest_scan = if opt.nocontestscan { Some(true) } else { config.no_contest_scan };
} config.open_browser = if opt.openbrowser { Some(true) } else { config.open_browser };
if opt.port.is_some() {
config.port = opt.port; // Use default database file if none set
} config.database_file.get_or_insert(Path::new("medal.db").to_owned());
if opt.nocontestscan {
config.no_contest_scan = Some(true); #[cfg(feature = "debug")]
} println!("Using config: {:#?}", config);
if opt.openbrowser {
config.open_browser = Some(true)
}
#[cfg(feature = "postgres")] #[cfg(feature = "postgres")]
{ {
...@@ -330,7 +330,10 @@ mod tests { ...@@ -330,7 +330,10 @@ mod tests {
// Wait for server to start // Wait for server to start
start_rx.recv().unwrap(); start_rx.recv().unwrap();
thread::sleep(time::Duration::from_millis(100)); thread::sleep(time::Duration::from_millis(100));
// Run test code
f(); f();
// Message test finished // Message test finished
stop_tx.send(()).unwrap(); stop_tx.send(()).unwrap();
} }
...@@ -629,6 +632,7 @@ mod tests { ...@@ -629,6 +632,7 @@ mod tests {
let resp = client.post("http://localhost:8086/save/1").form(&params).send().unwrap(); let resp = client.post("http://localhost:8086/save/1").form(&params).send().unwrap();
assert_eq!(resp.status(), StatusCode::FORBIDDEN); assert_eq!(resp.status(), StatusCode::FORBIDDEN);
// Check that the illigal request did not actually change anything
let mut resp = client.get("http://localhost:8086/load/1").send().unwrap(); let mut resp = client.get("http://localhost:8086/load/1").send().unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
......
...@@ -7,7 +7,7 @@ use iron_sessionstorage::traits::*; ...@@ -7,7 +7,7 @@ use iron_sessionstorage::traits::*;
use iron::modifiers::Redirect; use iron::modifiers::Redirect;
use iron::modifiers::RedirectRaw; use iron::modifiers::RedirectRaw;
use iron::{status, AfterMiddleware}; use iron::{status, AfterMiddleware, BeforeMiddleware};
use mount::Mount; use mount::Mount;
use router::Router; use router::Router;
...@@ -106,6 +106,20 @@ impl AroundMiddleware for CookieDistributor { ...@@ -106,6 +106,20 @@ impl AroundMiddleware for CookieDistributor {
} }
} }
pub struct RequestLogger {}
impl RequestLogger {
pub fn new() -> Self { Self {} }
}
impl BeforeMiddleware for RequestLogger {
fn before(&self, req: &mut Request) -> IronResult<()> {
println!("{}: {}", req.method, req.url);
Ok(())
}
}
#[derive(Debug)] #[derive(Debug)]
struct SessionError { struct SessionError {
message: String, message: String,
...@@ -283,7 +297,8 @@ fn debug_new_token<C>(req: &mut Request) -> IronResult<Response> ...@@ -283,7 +297,8 @@ fn debug_new_token<C>(req: &mut Request) -> IronResult<Response>
where C: MedalConnection + std::marker::Send + 'static { where C: MedalConnection + std::marker::Send + 'static {
let session_token = req.get_session_token(); let session_token = req.get_session_token();
println!("Loggin out session {:?}", session_token); #[cfg(feature = "debug")]
println!("Logging out session {:?}", session_token);
with_conn![core::logout, C, req, session_token]; with_conn![core::logout, C, req, session_token];
...@@ -294,7 +309,8 @@ fn debug_logout<C>(req: &mut Request) -> IronResult<Response> ...@@ -294,7 +309,8 @@ fn debug_logout<C>(req: &mut Request) -> IronResult<Response>
where C: MedalConnection + std::marker::Send + 'static { where C: MedalConnection + std::marker::Send + 'static {
let session_token = req.get_session_token(); let session_token = req.get_session_token();
println!("Loggin out session {:?}", session_token); #[cfg(feature = "debug")]
println!("Logging out session {:?}", session_token);
with_conn![core::logout, C, req, session_token]; with_conn![core::logout, C, req, session_token];
...@@ -468,16 +484,14 @@ fn submission_post<C>(req: &mut Request) -> IronResult<Response> ...@@ -468,16 +484,14 @@ fn submission_post<C>(req: &mut Request) -> IronResult<Response>
let session_token = req.expect_session_token()?; let session_token = req.expect_session_token()?;
let (csrf_token, data, grade, subtask) = { let (csrf_token, data, grade, subtask) = {
let formdata = iexpect!(req.get_ref::<UrlEncodedBody>().ok()); let formdata = iexpect!(req.get_ref::<UrlEncodedBody>().ok());
(iexpect!(formdata.get("csrf_token"),(status::BadRequest, mime!(Text/Html), format!("400 Bad Request")))[0].to_owned(), (iexpect!(formdata.get("csrf_token"))[0].to_owned(),
iexpect!(formdata.get("data"),(status::BadRequest, mime!(Text/Html), format!("400 Bad Request")))[0].to_owned(), iexpect!(formdata.get("data"))[0].to_owned(),
iexpect!(formdata.get("grade").unwrap_or(&vec!["0".to_owned()])[0].parse::<i32>().ok(),(status::BadRequest, mime!(Text/Html), format!("400 Bad Request"))), iexpect!(formdata.get("grade").unwrap_or(&vec!["0".to_owned()])[0].parse::<i32>().ok()),
formdata.get("subtask").map(|x| x[0].to_owned()), formdata.get("subtask").map(|x| x[0].to_owned()))
)
}; };
/* This should only be printed in verbose Mode:
print!("New submission for task {} (graded {}): ", task_id, grade); #[cfg(feature = "debug")]
println!("{}", data); println!("New submission for task {} (graded {}): {}", task_id, grade, data);
*/
let result = let result =
with_conn![core::save_submission, C, req, task_id, &session_token, &csrf_token, data, grade, subtask].aug(req)?; with_conn![core::save_submission, C, req, task_id, &session_token, &csrf_token, data, grade, subtask].aug(req)?;
...@@ -537,9 +551,9 @@ fn new_group<C>(req: &mut Request) -> IronResult<Response> ...@@ -537,9 +551,9 @@ fn new_group<C>(req: &mut Request) -> IronResult<Response>
let (csrf_token, name, tag) = { let (csrf_token, name, tag) = {
let formdata = iexpect!(req.get_ref::<UrlEncodedBody>().ok()); let formdata = iexpect!(req.get_ref::<UrlEncodedBody>().ok());
(iexpect!(formdata.get("csrf_token"),(status::BadRequest, mime!(Text/Html), format!("400 Bad Request")))[0].to_owned(), (iexpect!(formdata.get("csrf_token"))[0].to_owned(),
iexpect!(formdata.get("name"),(status::BadRequest, mime!(Text/Html), format!("400 Bad Request")))[0].to_owned(), iexpect!(formdata.get("name"))[0].to_owned(),
iexpect!(formdata.get("tag"),(status::BadRequest, mime!(Text/Html), format!("400 Bad Request")))[0].to_owned()) iexpect!(formdata.get("tag"))[0].to_owned())
}; };
let group_id = with_conn![core::add_group, C, req, &session_token, &csrf_token, name, tag].aug(req)?; let group_id = with_conn![core::add_group, C, req, &session_token, &csrf_token, name, tag].aug(req)?;
...@@ -876,7 +890,7 @@ pub fn start_server<C>(conn: C, config: Config) -> iron::error::HttpResult<iron: ...@@ -876,7 +890,7 @@ pub fn start_server<C>(conn: C, config: Config) -> iron::error::HttpResult<iron:
debug_create: get "/debug/create" => debug_create_session::<C>, debug_create: get "/debug/create" => debug_create_session::<C>,
); );
// TODO: how important is this? Should this be in the config? // TODO: how important is this? Should this be in the config? Or should this be autogenerated and saved to disk?
let my_secret = b"verysecret".to_vec(); let my_secret = b"verysecret".to_vec();
let mut mount = Mount::new(); let mut mount = Mount::new();
...@@ -888,8 +902,12 @@ pub fn start_server<C>(conn: C, config: Config) -> iron::error::HttpResult<iron: ...@@ -888,8 +902,12 @@ pub fn start_server<C>(conn: C, config: Config) -> iron::error::HttpResult<iron:
let mut ch = Chain::new(mount); let mut ch = Chain::new(mount);
#[cfg(feature = "debug")]
ch.link_before(RequestLogger::new());
ch.link(Write::<SharedDatabaseConnection<C>>::both(conn)); ch.link(Write::<SharedDatabaseConnection<C>>::both(conn));
ch.link(Write::<SharedConfiguration>::both(config.clone())); ch.link(Write::<SharedConfiguration>::both(config.clone()));
ch.link_around(CookieDistributor::new()); ch.link_around(CookieDistributor::new());
ch.link_around(SessionStorage::new(SignedCookieBackend::new(my_secret))); ch.link_around(SessionStorage::new(SignedCookieBackend::new(my_secret)));
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment