main.rs 33.7 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;
Robert Czechowski's avatar
Robert Czechowski committed
34
35
36
37
extern crate staticfile;
extern crate structopt;
extern crate time;
extern crate urlencoded;
38
39
40

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

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

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

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

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

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

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

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

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

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

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

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

    contests
}

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

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

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

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

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

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

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

156
157
158
159
160
161
162
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) {
163
        print!("Scanning for contests …");
164
        refresh_all_contests(&mut conn);
165
        println!(" Done")
166
167
168
169
170
    }

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

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

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

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

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

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

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

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

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

210
211
212
213
214
215
    #[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));
216
    opt.teacherpage.map(|x| config.teacher_page = Some(x));
217
218
219
    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
222
223
224
225
226

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

228
229
230
    #[cfg(feature = "postgres")]
    {
        if let Some(url) = config.database_url.clone() {
231
            #[cfg(feature = "debug")]
232
            print!("Using database {} … ", &url);
233
234
            #[cfg(not(feature = "debug"))]
            {
235
236
237
238
                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);
            }
239
240
241
242
243
244
            let conn = postgres::Connection::connect(url, postgres::TlsMode::None).unwrap();
            println!("Connected");

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

    #[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.");
260
}
261
262
263
264

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

Robert Czechowski's avatar
Robert Czechowski committed
267
268
    fn start_server_and_fn<F>(port: u16, set_user: Option<(String, String, bool)>, f: F)
        where F: Fn() {
269
        use std::sync::mpsc::channel;
Robert Czechowski's avatar
Robert Czechowski committed
270
        use std::{thread, time};
271
272
273
274
        let (start_tx, start_rx) = channel();
        let (stop_tx, stop_rx) = channel();

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

278
            if let Some(user) = set_user {
279
                let mut test_user = conn.new_session("");
280
                test_user.username = Some(user.0);
Robert Czechowski's avatar
Robert Czechowski committed
281
282
283
                test_user.is_teacher = user.2;
                test_user.set_password(&user.1).expect("Set Password did not work correctly.");
                conn.save_session(test_user);
284
285
            }

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

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

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

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

372
            let mut config = config::read_config_from_file(Path::new("thisfileshoudnotexist"));
373
            config.port = Some(port);
374
            config.cookie_signing_secret = Some("testtesttesttesttesttesttesttest".to_string());
375
            let mut srvr = start_server(conn, config).expect(&format!("Could not start server on port {}", port));
376

377
            // Message server started
378
379
            start_tx.send(()).unwrap();

380
            // Wait for test to finish
381
382
            stop_rx.recv().unwrap();

383
            srvr.close().unwrap();
384
385
        });

386
        // Wait for server to start
387
388
        start_rx.recv().unwrap();
        thread::sleep(time::Duration::from_millis(100));
389
390

        // Run test code
391
        f();
392

393
        // Message test finished
394
395
396
        stop_tx.send(()).unwrap();
    }

397
    fn login(port: u16, client: &reqwest::Client, username: &str, password: &str) -> reqwest::Response {
398
        let params = [("username", username), ("password", password)];
Robert Czechowski's avatar
Robert Czechowski committed
399
        let resp = client.post(&format!("http://localhost:{}/login", port)).form(&params).send().unwrap();
400
        resp
401
    }
Robert Czechowski's avatar
Robert Czechowski committed
402

403
404
405
406
407
    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
    }
408

409
    #[test]
Robert Czechowski's avatar
Robert Czechowski committed
410
    fn start_server_and_check_requests() {
Robert Czechowski's avatar
Robert Czechowski committed
411
        start_server_and_fn(8080, None, || {
412
            let mut resp = reqwest::get("http://localhost:8080").unwrap();
413
            assert_eq!(resp.status(), StatusCode::OK);
414
415

            let content = resp.text().unwrap();
416
            assert!(content.contains("Jugendwettbewerb Informatik</h1>"));
417
            assert!(!content.contains("Error"));
Robert Czechowski's avatar
Robert Czechowski committed
418
            assert!(!content.contains("Gruppenverwaltung"));
419
420

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

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

            let mut resp = reqwest::get("http://localhost:8080/group").unwrap();
428
            let content = resp.text().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
429
            assert!(content.contains("<h1>Login</h1>"));
430
431
        })
    }
Daniel Brüning's avatar
Daniel Brüning committed
432

433
434
    #[test]
    fn check_login_wrong_credentials() {
Robert Czechowski's avatar
Robert Czechowski committed
435
        start_server_and_fn(8081, None, || {
436
            let client = reqwest::Client::new();
Robert Czechowski's avatar
Robert Czechowski committed
437

438
            let mut resp = login(8081, &client, "nonexistingusername", "wrongpassword");
439
            assert_eq!(resp.status(), StatusCode::OK);
440
441

            let content = resp.text().unwrap();
442
443
            assert!(content.contains("<h1>Login</h1>"));
            assert!(content.contains("Login fehlgeschlagen."));
444
            assert!(!content.contains("Error"));
Robert Czechowski's avatar
Robert Czechowski committed
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460

            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"));
461
        })
462
    }
463
464

    #[test]
Robert Czechowski's avatar
Robert Czechowski committed
465
    fn check_login() {
Robert Czechowski's avatar
Robert Czechowski committed
466
        start_server_and_fn(8082, Some(("testusr".to_string(), "testpw".to_string(), false)), || {
467
468
469
470
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
471

472
            let mut resp = login(8082, &client, "testusr", "testpw");
473
            assert_eq!(resp.status(), StatusCode::FOUND);
474

475
            let content = resp.text().unwrap();
476
477
            assert!(!content.contains("Error"));

478
479
480
481
            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
482
483
484
485
            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();
486
487
            assert_eq!(resp.status(), StatusCode::OK);

488
            let content = resp.text().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
489
490
491
492
            assert!(!content.contains("Error"));
            assert!(!content.contains("Gruppenverwaltung"));
            assert!(content.contains("Eingeloggt als <em>testusr</em>"));
            assert!(content.contains("Jugendwettbewerb Informatik</h1>"));
493
494
495
        })
    }

496
    #[test]
Robert Czechowski's avatar
Robert Czechowski committed
497
    fn check_logout() {
Robert Czechowski's avatar
Robert Czechowski committed
498
        start_server_and_fn(8083, Some(("testusr".to_string(), "testpw".to_string(), false)), || {
499
500
501
502
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
503

504
            let resp = login(8083, &client, "testusr", "testpw");
505
506
507
508
509
510
511
            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);
512
513

            let content = resp.text().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
514
515
516
517
            assert!(content.contains("Benutzername"));
            assert!(content.contains("Passwort"));
            assert!(content.contains("Gruppencode / Teilnahmecode"));
            assert!(content.contains("Jugendwettbewerb Informatik</h1>"));
518
519
520
        })
    }

521
522
    #[test]
    fn check_group_creation_and_group_code_login() {
Robert Czechowski's avatar
Robert Czechowski committed
523
        start_server_and_fn(8084, Some(("testusr".to_string(), "testpw".to_string(), true)), || {
524
525
526
527
528
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

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

532
533
            let mut resp = client.get("http://localhost:8084").send().unwrap();
            assert_eq!(resp.status(), StatusCode::OK);
534
535

            let content = resp.text().unwrap();
536
537
            assert!(content.contains("[Lehrer]"));
            assert!(content.contains("Gruppenverwaltung"));
538
539
540

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

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

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

549
550
551
            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)];
552
553
            let resp = client.post("http://localhost:8084/group/").form(&params).send().unwrap();
            assert_eq!(resp.status(), StatusCode::FOUND);
554
555
556
557

            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
558

559
560
561
562
563
            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
564
565
566
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();
567
568
569
570

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

Robert Czechowski's avatar
Robert Czechowski committed
571
572
573
574
575
            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();
576
            assert_eq!(location, "http://localhost:8084/profile?status=firstlogin");
Robert Czechowski's avatar
Robert Czechowski committed
577
578

            let mut resp = client.get(location).send().unwrap();
579
580
581
582
583
584
585
            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
586
587
588
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();
589
590
591
592

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

Robert Czechowski's avatar
Robert Czechowski committed
593
594
595
596
            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();
597
598
            let content = resp.text().unwrap();
            assert!(content.contains("Eingeloggt als <em></em>"));
599
600
        })
    }
Robert Czechowski's avatar
Robert Czechowski committed
601
602
603
604
605
606
607
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

    #[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"));

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

638
639
640
            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
641
642
            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
643
644
645
646
647
648
649

            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>"));
650
651
652
653
654
        })
    }

    #[test]
    fn check_task_load_save() {
655
        start_server_and_fn(8086, None, || {
656
657
658
659
660
            let client = reqwest::Client::builder().cookie_store(true)
                                                   .redirect(reqwest::RedirectPolicy::none())
                                                   .build()
                                                   .unwrap();

661
            let resp = client.get("http://localhost:8086/contest/3").send().unwrap();
662
663
664
665
666
667
668
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
            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");
726
            assert_eq!(resp.status(), StatusCode::FOUND);
Robert Czechowski's avatar
Robert Czechowski committed
727

728
            let mut resp = client.get("http://localhost:8087/contest/1").send().unwrap();
729
730
731
732
733
734
            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)];
735
            let resp = client.post("http://localhost:8087/contest/1").form(&params).send().unwrap();
736
737
            assert_eq!(resp.status(), StatusCode::FOUND);

738
            let mut resp = client.get("http://localhost:8087/task/1").send().unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
739
740
741
742
743
744
            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];

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

Robert Czechowski's avatar
Robert Czechowski committed
748
749
750
            let content = resp.text().unwrap();
            assert_eq!(content, "{}");

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

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

Robert Czechowski's avatar
Robert Czechowski committed
759
760
            let content = resp.text().unwrap();
            assert_eq!(content, "{}");
761

762
            let mut resp = client.get("http://localhost:8087/contest/1").send().unwrap();
763
764
765
766
767
            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>"));
768
769

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

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

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

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

782
            let mut resp = client.get("http://localhost:8087/contest/1").send().unwrap();
783
784
785
786
787
            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
788
789
        })
    }
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814

    #[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"));
        })
    }
815
}