main.rs 13.4 KB
Newer Older
1
2
#![cfg_attr(feature = "strict", deny(warnings))]

Robert Czechowski's avatar
Robert Czechowski committed
3
4
5
6
7
8
9
#[macro_use]
extern crate iron;
#[macro_use]
extern crate router;
#[macro_use]
extern crate serde_derive;

Robert Czechowski's avatar
Robert Czechowski committed
10
extern crate handlebars_iron;
Robert Czechowski's avatar
Robert Czechowski committed
11
12
extern crate iron_sessionstorage;
extern crate mount;
13
extern crate params;
Robert Czechowski's avatar
Robert Czechowski committed
14
15
extern crate persistent;
extern crate rand;
16
extern crate reqwest;
Robert Czechowski's avatar
Robert Czechowski committed
17
18
extern crate rusqlite;
extern crate serde_json;
19
extern crate serde_yaml;
Robert Czechowski's avatar
Robert Czechowski committed
20
21
22
23
extern crate staticfile;
extern crate structopt;
extern crate time;
extern crate urlencoded;
24
25
26
27
28

use rusqlite::Connection;

mod db_apply_migrations;
mod db_conn;
Robert Czechowski's avatar
Robert Czechowski committed
29
mod db_conn_sqlite;
30
31
32
mod db_objects;

use db_conn::{MedalConnection, MedalObject};
Robert Czechowski's avatar
Robert Czechowski committed
33
use functions::SetPassword; // TODO: Refactor, so we don't need to take this from there!
34
35
36

use db_objects::*;

37
mod configreader_yaml;
Robert Czechowski's avatar
Robert Czechowski committed
38
mod webfw_iron;
Robert Czechowski's avatar
Robert Czechowski committed
39
40
41
42
43
44

use webfw_iron::start_server;

mod functions;

use std::fs;
Robert Czechowski's avatar
Robert Czechowski committed
45
use std::path;
Robert Czechowski's avatar
Robert Czechowski committed
46

Robert Czechowski's avatar
Robert Czechowski committed
47
use std::path::{Path, PathBuf};
48
49
use structopt::StructOpt;

50
51
52
mod oauth_provider;

#[derive(Serialize, Deserialize, Clone, Default, Debug)]
53
pub struct Config {
54
55
56
    host: Option<String>,
    port: Option<u16>,
    self_url: Option<String>,
57
    oauth_providers: Option<Vec<oauth_provider::OauthProvider>>,
58
    database_file: Option<PathBuf>,
59
60
}

61
fn read_config_from_file(file: &Path) -> Config {
62
    use std::io::Read;
Daniel Brüning's avatar
Daniel Brüning committed
63

64
    println!("Reading configuration file '{}'", file.to_str().unwrap_or("<Encoding error>"));
Daniel Brüning's avatar
Daniel Brüning committed
65

Robert Czechowski's avatar
Robert Czechowski committed
66
    let mut config: Config = if let Ok(mut file) = fs::File::open(file) {
67
68
69
70
        let mut contents = String::new();
        file.read_to_string(&mut contents).unwrap();
        serde_json::from_str(&contents).unwrap()
    } else {
71
        println!("Configuration file '{}' not found.", file.to_str().unwrap_or("<Encoding error>"));
72
        Default::default()
73
74
    };

75
76
77
78
79
80
81
    if let Some(ref oap) = config.oauth_providers {
        println!("OAuth providers:");
        for oap in oap {
            println!("  * {}", oap.provider_id);
        }
    }

Robert Czechowski's avatar
Robert Czechowski committed
82
83
84
85
86
87
88
89
90
    if config.host.is_none() {
        config.host = Some("[::]".to_string())
    }
    if config.port.is_none() {
        config.port = Some(8080)
    }
    if config.self_url.is_none() {
        config.self_url = Some("http://localhost:8080".to_string())
    }
91

92
    println!("OAuth providers will be told to redirect to {}", config.self_url.as_ref().unwrap());
93

94
    config
95
}
96

97
98
99
100
101
102
103
104
105
106
#[derive(StructOpt, Debug)]
#[structopt()]
struct Opt {
    /// Config file to use (default: 'config.json')
    #[structopt(short = "c", long = "config", default_value = "config.json", parse(from_os_str))]
    configfile: PathBuf,

    /// Database file to use (default: from config file or 'medal.db')
    #[structopt(short = "d", long = "database", parse(from_os_str))]
    databasefile: Option<PathBuf>,
107
108
109
110

    /// Port to listen on (default: from config file or 8080)
    #[structopt(short = "p", long = "port")]
    port: Option<u16>,
111
112
113
114

    /// Reset password of admin user (user_id=1)
    #[structopt(short = "a", long = "reset-admin-pw")]
    resetadminpw: bool,
115
116
}

Robert Czechowski's avatar
Robert Czechowski committed
117
fn read_contest(p: &path::PathBuf) -> Option<Contest> {
118
119
    use std::fs::File;
    use std::io::Read;
120

121
122
123
    let mut file = File::open(p).unwrap();
    let mut contents = String::new();
    file.read_to_string(&mut contents).unwrap();
124

Robert Czechowski's avatar
Robert Czechowski committed
125
126
127
    configreader_yaml::parse_yaml(&contents,
                                  p.file_name().to_owned()?.to_str()?,
                                  &format!("{}/", p.parent().unwrap().to_str()?))
Robert Czechowski's avatar
Robert Czechowski committed
128
129
130
131
}

fn get_all_contest_info(task_dir: &str) -> Vec<Contest> {
    fn walk_me_recursively(p: &path::PathBuf, contests: &mut Vec<Contest>) {
132
133
        if let Ok(paths) = fs::read_dir(p) {
            for path in paths {
Robert Czechowski's avatar
Robert Czechowski committed
134
135
                let p = path.unwrap().path();
                walk_me_recursively(&p, contests);
136
            }
Robert Czechowski's avatar
Robert Czechowski committed
137
        }
138

139
        if p.file_name().unwrap().to_string_lossy().to_string().ends_with(".yaml") {
140
            read_contest(p).map(|contest| contests.push(contest));
141
        };
Robert Czechowski's avatar
Robert Czechowski committed
142
143
144
145
146
    };

    let mut contests = Vec::new();
    match fs::read_dir(task_dir) {
        Err(why) => println!("Error opening tasks directory! {:?}", why.kind()),
Robert Czechowski's avatar
Robert Czechowski committed
147
148
149
150
151
        Ok(paths) => {
            for path in paths {
                walk_me_recursively(&path.unwrap().path(), &mut contests);
            }
        }
Robert Czechowski's avatar
Robert Czechowski committed
152
153
154
155
156
    };

    contests
}

Robert Czechowski's avatar
Robert Czechowski committed
157
fn refresh_all_contests(conn: &mut Connection) {
Robert Czechowski's avatar
Robert Czechowski committed
158
159
160
161
162
163
164
    let v = get_all_contest_info("tasks/");

    for mut contest_info in v {
        contest_info.save(conn);
    }
}

165
166
167
168
fn add_admin_user(conn: &mut Connection, resetpw: bool) {
    let mut admin = match conn.get_user_by_id(1) {
        None => {
            print!("New Database. Creating new admin user with credentials 'admin':");
169
            conn.new_session("")
Robert Czechowski's avatar
Robert Czechowski committed
170
        }
171
172
        Some(user) => {
            if !resetpw {
Robert Czechowski's avatar
Robert Czechowski committed
173
                return;
174
            }
175
176
177
178
179
            print!("Request to reset admin password. Set credentials 'admin':");
            user
        }
    };

Robert Czechowski's avatar
Robert Czechowski committed
180
    use rand::{distributions::Alphanumeric, thread_rng, Rng};
181
182

    let password: String = thread_rng().sample_iter(&Alphanumeric)
Robert Czechowski's avatar
Robert Czechowski committed
183
184
185
186
187
188
                                       .filter(|x| {
                                           let x = *x;
                                           !(x == 'l' || x == 'I' || x == '1' || x == 'O' || x == 'o' || x == '0')
                                       })
                                       .take(8)
                                       .collect();
189
190
191
192
    print!("'{}' …", &password);

    admin.username = Some("admin".into());
    match admin.set_password(&password) {
193
        None => println!(" FAILED! (Password hashing error)"),
194
195
        _ => {
            conn.save_session(admin);
196
            println!(" Done");
197
        }
198
199
200
    }
}

Robert Czechowski's avatar
Robert Czechowski committed
201
fn main() {
202
    let opt = Opt::from_args();
203
    //println!("{:?}", opt); // Show in different debug level?
Daniel Brüning's avatar
Daniel Brüning committed
204

205
206
    let mut config = read_config_from_file(&opt.configfile);

Robert Czechowski's avatar
Robert Czechowski committed
207
208
209
210
211
212
    if opt.databasefile.is_some() {
        config.database_file = opt.databasefile;
    }
    if opt.port.is_some() {
        config.port = opt.port;
    }
213

214
    let mut conn = match config.database_file {
Robert Czechowski's avatar
Robert Czechowski committed
215
216
217
218
219
220
221
222
        Some(ref path) => {
            println!("Using database file {}", &path.to_str().unwrap_or("<unprintable filename>"));
            Connection::create(path)
        }
        None => {
            println!("Using default database file ./medal.db");
            Connection::create(&Path::new("medal.db"))
        }
223
    };
224
    println!("connected!");
225

226
    println!("applying migrations …");
Robert Czechowski's avatar
Robert Czechowski committed
227
228
    db_apply_migrations::test(&mut conn);

229
    println!("scanning for contests …");
Robert Czechowski's avatar
Robert Czechowski committed
230
    refresh_all_contests(&mut conn);
231

232
233
    add_admin_user(&mut conn, opt.resetadminpw);

234
    match start_server(conn, config) {
235
        Ok(_) => println!("Server started"),
Robert Czechowski's avatar
Robert Czechowski committed
236
        Err(_) => println!("Error on server start …"),
237
    };
Robert Czechowski's avatar
Robert Czechowski committed
238

239
    println!("Could not run server. Is the port already in use?");
240
}
241
242
243
244

#[cfg(test)]
mod tests {
    use super::*;
245
    use std::io::Read;
246

Robert Czechowski's avatar
Robert Czechowski committed
247
248
    fn start_server_and_fn<F>(port: u16, set_user: Option<(String, String)>, f: F)
        where F: FnOnce() {
249
        use std::sync::mpsc::channel;
Robert Czechowski's avatar
Robert Czechowski committed
250
        use std::{thread, time};
251
252
253
254
255
256
257
        let (start_tx, start_rx) = channel();
        let (stop_tx, stop_rx) = channel();

        thread::spawn(move || {
            let mut conn = Connection::open_in_memory().unwrap();
            db_apply_migrations::test(&mut conn);

258
            if let Some(user) = set_user {
259
                let mut test_user = conn.new_session("");
260
                test_user.username = Some(user.0);
261
262
263
                match test_user.set_password(&user.1) {
                    None => panic!("Set Password did not work correctly.)"),
                    _ => conn.save_session(test_user),
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
                }
            }

            let mut config = read_config_from_file(Path::new("thisfileshoudnotexist"));
            config.port = Some(port);
            let srvr = start_server(conn, config);

            start_tx.send(()).unwrap();

            stop_rx.recv().unwrap();

            srvr.unwrap().close().unwrap();
        });

        // wait for server to start:
        start_rx.recv().unwrap();
        thread::sleep(time::Duration::from_millis(100));
        f();
        stop_tx.send(()).unwrap();
    }

285
    fn login_for_tests(port: u16, client: &reqwest::Client, username: &str, password: &str) -> reqwest::Response {
286
        let params = [("username", username), ("password", password)];
Robert Czechowski's avatar
Robert Czechowski committed
287
        let resp = client.post(&format!("http://localhost:{}/login", port)).form(&params).send().unwrap();
288
        resp
289
290
    }

291
292
293
294
295
296
297
    fn check_status(resp: &reqwest::Response, expected_status: reqwest::StatusCode) {
        let status = resp.status();
        if status != &expected_status {
            panic!("Status is not (as expexted) {}. Status: {}", expected_status, status)
        };
    }

298
299
    #[test]
    fn start_server_and_check_request() {
Robert Czechowski's avatar
Robert Czechowski committed
300
        start_server_and_fn(8080, None, || {
301
            let mut resp = reqwest::get("http://localhost:8080").unwrap();
302
            check_status(&resp, reqwest::StatusCode::Ok);
303
            let mut content = String::new();
304
            resp.read_to_string(&mut content).unwrap();
305
            assert!(content.contains("Jugendwettbewerb Informatik</h1>"));
306
307
308
            assert!(!content.contains("Error"));

            let mut resp = reqwest::get("http://localhost:8080/contest").unwrap();
309
            check_status(&resp, reqwest::StatusCode::Ok);
310
            let mut content = String::new();
311
            resp.read_to_string(&mut content).unwrap();
312
313
314
315
            assert!(content.contains("<h1>Wettbewerbe</h1>"));
            assert!(!content.contains("Error"));
        })
    }
Daniel Brüning's avatar
Daniel Brüning committed
316

317
318
    #[test]
    fn check_login_wrong_credentials() {
Robert Czechowski's avatar
Robert Czechowski committed
319
        start_server_and_fn(8081, None, || {
320
            let client = reqwest::Client::new().unwrap();
321
322
            let mut resp = login_for_tests(8081, &client, "nonexistingusername", "wrongpassword");
            check_status(&resp, reqwest::StatusCode::Ok);
323
            let mut content = String::new();
324
            resp.read_to_string(&mut content).unwrap();
325
326
            assert!(content.contains("<h1>Login</h1>"));
            assert!(content.contains("Login fehlgeschlagen."));
327
            assert!(!content.contains("Error"));
328
        })
329
    }
330
331
332

    #[test]
    fn start_server_and_check_login() {
Robert Czechowski's avatar
Robert Czechowski committed
333
        start_server_and_fn(8082, Some(("testusr".to_string(), "testpw".to_string())), || {
334
            let mut client = reqwest::Client::new().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
335
            client.redirect(reqwest::RedirectPolicy::custom(|attempt| attempt.stop()));
336
337
338
            let mut resp = login_for_tests(8082, &client, "testusr", "testpw");
            check_status(&resp, reqwest::StatusCode::Found);

339
            let mut content = String::new();
340
            resp.read_to_string(&mut content).unwrap();
341
342
343
            assert!(!content.contains("Error"));

            let header = resp.headers();
344
345
            let set_cookie = header.get::<reqwest::header::SetCookie>();
            match set_cookie {
346
                None => panic!("No setCookie."),
Robert Czechowski's avatar
Robert Czechowski committed
347
348
                Some(cookie) => {
                    if cookie.len() == 1 {
349
                        let new_cookie = reqwest::header::Cookie(cookie.to_vec());
Robert Czechowski's avatar
Robert Czechowski committed
350
                        let mut new_resp = client.get("http://localhost:8082").header(new_cookie).send().unwrap();
351
352
353
354
355
356
                        check_status(&new_resp, reqwest::StatusCode::Ok);

                        let mut new_content = String::new();
                        new_resp.read_to_string(&mut new_content).unwrap();
                        assert!(!content.contains("Error"));
                        assert!(new_content.contains("Eingeloggt als <em>testusr</em>"));
357
                        assert!(new_content.contains("Jugendwettbewerb Informatik</h1>"));
358
359
                    } else {
                        panic!("More than one setCookie.");
Robert Czechowski's avatar
Robert Czechowski committed
360
361
                    }
                }
362
363
364
365
            };
        })
    }

366
367
    #[test]
    fn start_server_and_check_logout() {
Robert Czechowski's avatar
Robert Czechowski committed
368
        start_server_and_fn(8083, Some(("testusr".to_string(), "testpw".to_string())), || {
369
            let mut client = reqwest::Client::new().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
370
            client.redirect(reqwest::RedirectPolicy::custom(|attempt| attempt.stop()));
371
            let resp = login_for_tests(8083, &client, "testusr", "testpw");
372
            check_status(&resp, reqwest::StatusCode::Found);
373
374

            let header = resp.headers();
375
376
            let set_cookie = header.get::<reqwest::header::SetCookie>();
            match set_cookie {
377
                None => panic!("No setCookie."),
Robert Czechowski's avatar
Robert Czechowski committed
378
379
380
381
382
383
384
385
386
387
388
                Some(cookie) => {
                    if cookie.len() == 1 {
                        let new_cookie = reqwest::header::Cookie(cookie.to_vec());
                        let mut new_resp =
                            client.get("http://localhost:8082/logout").header(new_cookie.clone()).send().unwrap();
                        check_status(&new_resp, reqwest::StatusCode::Found);
                        new_resp = client.get("http://localhost:8082").header(new_cookie).send().unwrap();
                        check_status(&new_resp, reqwest::StatusCode::Ok);

                        let mut new_content = String::new();
                        new_resp.read_to_string(&mut new_content).unwrap();
389
390
391
392
                        assert!(new_content.contains("Benutzername"));
                        assert!(new_content.contains("Passwort"));
                        assert!(new_content.contains("Gruppencode / Teilnahmecode"));
                        assert!(new_content.contains("Jugendwettbewerb Informatik</h1>"));
393
394
                    } else {
                        panic!("More than one setCookie.");
Robert Czechowski's avatar
Robert Czechowski committed
395
396
                    }
                }
397
398
399
400
            };
        })
    }

401
}