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"]
desktop = ["rusqlite", "webbrowser"]
watch = ["handlebars-iron/watch"]
strict = [] # Treat warnings as a build error
debug = []
[dependencies]
time = "0.1.40"
......
debug:
RUST_BACKTRACE=1 cargo run --features 'watch' -- -a
RUST_BACKTRACE=1 cargo run --features 'watch debug' -- -a
test:
RUST_BACKTRACE=1 cargo test --features 'watch complete'
RUST_BACKTRACE=1 cargo test --features 'complete debug'
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'
......
......@@ -12,18 +12,19 @@ extern crate iron_sessionstorage;
extern crate mount;
extern crate params;
extern crate persistent;
#[cfg(feature = "postgres")]
extern crate postgres;
extern crate rand;
extern crate reqwest;
#[cfg(feature = "rusqlite")]
extern crate rusqlite;
extern crate serde_json;
extern crate serde_yaml;
extern crate staticfile;
extern crate structopt;
extern crate time;
extern crate urlencoded;
#[cfg(feature = "postgres")]
extern crate postgres;
#[cfg(feature = "rusqlite")]
extern crate rusqlite;
#[cfg(feature = "webbrowser")]
extern crate webbrowser;
......@@ -42,7 +43,7 @@ mod webfw_iron;
use db_conn::{MedalConnection, MedalObject};
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 config::Config;
......@@ -186,28 +187,27 @@ fn open_browser_window(self_url: &str) {
fn main() {
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);
if opt.databasefile.is_some() {
config.database_file = opt.databasefile;
}
if config.database_file.is_none() {
config.database_file = Some(Path::new("medal.db").to_owned())
}
if opt.databaseurl.is_some() {
config.database_url = opt.databaseurl;
}
if opt.port.is_some() {
config.port = opt.port;
}
if opt.nocontestscan {
config.no_contest_scan = Some(true);
}
if opt.openbrowser {
config.open_browser = Some(true)
}
#[cfg(feature = "debug")]
println!("Config: {:#?}", config);
// Let options override config values
opt.databasefile.map(|x| config.database_file = Some(x));
opt.databaseurl.map(|x| config.database_url = Some(x));
opt.port.map(|x| config.port = Some(x));
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 };
// Use default database file if none set
config.database_file.get_or_insert(Path::new("medal.db").to_owned());
#[cfg(feature = "debug")]
println!("Using config: {:#?}", config);
#[cfg(feature = "postgres")]
{
......@@ -330,7 +330,10 @@ mod tests {
// Wait for server to start
start_rx.recv().unwrap();
thread::sleep(time::Duration::from_millis(100));
// Run test code
f();
// Message test finished
stop_tx.send(()).unwrap();
}
......@@ -629,6 +632,7 @@ mod tests {
let resp = client.post("http://localhost:8086/save/1").form(&params).send().unwrap();
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();
assert_eq!(resp.status(), StatusCode::OK);
......
......@@ -7,7 +7,7 @@ use iron_sessionstorage::traits::*;
use iron::modifiers::Redirect;
use iron::modifiers::RedirectRaw;
use iron::{status, AfterMiddleware};
use iron::{status, AfterMiddleware, BeforeMiddleware};
use mount::Mount;
use router::Router;
......@@ -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)]
struct SessionError {
message: String,
......@@ -283,7 +297,8 @@ fn debug_new_token<C>(req: &mut Request) -> IronResult<Response>
where C: MedalConnection + std::marker::Send + 'static {
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];
......@@ -294,7 +309,8 @@ fn debug_logout<C>(req: &mut Request) -> IronResult<Response>
where C: MedalConnection + std::marker::Send + 'static {
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];
......@@ -468,16 +484,14 @@ fn submission_post<C>(req: &mut Request) -> IronResult<Response>
let session_token = req.expect_session_token()?;
let (csrf_token, data, grade, subtask) = {
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("data"),(status::BadRequest, mime!(Text/Html), format!("400 Bad Request")))[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"))),
formdata.get("subtask").map(|x| x[0].to_owned()),
)
(iexpect!(formdata.get("csrf_token"))[0].to_owned(),
iexpect!(formdata.get("data"))[0].to_owned(),
iexpect!(formdata.get("grade").unwrap_or(&vec!["0".to_owned()])[0].parse::<i32>().ok()),
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);
println!("{}", data);
*/
#[cfg(feature = "debug")]
println!("New submission for task {} (graded {}): {}", task_id, grade, data);
let result =
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>
let (csrf_token, name, tag) = {
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("name"),(status::BadRequest, mime!(Text/Html), format!("400 Bad Request")))[0].to_owned(),
iexpect!(formdata.get("tag"),(status::BadRequest, mime!(Text/Html), format!("400 Bad Request")))[0].to_owned())
(iexpect!(formdata.get("csrf_token"))[0].to_owned(),
iexpect!(formdata.get("name"))[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)?;
......@@ -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>,
);
// 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 mut mount = Mount::new();
......@@ -888,8 +902,12 @@ pub fn start_server<C>(conn: C, config: Config) -> iron::error::HttpResult<iron:
let mut ch = Chain::new(mount);
#[cfg(feature = "debug")]
ch.link_before(RequestLogger::new());
ch.link(Write::<SharedDatabaseConnection<C>>::both(conn));
ch.link(Write::<SharedConfiguration>::both(config.clone()));
ch.link_around(CookieDistributor::new());
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