main.rs 34.2 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;

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

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

45
46
pub mod config;
pub mod contestreader_yaml;
47
pub mod core;
48
pub mod db_conn;
49
pub mod helpers;
50
51
52
pub mod oauth_provider;

mod db_apply_migrations;
53
mod db_conn_postgres;
54
mod db_conn_sqlite_new;
55
mod db_objects;
56
57
mod webfw_iron;

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

63
use config::Config;
64
65
use structopt::StructOpt;

66
use std::path::{Path, PathBuf};
67

68
fn read_contest(p: &PathBuf) -> Option<Contest> {
69
70
    use std::fs::File;
    use std::io::Read;
71

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

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

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

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

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

    contests
}

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

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

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

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

Robert Czechowski's avatar
Robert Czechowski committed
138
    use rand::{distributions::Alphanumeric, thread_rng, Rng};
139
140

    let password: String = thread_rng().sample_iter(&Alphanumeric)
Robert Czechowski's avatar
Robert Czechowski committed
141
142
143
144
145
146
                                       .filter(|x| {
                                           let x = *x;
                                           !(x == 'l' || x == 'I' || x == '1' || x == 'O' || x == 'o' || x == '0')
                                       })
                                       .take(8)
                                       .collect();
147
148
149
    print!("'{}', ", &password);

    let logincode: String = thread_rng().sample_iter(&Alphanumeric)
150
151
152
153
154
155
                                        .filter(|x| {
                                            let x = *x;
                                            !(x == 'l' || x == 'I' || x == '1' || x == 'O' || x == 'o' || x == '0')
                                        })
                                        .take(8)
                                        .collect();
156
157
    let logincode = format!("a{}", logincode);
    print!(" logincode:'{}' …", &logincode);
158
159

    admin.username = Some("admin".into());
160
    admin.logincode = Some(logincode);
161
    match admin.set_password(&password) {
162
        None => println!(" FAILED! (Password hashing error)"),
163
164
        _ => {
            conn.save_session(admin);
165
            println!(" Done");
166
        }
167
168
169
    }
}

170
171
172
173
174
175
176
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) {
177
        print!("Scanning for contests …");
178
        refresh_all_contests(&mut conn);
179
        println!(" Done")
180
181
182
183
184
    }

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

185
        #[cfg(feature = "webbrowser")]
186
        let self_url = config.self_url.clone();
187
        #[cfg(feature = "webbrowser")]
188
189
        let open_browser = config.open_browser;

190
        match start_server(conn, config) {
191
192
            Ok(_) => {
                println!("Server started");
193

194
195
196
197
198
                #[cfg(feature = "webbrowser")]
                {
                    if let (Some(self_url), Some(true)) = (self_url, open_browser) {
                        open_browser_window(&self_url);
                    }
199
                }
200
            }
201
202
            Err(_) => println!("Error on server start …"),
        };
203

204
205
206
207
        println!("Could not run server. Is the port already in use?");
    }
}

208
#[cfg(feature = "webbrowser")]
209
210
211
fn open_browser_window(self_url: &str) {
    match webbrowser::open(&self_url) {
        Ok(_) => (),
212
        Err(e) => println!("Error while opening webbrowser: {:?}", e),
213
214
215
    }
}

Robert Czechowski's avatar
Robert Czechowski committed
216
fn main() {
217
    let opt = config::Opt::from_args();
218
219
220

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

222
    let mut config = config::read_config_from_file(&opt.configfile);
223

224
225
226
227
228
229
    #[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));
230
    opt.teacherpage.map(|x| config.teacher_page = Some(x));
231
232
233
    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 };
234
    config.disable_results_page = if opt.disableresultspage { Some(true) } else { config.disable_results_page };
235
236
237
238
239
240

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

242
243
244
245
246
247
248
249
250
251
    #[cfg(feature = "postgres")]
    {
        if let Some(url) = config.database_url.clone() {
            print!("Using database {} … ", &url);
            let conn = postgres::Connection::connect(url, postgres::TlsMode::None).unwrap();
            println!("Connected");

            prepare_and_start_server(conn, config, opt.onlycontestscan, opt.resetadminpw);
            return;
        }
252
    }
253
254
255
256
257
258
259
260
261
262
263
264
265
266

    #[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.");
267
}
268
269
270
271

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

Robert Czechowski's avatar
Robert Czechowski committed
274
275
    fn start_server_and_fn<F>(port: u16, set_user: Option<(String, String, bool)>, f: F)
        where F: Fn() {
276
        use std::sync::mpsc::channel;
Robert Czechowski's avatar
Robert Czechowski committed
277
        use std::{thread, time};
278
279
280
281
        let (start_tx, start_rx) = channel();
        let (stop_tx, stop_rx) = channel();

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

285
            if let Some(user) = set_user {
286
                let mut test_user = conn.new_session("");
287
                test_user.username = Some(user.0);
Robert Czechowski's avatar
Robert Czechowski committed
288
289
290
                test_user.is_teacher = user.2;
                test_user.set_password(&user.1).expect("Set Password did not work correctly.");
                conn.save_session(test_user);
291
292
            }

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

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

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

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

379
            let mut config = config::read_config_from_file(Path::new("thisfileshoudnotexist"));
380
            config.port = Some(port);
381
            config.cookie_signing_secret = Some("testtesttesttesttesttesttesttest".to_string());
382
            let mut srvr = start_server(conn, config).expect(&format!("Could not start server on port {}", port));
383

384
            // Message server started
385
386
            start_tx.send(()).unwrap();

387
            // Wait for test to finish
388
389
            stop_rx.recv().unwrap();

390
            srvr.close().unwrap();
391
392
        });

393
        // Wait for server to start
394
395
        start_rx.recv().unwrap();
        thread::sleep(time::Duration::from_millis(100));
396
397

        // Run test code
398
        f();
399

400
        // Message test finished
401
402
403
        stop_tx.send(()).unwrap();
    }

404
    fn login(port: u16, client: &reqwest::Client, username: &str, password: &str) -> reqwest::Response {
405
        let params = [("username", username), ("password", password)];
Robert Czechowski's avatar
Robert Czechowski committed
406
        let resp = client.post(&format!("http://localhost:{}/login", port)).form(&params).send().unwrap();
407
        resp
408
    }
Robert Czechowski's avatar
Robert Czechowski committed
409

410
411
412
413
414
    fn login_code(port: u16, client: &reqwest::Client, code: &str) -> reqwest::Response {
        let params = [("code", code)];
        let resp = client.post(&format!("http://localhost:{}/clogin", port)).form(&params).send().unwrap();
        resp
    }
415

416
    #[test]
Robert Czechowski's avatar
Robert Czechowski committed
417
    fn start_server_and_check_requests() {
Robert Czechowski's avatar
Robert Czechowski committed
418
        start_server_and_fn(8080, None, || {
419
            let mut resp = reqwest::get("http://localhost:8080").unwrap();
420
            assert_eq!(resp.status(), StatusCode::OK);
421
422

            let content = resp.text().unwrap();
423
            assert!(content.contains("Jugendwettbewerb Informatik</h1>"));
424
            assert!(!content.contains("Error"));
Robert Czechowski's avatar
Robert Czechowski committed
425
            assert!(!content.contains("Gruppenverwaltung"));
426
427

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

            let content = resp.text().unwrap();
431
432
            assert!(content.contains("<h1>Wettbewerbe</h1>"));
            assert!(!content.contains("Error"));
Robert Czechowski's avatar
Robert Czechowski committed
433
434

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

440
441
    #[test]
    fn check_login_wrong_credentials() {
Robert Czechowski's avatar
Robert Czechowski committed
442
        start_server_and_fn(8081, None, || {
443
            let client = reqwest::Client::new();
Robert Czechowski's avatar
Robert Czechowski committed
444

445
            let mut resp = login(8081, &client, "nonexistingusername", "wrongpassword");
446
            assert_eq!(resp.status(), StatusCode::OK);
447
448

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

            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"));
468
        })
469
    }
470
471

    #[test]
Robert Czechowski's avatar
Robert Czechowski committed
472
    fn check_login() {
Robert Czechowski's avatar
Robert Czechowski committed
473
        start_server_and_fn(8082, Some(("testusr".to_string(), "testpw".to_string(), false)), || {
474
475
476
477
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
478

479
            let mut resp = login(8082, &client, "testusr", "testpw");
480
            assert_eq!(resp.status(), StatusCode::FOUND);
481

482
            let content = resp.text().unwrap();
483
484
            assert!(!content.contains("Error"));

485
486
487
488
            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
489
490
491
492
            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();
493
494
            assert_eq!(resp.status(), StatusCode::OK);

495
            let content = resp.text().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
496
497
498
499
            assert!(!content.contains("Error"));
            assert!(!content.contains("Gruppenverwaltung"));
            assert!(content.contains("Eingeloggt als <em>testusr</em>"));
            assert!(content.contains("Jugendwettbewerb Informatik</h1>"));
500
501
502
        })
    }

503
    #[test]
Robert Czechowski's avatar
Robert Czechowski committed
504
    fn check_logout() {
Robert Czechowski's avatar
Robert Czechowski committed
505
        start_server_and_fn(8083, Some(("testusr".to_string(), "testpw".to_string(), false)), || {
506
507
508
509
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
510

511
            let resp = login(8083, &client, "testusr", "testpw");
512
513
514
515
516
517
518
            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);
519
520

            let content = resp.text().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
521
522
523
524
            assert!(content.contains("Benutzername"));
            assert!(content.contains("Passwort"));
            assert!(content.contains("Gruppencode / Teilnahmecode"));
            assert!(content.contains("Jugendwettbewerb Informatik</h1>"));
525
526
527
        })
    }

528
529
    #[test]
    fn check_group_creation_and_group_code_login() {
Robert Czechowski's avatar
Robert Czechowski committed
530
        start_server_and_fn(8084, Some(("testusr".to_string(), "testpw".to_string(), true)), || {
531
532
533
534
535
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

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

539
540
            let mut resp = client.get("http://localhost:8084").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);
541
542

            let content = resp.text().unwrap();
543
544
            assert!(content.contains("[Lehrer]"));
            assert!(content.contains("Gruppenverwaltung"));
545
546
547

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

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

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

556
557
558
            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)];
559
560
            let resp = client.post("http://localhost:8084/group/").form(&params).send().unwrap();
            assert_eq!(resp.status(), StatusCode::FOUND);
561
562
563
564

            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
565

566
567
568
569
570
            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
571
572
573
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();
574
575
576
577

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

Robert Czechowski's avatar
Robert Czechowski committed
578
579
580
581
582
            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();
583
            assert_eq!(location, "http://localhost:8084/profile?status=firstlogin");
Robert Czechowski's avatar
Robert Czechowski committed
584
585

            let mut resp = client.get(location).send().unwrap();
586
587
588
589
590
591
592
            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
593
594
595
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();
596
597
598
599

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

Robert Czechowski's avatar
Robert Czechowski committed
600
601
602
603
            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();
604
605
            let content = resp.text().unwrap();
            assert!(content.contains("Eingeloggt als <em></em>"));
606
607
        })
    }
Robert Czechowski's avatar
Robert Czechowski committed
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640

    #[test]
    fn check_contest_start() {
        start_server_and_fn(8085, Some(("testusr".to_string(), "testpw".to_string(), false)), || {
            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"));

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

645
646
647
            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
648
649
            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
650
651
652
653
654
655
656

            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>"));
657
658
659
660
661
        })
    }

    #[test]
    fn check_task_load_save() {
662
        start_server_and_fn(8086, None, || {
663
664
665
666
667
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

668
            let resp = client.get("http://localhost:8086/contest/3").send().unwrap();
669
670
671
672
673
674
675
676
677
678
679
680
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
            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>"));

            let params = [("data", "SomeData"), ("grade", "2"), ("csrf_token", csrf)];
            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() {
        start_server_and_fn(8087, Some(("testusr".to_string(), "testpw".to_string(), false)), || {
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

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

735
            let mut resp = client.get("http://localhost:8087/contest/1").send().unwrap();
736
737
738
739
740
741
            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)];
742
            let resp = client.post("http://localhost:8087/contest/1").form(&params).send().unwrap();
743
744
            assert_eq!(resp.status(), StatusCode::FOUND);

745
            let mut resp = client.get("http://localhost:8087/task/1").send().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
746
747
748
749
750
751
            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];

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

Robert Czechowski's avatar
Robert Czechowski committed
755
756
757
            let content = resp.text().unwrap();
            assert_eq!(content, "{}");

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

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

Robert Czechowski's avatar
Robert Czechowski committed
766
767
            let content = resp.text().unwrap();
            assert_eq!(content, "{}");
768

769
            let mut resp = client.get("http://localhost:8087/contest/1").send().unwrap();
770
771
772
773
774
            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>"));
775
776

            let params = [("data", "SomeData"), ("grade", "2"), ("csrf_token", csrf)];
777
            let mut resp = client.post("http://localhost:8087/save/1").form(&params).send().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
778
779
780
781
782
            assert_eq!(resp.status(), StatusCode::OK);

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

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

Robert Czechowski's avatar
Robert Czechowski committed
786
787
            let content = resp.text().unwrap();
            assert_eq!(content, "SomeData");
788

789
            let mut resp = client.get("http://localhost:8087/contest/1").send().unwrap();
790
791
792
793
794
            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
795
796
        })
    }
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821

    #[test]
    fn check_taskgroup_rename() {
        start_server_and_fn(8088, None, || {
            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();
            println!("{}", content);
            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"));
        })
    }
822
}