main.rs 46.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*  medal                                                                                                            *\
 *  Copyright (C) 2020  Bundesweite Informatikwettbewerbe                                                            *
 *                                                                                                                   *
 *  This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero        *
 *  General Public License as published  by the Free Software Foundation, either version 3 of the License, or (at    *
 *  your option) any later version.                                                                                  *
 *                                                                                                                   *
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the       *
 *  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public      *
 *  License for more details.                                                                                        *
 *                                                                                                                   *
 *  You should have received a copy of the GNU Affero General Public License along with this program.  If not, see   *
\*  <http://www.gnu.org/licenses/>.                                                                                  */

15
16
#![cfg_attr(feature = "strict", deny(warnings))]

Robert Czechowski's avatar
Robert Czechowski committed
17
18
19
20
21
22
23
#[macro_use]
extern crate iron;
#[macro_use]
extern crate router;
#[macro_use]
extern crate serde_derive;

24
extern crate csv;
Robert Czechowski's avatar
Robert Czechowski committed
25
extern crate handlebars_iron;
Robert Czechowski's avatar
Robert Czechowski committed
26
27
extern crate iron_sessionstorage;
extern crate mount;
28
extern crate params;
Robert Czechowski's avatar
Robert Czechowski committed
29
30
extern crate persistent;
extern crate rand;
31
extern crate reqwest;
Robert Czechowski's avatar
Robert Czechowski committed
32
extern crate serde_json;
33
extern crate serde_yaml;
34
extern crate sha2;
Robert Czechowski's avatar
Robert Czechowski committed
35
36
37
38
extern crate staticfile;
extern crate structopt;
extern crate time;
extern crate urlencoded;
39
40
41

#[cfg(feature = "postgres")]
extern crate postgres;
42
#[cfg(feature = "rusqlite")]
43
extern crate rusqlite;
44
#[cfg(feature = "webbrowser")]
45
extern crate webbrowser;
46

47
48
pub mod config;
pub mod contestreader_yaml;
49
pub mod core;
50
pub mod db_conn;
51
pub mod helpers;
52
53
54
pub mod oauth_provider;

mod db_apply_migrations;
55
mod db_conn_postgres;
56
mod db_conn_sqlite_new;
57
mod db_objects;
58
59
mod webfw_iron;

60
use db_conn::{MedalConnection, MedalObject};
61
use db_objects::*;
62
use helpers::SetPassword;
Robert Czechowski's avatar
Robert Czechowski committed
63
64
use webfw_iron::start_server;

65
use config::Config;
66
67
use structopt::StructOpt;

Robert Czechowski's avatar
Robert Czechowski committed
68
use std::path::Path;
69

Robert Czechowski's avatar
Robert Czechowski committed
70
fn read_contest(p: &Path) -> Option<Contest> {
71
72
    use std::fs::File;
    use std::io::Read;
73

74
75
76
    let mut file = File::open(p).unwrap();
    let mut contents = String::new();
    file.read_to_string(&mut contents).unwrap();
77

78
    contestreader_yaml::parse_yaml(&contents,
79
80
                                   p.file_name().to_owned()?.to_str()?,
                                   &format!("{}/", p.parent().unwrap().to_str()?))
Robert Czechowski's avatar
Robert Czechowski committed
81
82
83
}

fn get_all_contest_info(task_dir: &str) -> Vec<Contest> {
Robert Czechowski's avatar
Robert Czechowski committed
84
    fn walk_me_recursively(p: &Path, contests: &mut Vec<Contest>) {
85
        if let Ok(paths) = std::fs::read_dir(p) {
86
            for path in paths {
Robert Czechowski's avatar
Robert Czechowski committed
87
88
                let p = path.unwrap().path();
                walk_me_recursively(&p, contests);
89
            }
Robert Czechowski's avatar
Robert Czechowski committed
90
        }
91

92
        if p.file_name().unwrap().to_string_lossy().to_string().ends_with(".yaml") {
93
            read_contest(p).map(|contest| contests.push(contest));
94
        };
Robert Czechowski's avatar
Robert Czechowski committed
95
    }
Robert Czechowski's avatar
Robert Czechowski committed
96
97

    let mut contests = Vec::new();
98
    match std::fs::read_dir(task_dir) {
Robert Czechowski's avatar
Robert Czechowski committed
99
        Err(why) => println!("Error opening tasks directory! {:?}", why.kind()),
Robert Czechowski's avatar
Robert Czechowski committed
100
101
102
103
104
        Ok(paths) => {
            for path in paths {
                walk_me_recursively(&path.unwrap().path(), &mut contests);
            }
        }
Robert Czechowski's avatar
Robert Czechowski committed
105
106
107
108
109
    };

    contests
}

110
111
112
113
fn refresh_all_contests<C>(conn: &mut C)
    where C: MedalConnection,
          db_objects::Contest: db_conn::MedalObject<C>
{
114
    conn.reset_all_contest_visibilities();
115
116
    conn.reset_all_taskgroup_visibilities();

Robert Czechowski's avatar
Robert Czechowski committed
117
118
119
120
121
122
123
    let v = get_all_contest_info("tasks/");

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

124
125
fn add_admin_user<C>(conn: &mut C, resetpw: bool)
    where C: MedalConnection {
126
127
128
    let mut admin = match conn.get_user_by_id(1) {
        None => {
            print!("New Database. Creating new admin user with credentials 'admin':");
129
            conn.new_session("")
Robert Czechowski's avatar
Robert Czechowski committed
130
        }
131
132
        Some(user) => {
            if !resetpw {
Robert Czechowski's avatar
Robert Czechowski committed
133
                return;
134
            }
135
136
137
138
139
            print!("Request to reset admin password. Set credentials 'admin':");
            user
        }
    };

140
    let password = helpers::make_unambiguous_code(8);
141
142
    print!("'{}', ", &password);

143
    let logincode = helpers::make_unambiguous_code_prefix(8, "a");
144
    print!(" logincode:'{}' …", &logincode);
145
146

    admin.username = Some("admin".into());
147
    admin.logincode = Some(logincode);
148
    match admin.set_password(&password) {
149
        None => println!(" FAILED! (Password hashing error)"),
150
151
        _ => {
            conn.save_session(admin);
152
            println!(" Done");
153
        }
154
155
156
    }
}

157
158
159
160
161
162
163
fn prepare_and_start_server<C>(mut conn: C, config: Config, onlycontestscan: bool, resetadminpw: bool)
    where C: MedalConnection + std::marker::Send + 'static,
          db_objects::Contest: db_conn::MedalObject<C>
{
    db_apply_migrations::test(&mut conn);

    if onlycontestscan || config.no_contest_scan == Some(false) {
164
        print!("Scanning for contests …");
165
        refresh_all_contests(&mut conn);
166
        println!(" Done")
167
168
169
170
171
    }

    if !onlycontestscan {
        add_admin_user(&mut conn, resetadminpw);

172
        #[cfg(feature = "webbrowser")]
173
        let self_url = config.self_url.clone();
174
        #[cfg(feature = "webbrowser")]
175
176
        let open_browser = config.open_browser;

177
        match start_server(conn, config) {
178
179
            Ok(_) => {
                println!("Server started");
180

181
182
183
184
185
                #[cfg(feature = "webbrowser")]
                {
                    if let (Some(self_url), Some(true)) = (self_url, open_browser) {
                        open_browser_window(&self_url);
                    }
186
                }
187
            }
188
189
            Err(_) => println!("Error on server start …"),
        };
190

191
192
193
194
        println!("Could not run server. Is the port already in use?");
    }
}

195
#[cfg(feature = "webbrowser")]
196
197
198
fn open_browser_window(self_url: &str) {
    match webbrowser::open(&self_url) {
        Ok(_) => (),
199
        Err(e) => println!("Error while opening webbrowser: {:?}", e),
200
201
202
    }
}

Robert Czechowski's avatar
Robert Czechowski committed
203
fn main() {
204
    let opt = config::Opt::from_args();
205
206
207

    #[cfg(feature = "debug")]
    println!("Options: {:#?}", opt);
Daniel Brüning's avatar
Daniel Brüning committed
208

209
    let mut config = config::read_config_from_file(&opt.configfile);
210

211
212
213
214
215
216
217
218
219
    #[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 };
220
    config.disable_results_page = if opt.disableresultspage { Some(true) } else { config.disable_results_page };
221
    config.enable_password_login = if opt.enablepasswordlogin { Some(true) } else { config.enable_password_login };
222
223
224
225
226
227

    // 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);
228

229
230
231
    #[cfg(feature = "postgres")]
    {
        if let Some(url) = config.database_url.clone() {
232
            #[cfg(feature = "debug")]
233
            print!("Using database {} … ", &url);
234
235
            #[cfg(not(feature = "debug"))]
            {
236
237
238
239
                let (begin_middle, end) = url.split_at(url.find('@').unwrap_or(0));
                let (begin, _middle) = begin_middle.split_at(begin_middle.rfind(':').unwrap_or(0));
                print!("Using database {}:***{} … ", begin, end);
            }
240
241
242
243
244
245
            let conn = postgres::Connection::connect(url, postgres::TlsMode::None).unwrap();
            println!("Connected");

            prepare_and_start_server(conn, config, opt.onlycontestscan, opt.resetadminpw);
            return;
        }
246
    }
247
248
249
250
251
252
253
254
255
256
257
258
259
260

    #[cfg(feature = "rusqlite")]
    {
        if let Some(path) = config.database_file.clone() {
            print!("Using database file {} … ", &path.to_str().unwrap_or("<unprintable filename>"));
            let conn = rusqlite::Connection::open(path).unwrap();
            println!("Connected");

            prepare_and_start_server(conn, config, opt.onlycontestscan, opt.resetadminpw);
            return;
        }
    }

    println!("No database configured. Try enableing the 'rusqlite' feature during compilation.\nLeaving now.");
261
}
262
263
264
265

#[cfg(test)]
mod tests {
    use super::*;
Robert Czechowski's avatar
Robert Czechowski committed
266
    use reqwest::StatusCode;
267

268
269
270
271
272
273
274
275
276
277
278
    fn addsimpleuser(conn: &mut rusqlite::Connection, username: String, password: String, is_t:bool, is_a:bool) {
        let mut test_user = conn.new_session("");
        test_user.username = Some(username);
        test_user.is_teacher = is_t;
        test_user.is_admin = Some(is_a);
        test_user.set_password(&password).expect("Set Password did not work correctly.");
        conn.save_session(test_user);
    }

    fn start_server_and_fn<P, F>(port: u16, p: P, f: F)
        where F: Fn(), P: Fn(&mut rusqlite::Connection) + std::marker::Send + 'static {
279
        use std::sync::mpsc::channel;
Robert Czechowski's avatar
Robert Czechowski committed
280
        use std::{thread, time};
281
282
283
284
        let (start_tx, start_rx) = channel();
        let (stop_tx, stop_rx) = channel();

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

288
            p(&mut conn);
289

290
            // ID: 1, gets renamed
Robert Czechowski's avatar
Robert Czechowski committed
291
292
293
294
295
296
            let mut contest = Contest::new("directory".to_string(),
                                           "public.yaml".to_string(),
                                           "RenamedContestName".to_string(),
                                           1,
                                           true,
                                           None,
297
298
                                           None,
                                           None,
299
                                           None,
300
301
                                           None,
                                           None,
302
                                           None,
303
                                           None,
Robert Czechowski's avatar
Robert Czechowski committed
304
305
306
                                           None);
            contest.save(&conn);

307
            // ID: 1
Robert Czechowski's avatar
Robert Czechowski committed
308
309
310
311
312
313
            let mut contest = Contest::new("directory".to_string(),
                                           "public.yaml".to_string(),
                                           "PublicContestName".to_string(),
                                           1,
                                           true,
                                           None,
314
315
                                           None,
                                           None,
316
                                           None,
317
318
                                           None,
                                           None,
319
                                           None,
320
                                           None,
Robert Czechowski's avatar
Robert Czechowski committed
321
                                           None);
322
            let mut taskgroup = Taskgroup::new("TaskgroupName".to_string(), None);
323
            let task = Task::new("taskdir1".to_string(), 3); // ID: 1
Robert Czechowski's avatar
Robert Czechowski committed
324
            taskgroup.tasks.push(task);
325
            let task = Task::new("taskdir2".to_string(), 4); // ID: 2
Robert Czechowski's avatar
Robert Czechowski committed
326
327
328
329
            taskgroup.tasks.push(task);
            contest.taskgroups.push(taskgroup);
            contest.save(&conn);

330
            // ID: 2
Robert Czechowski's avatar
Robert Czechowski committed
331
332
333
334
335
336
            let mut contest = Contest::new("directory".to_string(),
                                           "private.yaml".to_string(),
                                           "PrivateContestName".to_string(),
                                           1,
                                           false,
                                           None,
337
338
                                           None,
                                           None,
339
                                           None,
340
341
                                           None,
                                           None,
342
                                           None,
343
                                           None,
Robert Czechowski's avatar
Robert Czechowski committed
344
                                           None);
345
            let mut taskgroup = Taskgroup::new("TaskgroupName".to_string(), None);
346
            let task = Task::new("taskdir1".to_string(), 3); // ID: 3
Robert Czechowski's avatar
Robert Czechowski committed
347
            taskgroup.tasks.push(task);
348
            let task = Task::new("taskdir2".to_string(), 4); // ID: 4
Robert Czechowski's avatar
Robert Czechowski committed
349
350
351
352
            taskgroup.tasks.push(task);
            contest.taskgroups.push(taskgroup);
            contest.save(&conn);

353
            // ID: 3
Robert Czechowski's avatar
Robert Czechowski committed
354
355
356
357
358
359
            let mut contest = Contest::new("directory".to_string(),
                                           "infinte.yaml".to_string(),
                                           "InfiniteContestName".to_string(),
                                           0,
                                           true,
                                           None,
360
                                           None,
361
362
                                           None,
                                           None,
363
                                           None,
364
                                           None,
365
366
                                           None,
                                           None,
Robert Czechowski's avatar
Robert Czechowski committed
367
                                           None);
368
369
370
371
372
373
374
375
376
            let mut taskgroup = Taskgroup::new("TaskgroupRenameName".to_string(), None);
            let task = Task::new("taskdir1".to_string(), 3); // ID: 5
            taskgroup.tasks.push(task);
            let task = Task::new("taskdir2".to_string(), 4); // ID: 6
            taskgroup.tasks.push(task);
            contest.taskgroups.push(taskgroup);
            contest.save(&conn);

            let mut taskgroup = Taskgroup::new("TaskgroupNewName".to_string(), None);
377
            let task = Task::new("taskdir1".to_string(), 3); // ID: 5
Robert Czechowski's avatar
Robert Czechowski committed
378
            taskgroup.tasks.push(task);
379
            let task = Task::new("taskdir2".to_string(), 4); // ID: 6
Robert Czechowski's avatar
Robert Czechowski committed
380
381
382
383
            taskgroup.tasks.push(task);
            contest.taskgroups.push(taskgroup);
            contest.save(&conn);

384
            let mut config = config::read_config_from_file(Path::new("thisfileshoudnotexist"));
385
            config.port = Some(port);
386
            config.cookie_signing_secret = Some("testtesttesttesttesttesttesttest".to_string());
Robert Czechowski's avatar
Robert Czechowski committed
387
388
            let message = format!("Could not start server on port {}", port);
            let mut srvr = start_server(conn, config).expect(&message);
389

390
            // Message server started
391
392
            start_tx.send(()).unwrap();

393
            // Wait for test to finish
394
395
            stop_rx.recv().unwrap();

396
            srvr.close().unwrap();
397
398
        });

399
        // Wait for server to start
400
401
        start_rx.recv().unwrap();
        thread::sleep(time::Duration::from_millis(100));
402
403

        // Run test code
404
        f();
405

406
        // Message test finished
407
408
409
        stop_tx.send(()).unwrap();
    }

410
    fn login(port: u16, client: &reqwest::Client, username: &str, password: &str) -> reqwest::Response {
411
        let params = [("username", username), ("password", password)];
Robert Czechowski's avatar
Robert Czechowski committed
412
        client.post(&format!("http://localhost:{}/login", port)).form(&params).send().unwrap()
413
    }
Robert Czechowski's avatar
Robert Czechowski committed
414

415
416
    fn login_code(port: u16, client: &reqwest::Client, code: &str) -> reqwest::Response {
        let params = [("code", code)];
Robert Czechowski's avatar
Robert Czechowski committed
417
        client.post(&format!("http://localhost:{}/clogin", port)).form(&params).send().unwrap()
418
    }
419

420
    #[test]
Robert Czechowski's avatar
Robert Czechowski committed
421
    fn start_server_and_check_requests() {
422
        start_server_and_fn(8080, |_|{}, || {
423
            let mut resp = reqwest::get("http://localhost:8080").unwrap();
424
            assert_eq!(resp.status(), StatusCode::OK);
425
426

            let content = resp.text().unwrap();
427
            assert!(content.contains("Jugendwettbewerb Informatik</h1>"));
428
            assert!(!content.contains("Error"));
Robert Czechowski's avatar
Robert Czechowski committed
429
            assert!(!content.contains("Gruppenverwaltung"));
430
431

            let mut resp = reqwest::get("http://localhost:8080/contest").unwrap();
432
            assert_eq!(resp.status(), StatusCode::OK);
433
434

            let content = resp.text().unwrap();
435
436
            assert!(content.contains("<h1>Wettbewerbe</h1>"));
            assert!(!content.contains("Error"));
Robert Czechowski's avatar
Robert Czechowski committed
437
438

            let mut resp = reqwest::get("http://localhost:8080/group").unwrap();
439
            let content = resp.text().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
440
            assert!(content.contains("<h1>Login</h1>"));
441
442
        })
    }
Daniel Brüning's avatar
Daniel Brüning committed
443

444
445
    #[test]
    fn check_login_wrong_credentials() {
446
        start_server_and_fn(8081, |_|{}, || {
447
            let client = reqwest::Client::new();
Robert Czechowski's avatar
Robert Czechowski committed
448

449
            let mut resp = login(8081, &client, "nonexistingusername", "wrongpassword");
450
            assert_eq!(resp.status(), StatusCode::OK);
451
452

            let content = resp.text().unwrap();
453
454
            assert!(content.contains("<h1>Login</h1>"));
            assert!(content.contains("Login fehlgeschlagen."));
455
            assert!(!content.contains("Error"));
Robert Czechowski's avatar
Robert Czechowski committed
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471

            let mut resp = login_code(8081, &client, "g23AgaV");
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("<h1>Login</h1>"));
            assert!(content.contains("Kein gültiger Code."));
            assert!(!content.contains("Error"));

            let mut resp = login_code(8081, &client, "u9XuAbH7p");
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("<h1>Login</h1>"));
            assert!(content.contains("Kein gültiger Code."));
            assert!(!content.contains("Error"));
472
        })
473
    }
474
475

    #[test]
Robert Czechowski's avatar
Robert Czechowski committed
476
    fn check_login() {
477
478
479
        start_server_and_fn(8082, |conn| {
            addsimpleuser(conn, "testusr".to_string(), "testpw".to_string(), false, false);
        }, || {
480
481
482
483
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
484

485
            let mut resp = login(8082, &client, "testusr", "testpw");
486
            assert_eq!(resp.status(), StatusCode::FOUND);
487

488
            let content = resp.text().unwrap();
489
490
            assert!(!content.contains("Error"));

491
492
493
494
            let mut set_cookie = resp.headers().get_all("Set-Cookie").iter();
            assert!(set_cookie.next().is_some());
            assert!(set_cookie.next().is_none());

Robert Czechowski's avatar
Robert Czechowski committed
495
496
497
498
            let location = resp.headers().get(reqwest::header::LOCATION).unwrap().to_str().unwrap();
            assert_eq!(location, "http://localhost:8082/");

            let mut resp = client.get(location).send().unwrap();
499
500
            assert_eq!(resp.status(), StatusCode::OK);

501
            let content = resp.text().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
502
503
504
505
            assert!(!content.contains("Error"));
            assert!(!content.contains("Gruppenverwaltung"));
            assert!(content.contains("Eingeloggt als <em>testusr</em>"));
            assert!(content.contains("Jugendwettbewerb Informatik</h1>"));
506
507
508
        })
    }

509
    #[test]
Robert Czechowski's avatar
Robert Czechowski committed
510
    fn check_logout() {
511
512
513
        start_server_and_fn(8083, |conn| {
            addsimpleuser(conn, "testusr".to_string(), "testpw".to_string(), false, false);
        }, || {
514
515
516
517
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
518

519
            let resp = login(8083, &client, "testusr", "testpw");
520
521
522
523
524
525
526
            assert_eq!(resp.status(), StatusCode::FOUND);

            let resp = client.get("http://localhost:8083/logout").send().unwrap();
            assert_eq!(resp.status(), StatusCode::FOUND);

            let mut resp = client.get("http://localhost:8083").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);
527
528

            let content = resp.text().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
529
530
531
532
            assert!(content.contains("Benutzername"));
            assert!(content.contains("Passwort"));
            assert!(content.contains("Gruppencode / Teilnahmecode"));
            assert!(content.contains("Jugendwettbewerb Informatik</h1>"));
533
534
535
        })
    }

536
537
    #[test]
    fn check_group_creation_and_group_code_login() {
538
539
540
        start_server_and_fn(8084, |conn| {
            addsimpleuser(conn, "testusr".to_string(), "testpw".to_string(), true, false);
        }, || {
541
542
543
544
545
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

546
            let resp = login(8084, &client, "testusr", "testpw");
547
            assert_eq!(resp.status(), StatusCode::FOUND);
548

549
550
            let mut resp = client.get("http://localhost:8084").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);
551
552

            let content = resp.text().unwrap();
553
554
            assert!(content.contains("[Lehrer]"));
            assert!(content.contains("Gruppenverwaltung"));
555
556
557

            let mut resp = client.get("http://localhost:8084/group/").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);
558
559

            let content = resp.text().unwrap();
560
561
            assert!(content.contains("Gruppe anlegen"));

562
            let params = [("name", "WrongGroupname"), ("tag", "WrongMarker"), ("csrf_token", "76CfTPJaoz")];
563
564
            let resp = client.post("http://localhost:8084/group/").form(&params).send().unwrap();
            assert_eq!(resp.status(), StatusCode::FORBIDDEN);
565

566
567
568
            let pos = content.find("type=\"hidden\" name=\"csrf_token\" value=\"").expect("CSRF-Token not found");
            let csrf = &content[pos + 39..pos + 49];
            let params = [("name", "Groupname"), ("tag", "Marker"), ("csrf_token", csrf)];
569
570
            let resp = client.post("http://localhost:8084/group/").form(&params).send().unwrap();
            assert_eq!(resp.status(), StatusCode::FOUND);
571
572
573
574

            let mut resp = client.get("http://localhost:8084/group/").send().unwrap();
            let content = resp.text().unwrap();
            assert!(!content.contains("WrongGroupname"));
Robert Czechowski's avatar
Robert Czechowski committed
575

576
577
578
579
580
            let pos = content.find("<td><a href=\"/group/1\">Groupname</a></td>").expect("Group not found");
            let groupcode = &content[pos + 58..pos + 65];

            // New client to test group code login
            let client = reqwest::Client::builder().cookie_store(true)
Robert Czechowski's avatar
Robert Czechowski committed
581
582
583
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();
584
585
586
587

            let resp = login_code(8084, &client, groupcode);
            assert_eq!(resp.status(), StatusCode::FOUND);

Robert Czechowski's avatar
Robert Czechowski committed
588
589
590
591
592
            let mut set_cookie = resp.headers().get_all("Set-Cookie").iter();
            assert!(set_cookie.next().is_some());
            assert!(set_cookie.next().is_none());

            let location = resp.headers().get(reqwest::header::LOCATION).unwrap().to_str().unwrap();
593
            assert_eq!(location, "http://localhost:8084/profile?status=firstlogin");
Robert Czechowski's avatar
Robert Czechowski committed
594
595

            let mut resp = client.get(location).send().unwrap();
596
597
598
599
600
601
602
            let content = resp.text().unwrap();

            let pos = content.find("<p>Login-Code: ").expect("Logincode not found");
            let logincode = &content[pos + 15..pos + 24];

            // New client to test login code login
            let client = reqwest::Client::builder().cookie_store(true)
Robert Czechowski's avatar
Robert Czechowski committed
603
604
605
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();
606
607
608
609

            let resp = login_code(8084, &client, logincode);
            assert_eq!(resp.status(), StatusCode::FOUND);

Robert Czechowski's avatar
Robert Czechowski committed
610
611
612
613
            let location = resp.headers().get(reqwest::header::LOCATION).unwrap().to_str().unwrap();
            assert_eq!(location, "http://localhost:8084/");

            let mut resp = client.get(location).send().unwrap();
614
615
            let content = resp.text().unwrap();
            assert!(content.contains("Eingeloggt als <em></em>"));
616
617
        })
    }
Robert Czechowski's avatar
Robert Czechowski committed
618
619
620

    #[test]
    fn check_contest_start() {
621
622
623
        start_server_and_fn(8085, |conn| {
            addsimpleuser(conn, "testusr".to_string(), "testpw".to_string(), false, false);
        }, || {
Robert Czechowski's avatar
Robert Czechowski committed
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

            let resp = login(8085, &client, "testusr", "testpw");
            assert_eq!(resp.status(), StatusCode::FOUND);

            let mut resp = client.get("http://localhost:8085/contest/").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("PublicContestName"));
            assert!(content.contains("InfiniteContestName"));
            //assert!(content.contains("PrivateContestName"));
            assert!(!content.contains("WrongContestName"));
            assert!(!content.contains("RenamedContestName"));
            assert!(content.contains("<a href=\"/contest/1\">PublicContestName</a>"));

            let mut resp = client.get("http://localhost:8085/contest/1").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("PublicContestName"));
            assert!(!content.contains("InfiniteContestName"));
            assert!(!content.contains("PrivateContestName"));
            assert!(!content.contains("WrongContestName"));
            assert!(!content.contains("RenamedContestName"));

653
            let params = [("csrf_token", "76CfTPJaoz")];
Robert Czechowski's avatar
Robert Czechowski committed
654
655
656
            let resp = client.post("http://localhost:8085/contest/1").form(&params).send().unwrap();
            assert_eq!(resp.status(), StatusCode::FORBIDDEN);

657
658
659
            let pos = content.find("type=\"hidden\" name=\"csrf_token\" value=\"").expect("CSRF-Token not found");
            let csrf = &content[pos + 39..pos + 49];
            let params = [("csrf_token", csrf)];
Robert Czechowski's avatar
Robert Czechowski committed
660
661
            let resp = client.post("http://localhost:8085/contest/1").form(&params).send().unwrap();
            assert_eq!(resp.status(), StatusCode::FOUND);
Robert Czechowski's avatar
Robert Czechowski committed
662
663
664
665
666
667
668

            let mut resp = client.get("http://localhost:8085/contest/1").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("<a href=\"/task/1\">☆☆☆</a></li>"));
            assert!(content.contains("<a href=\"/task/2\">☆☆☆☆</a></li>"));
669
670
671
672
673
        })
    }

    #[test]
    fn check_task_load_save() {
674
        start_server_and_fn(8086, |_|{}, || {
675
676
677
678
679
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

680
            let resp = client.get("http://localhost:8086/contest/3").send().unwrap();
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
            assert_eq!(resp.status(), StatusCode::OK);

            let mut resp = client.get("http://localhost:8086/task/5").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            let pos = content.find("#taskid=5&csrftoken=").expect("CSRF-Token not found");
            let csrf = &content[pos + 20..pos + 30];

            let mut resp = client.get("http://localhost:8086/load/5").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert_eq!(content, "{}");

            let params = [("data", "WrongData"), ("grade", "1"), ("csrf_token", "FNQU4QsEMY")];
            let resp = client.post("http://localhost:8086/save/5").form(&params).send().unwrap();
            assert_eq!(resp.status(), StatusCode::FORBIDDEN);

            // Check that the illegitimate request did not actually change anything
            let mut resp = client.get("http://localhost:8086/load/5").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert_eq!(content, "{}");

            let mut resp = client.get("http://localhost:8086/contest/3").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("<a href=\"/task/5\">☆☆☆</a></li>"));
            assert!(content.contains("<a href=\"/task/6\">☆☆☆☆</a></li>"));

714
            let params = [("data", "SomeData"), ("grade", "67"), ("csrf_token", csrf)];
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
            let mut resp = client.post("http://localhost:8086/save/5").form(&params).send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert_eq!(content, "{}");

            let mut resp = client.get("http://localhost:8086/load/5").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert_eq!(content, "SomeData");

            let mut resp = client.get("http://localhost:8086/contest/3").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("<a href=\"/task/5\">★★☆</a></li>"));
            assert!(content.contains("<a href=\"/task/6\">☆☆☆☆</a></li>"));
        })
    }

    #[test]
    fn check_task_load_save_logged_in() {
738
739
740
        start_server_and_fn(8087, |conn| {
            addsimpleuser(conn, "testusr".to_string(), "testpw".to_string(), false, false);
        }, || {
741
742
743
744
745
746
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

            let resp = login(8087, &client, "testusr", "testpw");
747
            assert_eq!(resp.status(), StatusCode::FOUND);
Robert Czechowski's avatar
Robert Czechowski committed
748

749
            let mut resp = client.get("http://localhost:8087/contest/1").send().unwrap();
750
751
752
753
754
755
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            let pos = content.find("type=\"hidden\" name=\"csrf_token\" value=\"").expect("CSRF-Token not found");
            let csrf = &content[pos + 39..pos + 49];
            let params = [("csrf_token", csrf)];
756
            let resp = client.post("http://localhost:8087/contest/1").form(&params).send().unwrap();
757
758
            assert_eq!(resp.status(), StatusCode::FOUND);

759
            let mut resp = client.get("http://localhost:8087/task/1").send().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
760
761
762
763
764
765
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            let pos = content.find("#taskid=1&csrftoken=").expect("CSRF-Token not found");
            let csrf = &content[pos + 20..pos + 30];

766
            let mut resp = client.get("http://localhost:8087/load/1").send().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
767
            assert_eq!(resp.status(), StatusCode::OK);
768

Robert Czechowski's avatar
Robert Czechowski committed
769
770
771
            let content = resp.text().unwrap();
            assert_eq!(content, "{}");

772
            let params = [("data", "WrongData"), ("grade", "1"), ("csrf_token", "FNQU4QsEMY")];
773
            let resp = client.post("http://localhost:8087/save/1").form(&params).send().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
774
775
            assert_eq!(resp.status(), StatusCode::FORBIDDEN);

776
            // Check that the illigal request did not actually change anything
777
            let mut resp = client.get("http://localhost:8087/load/1").send().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
778
            assert_eq!(resp.status(), StatusCode::OK);
779

Robert Czechowski's avatar
Robert Czechowski committed
780
781
            let content = resp.text().unwrap();
            assert_eq!(content, "{}");
782

783
            let mut resp = client.get("http://localhost:8087/contest/1").send().unwrap();
784
785
786
787
788
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("<a href=\"/task/1\">☆☆☆</a></li>"));
            assert!(content.contains("<a href=\"/task/2\">☆☆☆☆</a></li>"));
789

790
            let params = [("data", "SomeData"), ("grade", "67"), ("csrf_token", csrf)];
791
            let mut resp = client.post("http://localhost:8087/save/1").form(&params).send().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
792
793
794
795
796
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert_eq!(content, "{}");

797
            let mut resp = client.get("http://localhost:8087/load/1").send().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
798
            assert_eq!(resp.status(), StatusCode::OK);
799

Robert Czechowski's avatar
Robert Czechowski committed
800
801
            let content = resp.text().unwrap();
            assert_eq!(content, "SomeData");
802

803
            let mut resp = client.get("http://localhost:8087/contest/1").send().unwrap();
804
805
806
807
808
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("<a href=\"/task/1\">★★☆</a></li>"));
            assert!(content.contains("<a href=\"/task/2\">☆☆☆☆</a></li>"));
Robert Czechowski's avatar
Robert Czechowski committed
809
810
        })
    }
811
812
813

    #[test]
    fn check_taskgroup_rename() {
814
        start_server_and_fn(8088, |_|{}, || {
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

            let mut resp = client.get("http://localhost:8088/contest/3").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("TaskgroupNewName"));
            assert!(!content.contains("TaskgroupRenameName"));

            let mut resp = client.get("http://localhost:8088/task/5").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("TaskgroupNewName"));
            assert!(!content.contains("TaskgroupRenameName"));
        })
    }
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857

    #[test]
    fn check_admin_interface_link() {
        start_server_and_fn(8089, |conn| {
            addsimpleuser(conn, "testadm".to_string(), "testpw1".to_string(), false, true);
            addsimpleuser(conn, "testusr".to_string(), "testpw2".to_string(), false, false);
            addsimpleuser(conn, "testtch".to_string(), "testpw3".to_string(), true, false);
        }, || {
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

            let resp = login(8089, &client, "testadm", "testpw1");
            assert_eq!(resp.status(), StatusCode::FOUND);

            let mut resp = client.get("http://localhost:8089/").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("Administration"));
            assert!(content.contains("<a href=\"/admin/\""));

858

859
860
861
862
863
864
865
866
867
868
869
870
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

            let mut resp = client.get("http://localhost:8089/").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(!content.contains("Administration"));
            assert!(!content.contains("<a href=\"/admin/\""));

871

872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

            let mut resp = login(8089, &client, "testusr", "testpw2");
            assert_eq!(resp.status(), StatusCode::FOUND);

            println!("{}", resp.text().unwrap());

            let mut resp = client.get("http://localhost:8089/").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(!content.contains("Administration"));
            assert!(!content.contains("<a href=\"/admin/\""));

889

890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

            let mut resp = login(8089, &client, "testtch", "testpw3");
            assert_eq!(resp.status(), StatusCode::FOUND);

            println!("{}", resp.text().unwrap());

            let mut resp = client.get("http://localhost:8089/").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(!content.contains("Administration"));
            assert!(!content.contains("<a href=\"/admin/\""));
        })
    }

    #[test]
    fn check_admin_interface_access() {
        start_server_and_fn(8090, |conn| {
            addsimpleuser(conn, "testadm".to_string(), "testpw1".to_string(), false, true);
            addsimpleuser(conn, "testusr".to_string(), "testpw2".to_string(), false, false);
            addsimpleuser(conn, "testtch".to_string(), "testpw3".to_string(), true, false);
        }, || {
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

            let resp = login(8090, &client, "testadm", "testpw1");
            assert_eq!(resp.status(), StatusCode::FOUND);


            let mut resp = client.get("http://localhost:8090/admin").send().unwrap();
926
            assert_eq!(resp.status(), StatusCode::OK);
927
928
929
930
931
932

            let content = resp.text().unwrap();
            assert!(content.contains("Administration"));
            assert!(content.contains("Admin-Suche"));
            assert!(content.contains("Wettbewerbs-Export"));

933

934
935
936
937
938
939
940
941
942
943
944
945
946
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

            let mut resp = client.get("http://localhost:8090/admin").send().unwrap();
            assert_eq!(resp.status(), StatusCode::FOUND);

            let content = resp.text().unwrap();
            assert!(!content.contains("Administration"));
            assert!(!content.contains("Admin-Suche"));
            assert!(!content.contains("Wettbewerbs-Export"));

947

948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

            let mut resp = login(8090, &client, "testusr", "testpw2");
            assert_eq!(resp.status(), StatusCode::FOUND);

            println!("{}", resp.text().unwrap());

            let mut resp = client.get("http://localhost:8090/admin").send().unwrap();
            assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

            let content = resp.text().unwrap();
            assert!(!content.contains("Administration"));
            assert!(!content.contains("Admin-Suche"));
            assert!(!content.contains("Wettbewerbs-Export"));

966

967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

            let mut resp = login(8090, &client, "testtch", "testpw3");
            assert_eq!(resp.status(), StatusCode::FOUND);

            println!("{}", resp.text().unwrap());

            let mut resp = client.get("http://localhost:8090/admin").send().unwrap();
            assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

            let content = resp.text().unwrap();
            assert!(!content.contains("Administration"));
            assert!(!content.contains("Admin-Suche"));
            assert!(!content.contains("Wettbewerbs-Export"));
        })
    }
986
987

    #[test]
988
    fn check_cleanup() {
989
        start_server_and_fn(8091, |conn| {
990
991
992
            let ago170days = Some(time::get_time() - time::Duration::days(170));
            let ago190days = Some(time::get_time() - time::Duration::days(190));

993
994
995
            let mut test_user = conn.new_session("");
            test_user.username = Some("testusr".to_string());
            test_user.set_password(&"testpw").expect("Set Password did not work correctly.");
996
            conn.session_set_activity_dates(test_user.id, ago190days, ago190days, ago190days);
997
998
999
            conn.save_session(test_user);

            let mut test_user = conn.new_session("");
1000
            test_user.lastname = Some("teststdold".to_string());
1001
            test_user.logincode = Some("logincode1".to_string());
1002
1003
            test_user.managed_by = Some(1); // Fake id, should this group really exist?
            conn.session_set_activity_dates(test_user.id, ago190days, ago190days, ago190days);
1004
1005
1006
            conn.save_session(test_user);

            let mut test_user = conn.new_session("");
1007
            test_user.lastname = Some("teststdnew".to_string());
1008
            test_user.logincode = Some("logincode2".to_string());
1009
1010
            test_user.managed_by = Some(1);
            conn.session_set_activity_dates(test_user.id, ago190days, ago170days, ago190days);
1011
1012
1013
1014
1015
1016
1017
1018
            conn.save_session(test_user);

            addsimpleuser(conn, "testadm".to_string(), "testpw1".to_string(), false, true);
        }, || {
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();
1019
            // Login as Admin
1020
1021
1022
            let resp = login(8091, &client, "testadm", "testpw1");
            assert_eq!(resp.status(), StatusCode::FOUND);

1023
1024
1025
1026
1027
1028
1029
1030
            // Check old account still existing
            let mut resp = client.get("http://localhost:8091/admin/user/2").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("teststdold"));

            // Delete old data
1031
1032
1033
1034
1035
1036
1037
1038
1039
            let mut resp = client.get("http://localhost:8091/admin/cleanup").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert!(content.contains("Alte Daten löschen"));

            let pos = content.find("type=\"hidden\" name=\"csrf_token\" value=\"").expect("CSRF-Token not found");
            let csrf = &content[pos + 39..pos + 49];
            let params = [("csrf_token", csrf)];
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
            let mut resp = client.post("http://localhost:8091/admin/cleanup").form(&params).send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);

            let content = resp.text().unwrap();
            assert_eq!(content, "{\"status\":\"ok\",\"n_users\":1,\"n_groups\":0,\"n_teachers\":0,\"n_other\":0}\n");

            // Check old account no longer existing
            let mut resp = client.get("http://localhost:8091/admin/user/2").send().unwrap();
            assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

            let content = resp.text().unwrap();
            assert!(!content.contains("teststdold"));

            // Logout as admin
            let resp = client.get("http://localhost:8091/logout").send().unwrap();
            assert_eq!(resp.status(), StatusCode::FOUND);

            // Check login with old account no longer possible
            let resp = login_code(8091, &client, "logincode1");