db_conn_postgres.rs 81.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *                                                                             *
 *        WARNING                                                              *
 *                                                                             *
 * This file is auto generated by ./generate_connectors.sh                     *
 *                                                                             *
 * Do not edit this file directly. Instead edit one of the corresponding       *
 * .header.rs oder .base.rs files.                                             *
 *                                                                             *
 *                                                                             *
 *                                                                             *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*  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/>.                                                                                  */

28
29
#![cfg(feature = "postgres")]

30
31
extern crate postgres;

32
33
34
use postgres::Connection;
use time;
use time::Duration;
35

36
use db_conn::{MedalConnection, MedalObject, SignupResult};
37
use db_objects::*;
38
use helpers;
39

40
41
fn gen_tosql_vector() -> Vec<&'static dyn postgres::types::ToSql> { Vec::new() }

42
trait Queryable {
Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
43
44
    fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F)
                           -> postgres::Result<Option<T>>
45
        where F: FnOnce(postgres::rows::Row<'_>) -> T;
46
47
    fn query_map_many<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F) -> postgres::Result<Vec<T>>
        where F: FnMut(postgres::rows::Row<'_>) -> T;
48
    fn exists(&self, sql: &str, params: &[&dyn postgres::types::ToSql]) -> bool;
49
    fn get_last_id(&self) -> Option<i32>;
50
51
52
}

impl Queryable for Connection {
Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
53
54
    fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F)
                           -> postgres::Result<Option<T>>
55
56
        where F: FnOnce(postgres::rows::Row<'_>) -> T {
        let rows = self.query(sql, params)?;
57

58
59
        Ok(rows.iter().next().map(f))
    }
60

61
62
63
64
65
    fn query_map_many<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F) -> postgres::Result<Vec<T>>
        where F: FnMut(postgres::rows::Row<'_>) -> T {
        Ok(self.query(sql, params)?.iter().map(f).collect())
    }

66
67
    fn exists(&self, sql: &str, params: &[&dyn postgres::types::ToSql]) -> bool {
        let stmt = self.prepare(sql).unwrap();
Robert Czechowski's avatar
Robert Czechowski committed
68
        stmt.query(params).unwrap().len() > 0
69
70
    }

71
72
73
74
75
76
    fn get_last_id(&self) -> Option<i32> {
        self.query("SELECT lastval()", &[]).unwrap().iter().next().map(|row| {
                                                                      let r: i64 = row.get(0);
                                                                      r as i32
                                                                  })
    }
77
    // Empty line intended
78
79
}

80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
impl MedalObject<Connection> for Submission {
    fn save(&mut self, conn: &Connection) {
        match self.get_id() {
            Some(_id) => unimplemented!(),
            None => {
                let query = "INSERT INTO submission (task, session, grade, validated, nonvalidated_grade,
                                                     subtask_identifier, value, date, needs_validation)
                             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)";
                conn.execute(query,
                             &[&self.task,
                               &self.session_user,
                               &self.grade,
                               &self.validated,
                               &self.nonvalidated_grade,
                               &self.subtask_identifier,
                               &self.value,
                               &self.date,
                               &self.needs_validation])
                    .unwrap();
                self.set_id(conn.get_last_id().unwrap());
            }
        }
    }
}

impl MedalObject<Connection> for Grade {
    fn save(&mut self, conn: &Connection) {
        let query = "INSERT INTO grade (taskgroup, session, grade, validated)
                     VALUES ($1, $2, $3, $4)
                     ON CONFLICT ON CONSTRAINT grade_pkey DO UPDATE SET grade = excluded.grade, validated = excluded.validated";
        conn.execute(query, &[&self.taskgroup, &self.user, &self.grade, &self.validated]).unwrap();
    }
}
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/*  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/>.                                                                                  */

127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
impl MedalObject<Connection> for Participation {
    fn save(&mut self, conn: &Connection) {
        let query = "INSERT INTO participation (contest, session, start_date)
                     VALUES ($1, $2, $3)";
        conn.execute(query, &[&self.contest, &self.user, &self.start]).unwrap();
    }
}

impl MedalObject<Connection> for Group {
    fn save(&mut self, conn: &Connection) {
        match self.get_id() {
            Some(_id) => unimplemented!(),
            None => {
                let query = "INSERT INTO usergroup (name, groupcode, tag, admin)
                             VALUES ($1, $2, $3, $4)";
                conn.execute(query, &[&self.name, &self.groupcode, &self.tag, &self.admin]).unwrap();
                self.set_id(conn.get_last_id().unwrap());
            }
        }
    }
}

impl MedalObject<Connection> for Task {
    fn save(&mut self, conn: &Connection) {
        let query = "SELECT id
                     FROM task
                     WHERE taskgroup = $1
                     AND location = $2";
        conn.query_map_one(query, &[&self.taskgroup, &self.location], |row| row.get(0))
            .unwrap_or(None)
157
            .map(|id| {
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
                self.set_id(id);
            })
            .unwrap_or(()); // Err means no entry yet and is expected result

        let id = match self.get_id() {
            Some(id) => {
                let query = "UPDATE task
                             SET taskgroup = $1, location = $2, stars = $3
                             WHERE id = $4";
                conn.execute(query, &[&self.taskgroup, &self.location, &self.stars, &id]).unwrap();
                id
            }
            None => {
                let query = "INSERT INTO task (taskgroup, location, stars)
                             VALUES ($1, $2, $3)";
                conn.execute(query, &[&self.taskgroup, &self.location, &self.stars]).unwrap();
                conn.get_last_id().unwrap()
            }
        };
        self.set_id(id);
    }
}

impl MedalObject<Connection> for Taskgroup {
    fn save(&mut self, conn: &Connection) {
        if let Some(first_task) = self.tasks.get(0) {
            let query = "SELECT taskgroup.id
                         FROM taskgroup
                         JOIN task
                         ON task.taskgroup = taskgroup.id
                         WHERE contest = $1
                         AND task.location = $2";
            conn.query_map_one(query, &[&self.contest, &first_task.location], |row| row.get(0))
                .unwrap_or(None)
192
                .map(|id| {
193
194
195
196
197
198
199
200
                    self.set_id(id);
                })
                .unwrap_or(()); // Err means no entry yet and is expected result
        }

        let id = match self.get_id() {
            Some(id) => {
                let query = "UPDATE taskgroup
201
202
203
                             SET contest = $1, name = $2, active = $3, positionalnumber = $4
                             WHERE id = $5";
                conn.execute(query, &[&self.contest, &self.name, &self.active, &self.positionalnumber, &id]).unwrap();
204
205
206
                id
            }
            None => {
207
208
209
                let query = "INSERT INTO taskgroup (contest, name, active, positionalnumber)
                             VALUES ($1, $2, $3, $4)";
                conn.execute(query, &[&self.contest, &self.name, &self.active, &self.positionalnumber]).unwrap();
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
                conn.get_last_id().unwrap()
            }
        };
        self.set_id(id);
        for mut task in &mut self.tasks {
            task.taskgroup = id;
            task.save(conn);
        }
    }
}

impl MedalObject<Connection> for Contest {
    fn save(&mut self, conn: &Connection) {
        let query = "SELECT id
                     FROM contest
                     WHERE location = $1
                     AND filename = $2";
        conn.query_map_one(query, &[&self.location, &self.filename], |row| row.get(0))
            .unwrap_or(None)
229
            .map(|id| {
230
231
232
233
234
235
236
                self.set_id(id);
            })
            .unwrap_or(()); // Err means no entry yet and is expected result

        let id = match self.get_id() {
            Some(id) => {
                let query = "UPDATE contest
237
238
                             SET location = $2,filename = $3, name = $4, duration = $5, public = $6, start_date = $7,
                                 end_date = $8, min_grade = $9, max_grade = $10, positionalnumber = $11,
239
                                 requires_login = $12, secret = $13, message = $14
240
                             WHERE id = $1";
241
                conn.execute(query,
242
243
                             &[&id,
                               &self.location,
244
245
246
247
248
249
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
                               &self.end,
250
251
                               &self.min_grade,
                               &self.max_grade,
252
                               &self.positionalnumber,
253
                               &self.requires_login,
254
255
                               &self.secret,
                               &self.message])
256
257
258
259
                    .unwrap();
                id
            }
            None => {
260
                let query = "INSERT INTO contest (location, filename, name, duration, public, start_date, end_date,
261
262
                                                  min_grade, max_grade, positionalnumber, requires_login, secret, message)
                             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)";
263
264
265
266
267
268
269
                conn.execute(query,
                             &[&self.location,
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
270
271
                               &self.end,
                               &self.min_grade,
272
                               &self.max_grade,
273
274
                               &self.positionalnumber,
                               &self.requires_login,
275
276
                               &self.secret,
                               &self.message])
277
278
279
280
281
282
283
284
285
286
287
288
                    .unwrap();
                conn.get_last_id().unwrap()
            }
        };
        self.set_id(id);
        for mut taskgroup in &mut self.taskgroups {
            taskgroup.contest = id;
            taskgroup.save(conn);
        }
    }
}

289
impl MedalConnection for Connection {
290
291
292
293
294
295
    fn dbtype(&self) -> &'static str { "postgres" }

    fn migration_already_applied(&self, name: &str) -> bool {
        let create_string = "CREATE TABLE IF NOT EXISTS migrations (name TEXT PRIMARY KEY);";
        self.execute(create_string, &[]).unwrap();

296
297
        let query = "SELECT name FROM migrations WHERE name = $1";
        self.exists(query, &[&name])
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
    }

    fn apply_migration(&mut self, name: &str, contents: &str) {
        print!("Applying migration `{}` … ", name);

        let tx = self.transaction().unwrap();

        tx.batch_execute(&contents).unwrap();
        tx.execute("INSERT INTO migrations (name) VALUES ($1)", &[&name]).unwrap();

        tx.commit().unwrap();

        println!("OK.");
    }

    // fn get_session<T: ToSql>(&self, key: T, keyname: &str) -> Option<SessionUser> {
    fn get_session(&self, key: &str) -> Option<SessionUser> {
315
316
        let query = "SELECT id, csrf_token, last_login, last_activity, permanent_login, username, password, salt,
                            logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname, street,
317
                            zip, city, nation, grade, sex, is_admin, is_teacher, managed_by, oauth_provider, oauth_foreign_id
318
319
                     FROM session
                     WHERE session_token = $1";
320
321
322
323
324
325
326
327
328
        let session = self.query_map_one(query, &[&key], |row| SessionUser { id: row.get(0),
                                                                             session_token: Some(key.to_string()),
                                                                             csrf_token: row.get(1),
                                                                             last_login: row.get(2),
                                                                             last_activity: row.get(3),
                                                                             permanent_login: row.get(4),

                                                                             username: row.get(5),
                                                                             password: row.get(6),
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
                                                                             salt: row.get(7),
                                                                             logincode: row.get(8),
                                                                             email: row.get(9),
                                                                             email_unconfirmed: row.get(10),
                                                                             email_confirmationcode: row.get(11),

                                                                             firstname: row.get(12),
                                                                             lastname: row.get(13),
                                                                             street: row.get(14),
                                                                             zip: row.get(15),
                                                                             city: row.get(16),
                                                                             nation: row.get(17),
                                                                             grade: row.get(18),
                                                                             sex: row.get(19),

344
345
346
                                                                             is_admin: row.get(20),
                                                                             is_teacher: row.get(21),
                                                                             managed_by: row.get(22),
347

348
349
                                                                             oauth_provider: row.get(23),
                                                                             oauth_foreign_id: row.get(24) })
350
                          .ok()??;
351

352
        let duration = Duration::hours(12);
353
        let now = time::get_time();
354

355
356
        if let Some(last_activity) = session.last_activity {
            if now - last_activity < duration {
357
358
359
360
                let query = "UPDATE session
                             SET last_activity = $1
                             WHERE id = $2";
                self.execute(query, &[&now, &session.id]).unwrap();
361
                return Some(session);
362
            } else {
363
364
365
366
                // Session timed out
                // Should remove session token from session
                return None;
            }
367
        }
368
369
370
        // last_activity undefined
        // TODO: What should happen here?
        None
371
372
    }
    fn save_session(&self, session: SessionUser) {
373
374
375
376
377
378
379
380
381
382
383
384
        self.execute("UPDATE session
                      SET username = $1,
                          password = $2,
                          salt = $3,
                          logincode = $4,
                          firstname = $5,
                          lastname = $6,
                          street = $7,
                          zip = $8,
                          city = $9,
                          grade = $10,
                          sex = $11,
385
386
                          is_admin = $12,
                          is_teacher = $13,
387
388
389
390
                          permanent_login = $14,
                          email = $15,
                          email_unconfirmed = $16
                      WHERE id = $17",
391
392
393
394
395
396
397
398
399
400
                     &[&session.username,
                       &session.password,
                       &session.salt,
                       &session.logincode,
                       &session.firstname,
                       &session.lastname,
                       &session.street,
                       &session.zip,
                       &session.city,
                       &session.grade,
401
                       &session.sex,
402
                       &session.is_admin,
403
                       &session.is_teacher,
404
                       &session.permanent_login,
405
406
                       &session.email,
                       &session.email_unconfirmed,
407
408
409
410
                       &session.id])
            .unwrap();
    }
    fn new_session(&self, session_token: &str) -> SessionUser {
411
        let csrf_token = helpers::make_csrf_token();
412
413

        let now = time::get_time();
414
        let query = "INSERT INTO session (session_token, csrf_token, last_activity, permanent_login, grade, sex,
415
                                          is_teacher)
416
417
                     VALUES ($1, $2, $3, $4, $5, $6, $7)";
        self.execute(query, &[&session_token, &csrf_token, &now, &false, &0, &None::<i32>, &false]).unwrap();
418

419
420
        let id = self.get_last_id().expect("Expected to get last row id");

421
        SessionUser::minimal(id, session_token.to_owned(), csrf_token)
422
423
    }
    fn get_session_or_new(&self, key: &str) -> SessionUser {
424
425
426
        let query = "UPDATE session
                     SET session_token = $1
                     WHERE session_token = $2";
427
428
429
        self.get_session(&key).ensure_alive().unwrap_or_else(|| {
                                                 // TODO: Factor this out in own function
                                                 // TODO: Should a new session key be generated every time?
430
                                                 self.execute(query, &[&Option::<String>::None, &key]).unwrap();
431
432
                                                 self.new_session(&key)
                                             })
433
434
435
    }

    fn get_user_by_id(&self, user_id: i32) -> Option<SessionUser> {
436
        let query = "SELECT session_token, csrf_token, last_login, last_activity, permanent_login, username, password,
437
                            salt, logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname,
438
                            street, zip, city, nation, grade, sex, is_admin, is_teacher, managed_by, oauth_provider,
439
                            oauth_foreign_id
440
441
                     FROM session
                     WHERE id = $1";
442
443
444
445
446
447
448
449
450
        self.query_map_one(query, &[&user_id], |row| SessionUser { id: user_id,
                                                                   session_token: row.get(0),
                                                                   csrf_token: row.get(1),
                                                                   last_login: row.get(2),
                                                                   last_activity: row.get(3),
                                                                   permanent_login: row.get(4),

                                                                   username: row.get(5),
                                                                   password: row.get(6),
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
                                                                   salt: row.get(7),
                                                                   logincode: row.get(8),
                                                                   email: row.get(9),
                                                                   email_unconfirmed: row.get(10),
                                                                   email_confirmationcode: row.get(11),

                                                                   firstname: row.get(12),
                                                                   lastname: row.get(13),
                                                                   street: row.get(14),
                                                                   zip: row.get(15),
                                                                   city: row.get(16),
                                                                   nation: row.get(17),
                                                                   grade: row.get(18),
                                                                   sex: row.get(19),

466
467
468
                                                                   is_admin: row.get(20),
                                                                   is_teacher: row.get(21),
                                                                   managed_by: row.get(22),
469

470
471
                                                                   oauth_provider: row.get(23),
                                                                   oauth_foreign_id: row.get(24) })
472
            .ok()?
473
474
475
476
477
478
479
480
481
482
    }

    fn get_user_and_group_by_id(&self, user_id: i32) -> Option<(SessionUser, Option<Group>)> {
        let session = self.get_user_by_id(user_id)?;

        let group_id = match session.managed_by {
            Some(id) => id,
            None => return Some((session, None)),
        };

483
484
485
        let query = "SELECT name, groupcode, tag, admin
                     FROM usergroup
                     WHERE id = $1";
486
487
488
489
490
491
492
493
494
        let res = self.query_map_one(query, &[&group_id], |row| Group { id: Some(group_id),
                                                                        name: row.get(0),
                                                                        groupcode: row.get(1),
                                                                        tag: row.get(2),
                                                                        admin: row.get(3),
                                                                        members: Vec::new() })
                      .ok()?;
        match res {
            Some(group) => Some((session, Some(group))),
495
496
497
498
499
500
            _ => Some((session, None)),
        }
    }

    //TODO: use session
    fn login(&self, _session: Option<&str>, username: &str, password: &str) -> Result<String, ()> {
501
502
503
504
        let query = "SELECT id, password, salt
                     FROM session
                     WHERE username = $1";
        self.query_map_one(query, &[&username], |row| {
505
506
507
508
                let (id, password_hash, salt): (i32, Option<String>, Option<String>) =
                    (row.get(0), row.get(1), row.get(2));

                //password_hash ist das, was in der Datenbank steht
509
                if helpers::verify_password(&password,
510
511
                                            &salt.ok_or_else(|| println!("salt from database empty"))?,
                                            &password_hash.ok_or_else(|| println!("password from database empty"))?)
512
513
514
515
                {
                    // TODO: fail more pleasantly
                    // Login okay, update session now!

516
517
                    let session_token = helpers::make_session_token();
                    let csrf_token = helpers::make_csrf_token();
518
519
                    let now = time::get_time();

520
521
522
                    let query = "UPDATE session
                                 SET session_token = $1, csrf_token = $2, last_login = $3, last_activity = $3
                                 WHERE id = $4";
523
                    self.execute(query, &[&session_token, &csrf_token, &now, &id]).unwrap();
524
525
526
527
528

                    Ok(session_token)
                } else {
                    Err(())
                }
529
530
531
            })
            .map_err(|_| ())?
            .ok_or(())?
532
533
534
535
    }

    //TODO: use session
    fn login_with_code(&self, _session: Option<&str>, logincode: &str) -> Result<String, ()> {
536
537
538
539
        if logincode == "" {
            return Err(());
        }

540
541
542
543
        let query = "SELECT id
                     FROM session
                     WHERE logincode = $1";
        self.query_map_one(query, &[&logincode], |row| {
544
545
546
                // Login okay, update session now!
                let id: i32 = row.get(0);

547
548
                let session_token = helpers::make_session_token();
                let csrf_token = helpers::make_csrf_token();
549
550
                let now = time::get_time();

551
552
553
                let query = "UPDATE session
                             SET session_token = $1, csrf_token = $2, last_login = $3, last_activity = $3
                             WHERE id = $4";
554
                self.execute(query, &[&session_token, &csrf_token, &now, &id]).unwrap();
555

556
                session_token
557
558
559
            })
            .map_err(|_| ())?
            .ok_or(())
560
561
562
    }

    //TODO: use session
563
564
    fn login_foreign(&self, _session: Option<&str>, provider_id: &str, foreign_id: &str,
                     (is_teacher, is_admin, firstname, lastname, sex): (bool, bool, &str, &str, Option<i32>))
565
                     -> Result<(String, Option<time::Timespec>), ()>
566
    {
567
568
        let session_token = helpers::make_session_token();
        let csrf_token = helpers::make_csrf_token();
569
570
        let now = time::get_time();

571
        let query = "SELECT id, last_activity
572
                     FROM session
573
574
                     WHERE oauth_foreign_id = $1
                           AND oauth_provider = $2";
575
576
577
578
        match self.query_map_one(query, &[&foreign_id, &provider_id], |row| -> (i32, time::Timespec) {
                      (row.get(0), row.get(1))
                  }) {
            Ok(Some((id, last_activity))) => {
579
                let query = "UPDATE session
580
                             SET session_token = $1, csrf_token = $2, last_login = $3, last_activity = $3,
581
582
                                 is_teacher = $4, is_admin = $5,  firstname = $6, lastname = $7, sex = $8
                             WHERE id = $9";
583
584
585
586
587
588
589
590
591
592
593
                self.execute(query,
                             &[&session_token,
                               &csrf_token,
                               &now,
                               &is_teacher,
                               &is_admin,
                               &firstname,
                               &lastname,
                               &sex,
                               &id])
                    .unwrap();
594

595
                Ok((session_token, Some(last_activity)))
596
597
598
            }
            // Add!
            _ => {
599
                let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity,
600
                                                  permanent_login, grade, sex, is_teacher, is_admin, oauth_foreign_id,
601
                                                  oauth_provider, firstname, lastname)
602
                             VALUES ($1, $2, $3, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)";
603
604
605
606
607
                self.execute(query,
                             &[&session_token,
                               &csrf_token,
                               &now,
                               &false,
608
                               &(if is_teacher { 255 } else { 0 }),
609
                               &sex,
610
                               &is_teacher,
611
                               &is_admin,
612
                               &foreign_id,
613
                               &provider_id,
614
615
616
                               &firstname,
                               &lastname])
                    .unwrap();
617

618
                Ok((session_token, None))
619
620
621
622
623
624
            }
        }
    }

    //TODO: use session
    fn create_user_with_groupcode(&self, _session: Option<&str>, groupcode: &str) -> Result<String, ()> {
625
626
627
628
        if groupcode == "" {
            return Err(());
        }

629
630
631
        let query = "SELECT id
                     FROM usergroup
                     WHERE groupcode = $1";
632
633
        let group_id =
            self.query_map_one(query, &[&groupcode], |row| -> i32 { row.get(0) }).map_err(|_| ())?.ok_or(())?;
634

635
636
637
        // Login okay, create session!
        let session_token = helpers::make_session_token();
        let csrf_token = helpers::make_csrf_token();
638
        let login_code = helpers::make_login_code(); // TODO: check for collisions
639
        let now = time::get_time();
640

641
        let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity, permanent_login,
642
                                          logincode, grade, sex, is_teacher, managed_by)
643
                     VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)";
644
645
646
647
648
649
650
651
652
653
654
655
        self.execute(query,
                     &[&session_token,
                       &csrf_token,
                       &now,
                       &now,
                       &false,
                       &login_code,
                       &0,
                       &None::<i32>,
                       &false,
                       &group_id])
            .unwrap();
656

657
        Ok(session_token)
658
659
    }

Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
660
    fn create_group_with_users(&self, mut group: Group) {
661
662
663
664
665
666
        // Generate group ID:
        group.save(self);

        for user in group.members {
            let csrf_token = helpers::make_csrf_token();
            let login_code = helpers::make_login_code(); // TODO: check for collisions
Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
667

668
            let query = "INSERT INTO session (firstname, lastname, csrf_token, permanent_login, logincode, grade, sex,
669
                                              is_teacher, managed_by)
670
                         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)";
671
672
673
674
675
676
677
            self.execute(query,
                         &[&user.firstname,
                           &user.lastname,
                           &csrf_token,
                           &false,
                           &login_code,
                           &user.grade,
678
                           &None::<i32>,
679
680
681
                           &false,
                           &group.id])
                .unwrap();
682
        }
683
684
    }

685
    fn logout(&self, session: &str) {
686
687
688
        let query = "UPDATE session
                     SET session_token = NULL
                     WHERE session_token = $1";
689
        self.execute(query, &[&session]).unwrap();
690
691
    }

Robert Czechowski's avatar
Robert Czechowski committed
692
693
    fn signup(&self, session_token: &str, username: &str, email: &str, password_hash: String, salt: &str)
              -> SignupResult {
694
695
696
        let mut session_user = self.get_session_or_new(&session_token);

        if session_user.is_logged_in() {
Robert Czechowski's avatar
Robert Czechowski committed
697
            return SignupResult::UserLoggedIn;
698
699
700
        }

        if let Ok(None) = self.query_map_one("SELECT username FROM session WHERE username = $1",
Robert Czechowski's avatar
Robert Czechowski committed
701
702
703
704
                                             &[&username],
                                             |row| -> Option<String> { row.get(0) })
        {
        } else {
705
            //This username already exists!
Robert Czechowski's avatar
Robert Czechowski committed
706
            return SignupResult::UsernameTaken;
707
708
        }
        if let Ok(None) = self.query_map_one("SELECT email, email_unconfirmed FROM session WHERE email = $1 OR email_unconfirmed = $1",
Robert Czechowski's avatar
Robert Czechowski committed
709
710
711
712
                                             &[&email],
                                             |row| -> (Option<String>, Option<String>) { (row.get(0), row.get(1)) })
        {
        } else {
713
            //This email already exists!
Robert Czechowski's avatar
Robert Czechowski committed
714
            return SignupResult::EmailTaken;
715
716
717
718
719
720
721
722
723
724
725
        }

        session_user.username = Some(username.to_string());
        session_user.email_unconfirmed = Some(email.to_string());
        session_user.password = Some(password_hash);
        session_user.salt = Some(salt.to_string());

        self.save_session(session_user);
        SignupResult::SignedUp
    }

726
727
    fn load_submission(&self, session: &SessionUser, task: i32, subtask: Option<&str>) -> Option<Submission> {
        match subtask {
728
729
730
731
732
733
734
735
            None => {
                let query = "SELECT id, grade, validated, nonvalidated_grade, value, date, needs_validation
                             FROM submission
                             WHERE task = $1
                             AND session = $2
                             ORDER BY id DESC
                             LIMIT 1";
                self.query_map_one(query, &[&task, &session.id], |row| Submission { id: Some(row.get(0)),
Robert Czechowski's avatar
Robert Czechowski committed
736
                                                                                    task,
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
                                                                                    session_user: session.id,
                                                                                    grade: row.get(1),
                                                                                    validated: row.get(2),
                                                                                    nonvalidated_grade: row.get(3),
                                                                                    subtask_identifier: None,
                                                                                    value: row.get(4),
                                                                                    date: row.get(5),
                                                                                    needs_validation: row.get(6) })
                    .ok()?
            }
            Some(subtask_id) => {
                let query = "SELECT id, grade, validated, nonvalidated_grade, value, date, needs_validation
                             FROM submission
                             WHERE task = $1
                             AND session = $2
                             AND subtask_identifier = $3
                             ORDER BY id DESC
                             LIMIT 1";
                self.query_map_one(query, &[&task, &session.id, &subtask_id], |row| {
                        Submission { id: Some(row.get(0)),
Robert Czechowski's avatar
Robert Czechowski committed
757
                                     task,
758
759
760
761
762
763
764
765
766
767
768
                                     session_user: session.id,
                                     grade: row.get(1),
                                     validated: row.get(2),
                                     nonvalidated_grade: row.get(3),
                                     subtask_identifier: Some(subtask_id.to_string()),
                                     value: row.get(4),
                                     date: row.get(5),
                                     needs_validation: row.get(6) }
                    })
                    .ok()?
            }
769
770
        }
    }
771
772
773
774
775
776
777
778
    fn get_all_submissions(&self, session_id: i32, task: i32, subtask: Option<&str>) -> Vec<Submission> {
        match subtask {
            None => {
                let query = "SELECT id, grade, validated, nonvalidated_grade, value, date, needs_validation
                             FROM submission
                             WHERE task = $1
                             AND session = $2";
                self.query_map_many(query, &[&task, &session_id], |row| Submission { id: Some(row.get(0)),
Robert Czechowski's avatar
Robert Czechowski committed
779
                                                                                     task,
780
781
782
783
784
785
786
                                                                                     session_user: session_id,
                                                                                     grade: row.get(1),
                                                                                     validated: row.get(2),
                                                                                     nonvalidated_grade: row.get(3),
                                                                                     subtask_identifier: None,
                                                                                     value: row.get(4),
                                                                                     date: row.get(5),
787
788
789
                                                                                     needs_validation: row.get(6) })
                    .unwrap()
            }
790
            _ => unimplemented!(),
791
792
        }
    }
793
794
795
796
797
798
799
800
801
802
803
    fn submit_submission(&self, mut submission: Submission) {
        submission.save(self);

        let mut grade = self.get_grade_by_submission(submission.id.unwrap());
        if grade.grade.is_none() || submission.grade > grade.grade.unwrap() {
            grade.grade = Some(submission.grade);
            grade.validated = false;
            grade.save(self);
        }
    }
    fn get_grade_by_submission(&self, submission_id: i32) -> Grade {
804
805
806
807
808
809
        let query = "SELECT grade.taskgroup, grade.session, grade.grade, grade.validated
                     FROM grade
                     JOIN task ON grade.taskgroup = task.taskgroup
                     JOIN submission ON task.id = submission.task
                     AND grade.session = submission.session
                     WHERE submission.id = $1";
810
811
812
813
814
815
816
        self.query_map_one(query, &[&submission_id], |row| Grade { taskgroup: row.get(0),
                                                                   user: row.get(1),
                                                                   grade: row.get(2),
                                                                   validated: row.get(3) })
            .unwrap_or(None)
            .unwrap_or_else(|| {
                let query = "SELECT task.taskgroup, submission.session
817
818
819
                         FROM submission
                         JOIN task ON task.id = submission.task
                         WHERE submission.id = $1";
820
821
822
823
824
825
826
                self.query_map_one(query, &[&submission_id], |row| Grade { taskgroup: row.get(0),
                                                                           user: row.get(1),
                                                                           grade: None,
                                                                           validated: false })
                    .unwrap()
                    .unwrap() // should this unwrap?
            })
827
828
829
830
    }

    fn get_contest_groups_grades(&self, session_id: i32, contest_id: i32)
                                 -> (Vec<String>, Vec<(Group, Vec<(UserInfo, Vec<Grade>)>)>) {
831
832
833
        let query = "SELECT id, name
                     FROM taskgroup
                     WHERE contest = $1
834
835
                     AND active = $2
                     ORDER BY positionalnumber";
836
        let tasknames: Vec<(i32, String)> =
837
            self.query_map_many(query, &[&contest_id, &true], |row| (row.get(0), row.get(1))).unwrap();
838

839
840
841
842
843
844
845
        let mut taskindex: ::std::collections::BTreeMap<i32, usize> = ::std::collections::BTreeMap::new();

        let n_tasks = tasknames.len();
        for (index, (i, _)) in tasknames.iter().enumerate() {
            taskindex.insert(*i, index);
        }

846
847
        let query = "SELECT grade.taskgroup, grade.session, grade.grade, grade.validated, usergroup.id, usergroup.name,
                            usergroup.groupcode, usergroup.tag, student.id, student.username, student.logincode,
848
                            student.firstname, student.lastname, student.grade AS sgrade
849
850
851
852
853
854
                     FROM grade
                     JOIN taskgroup ON grade.taskgroup = taskgroup.id
                     JOIN session AS student ON grade.session = student.id
                     JOIN usergroup ON student.managed_by = usergroup.id
                     WHERE usergroup.admin = $1
                     AND taskgroup.contest = $2
855
                     AND taskgroup.active = $3
856
857
                     ORDER BY usergroup.id, sgrade, student.lastname, student.firstname, student.id,
                              taskgroup.positionalnumber";
858
        let gradeinfo =
859
            self.query_map_many(query, &[&session_id, &contest_id, &true], |row| {
860
861
862
863
864
865
866
867
868
869
870
                    (Grade { taskgroup: row.get(0), user: row.get(1), grade: row.get(2), validated: row.get(3) },
                     Group { id: Some(row.get(4)),
                             name: row.get(5),
                             groupcode: row.get(6),
                             tag: row.get(7),
                             admin: session_id,
                             members: Vec::new() },
                     UserInfo { id: row.get(8),
                                username: row.get(9),
                                logincode: row.get(10),
                                firstname: row.get(11),
871
                                lastname: row.get(12),
Robert Czechowski's avatar
Robert Czechowski committed
872
                                grade: row.get(13) })
873
874
875
                })
                .unwrap();
        let mut gradeinfo_iter = gradeinfo.iter();
876
877

        if let Some(t /*Ok((grade, mut group, mut userinfo))*/) = gradeinfo_iter.next() {
878
            let (grade, mut group, mut userinfo) = t.clone();
879
880
881
882
883
884

            let mut grades: Vec<Grade> = vec![Default::default(); n_tasks];
            let mut users: Vec<(UserInfo, Vec<Grade>)> = Vec::new();
            let mut groups: Vec<(Group, Vec<(UserInfo, Vec<Grade>)>)> = Vec::new();

            let index = grade.taskgroup;
885
            grades[taskindex[&index]] = grade;
886
887

            for ggu in gradeinfo_iter {
888
889
                let (g, gr, ui) = ggu;
                if gr.id != group.id {
890
891
                    users.push((userinfo, grades));
                    userinfo = ui.clone();
892
893
                    grades = vec![Default::default(); n_tasks];

894
895
                    groups.push((group, users));
                    group = gr.clone();
896
897
                    users = Vec::new();
                } else if ui.id != userinfo.id {
898
899
                    users.push((userinfo, grades));
                    userinfo = ui.clone();
900
                    grades = vec![Default::default(); n_tasks];
901
                }
902
                let index = g.taskgroup;
903
                grades[taskindex[&index]] = *g;
904
            }
905
906
            users.push((userinfo, grades));
            groups.push((group, users));
907
908
909
910
911
912
913

            (tasknames.iter().map(|(_, name)| name.clone()).collect(), groups)
        } else {
            (Vec::new(), Vec::new()) // should those be default filled?
        }
    }
    fn get_contest_user_grades(&self, session_token: &str, contest_id: i32) -> Vec<Grade> {
914
915
916
        let query = "SELECT id, name
                     FROM taskgroup
                     WHERE contest = $1
917
918
                     AND active = $2
                     ORDER BY positionalnumber";
919
        let tasknames: Vec<(i32, String)> =
920
            self.query_map_many(query, &[&contest_id, &true], |row| (row.get(0), row.get(1))).unwrap();
921
922
923
924
925
926
927
        let mut taskindex: ::std::collections::BTreeMap<i32, usize> = ::std::collections::BTreeMap::new();

        let n_tasks = tasknames.len();
        for (index, (i, _)) in tasknames.iter().enumerate() {
            taskindex.insert(*i, index);
        }

928
929
930
931
932
933
        let query = "SELECT grade.taskgroup, grade.session, grade.grade, grade.validated
                     FROM grade
                     JOIN taskgroup ON grade.taskgroup = taskgroup.id
                     JOIN session ON session.id = grade.session
                     WHERE session.session_token = $1
                     AND taskgroup.contest = $2
934
935
                     AND taskgroup.active = $3
                     ORDER BY taskgroup.positionalnumber";
936
        let gradeinfo =
937
            self.query_map_many(query, &[&session_token, &contest_id, &true], |row| Grade { taskgroup: row.get(0),
Robert Czechowski's avatar
Robert Czechowski committed
938
939
940
                                                                                            user: row.get(1),
                                                                                            grade: row.get(2),
                                                                                            validated: row.get(3) })
941
942
                .unwrap();
        let gradeinfo_iter = gradeinfo.iter();
943
944
945
946
947

        let mut grades: Vec<Grade> = vec![Default::default(); n_tasks];

        for g in gradeinfo_iter {
            let index = g.taskgroup;
948
            grades[taskindex[&index]] = *g;
949
950
951
952
953
954
        }

        grades
    }

    fn get_taskgroup_user_grade(&self, session_token: &str, taskgroup_id: i32) -> Grade {
955
        let query = "SELECT grade.taskgroup, grade.session, grade.grade, grade.validated
956
957
958
959
                     FROM grade
                     JOIN session ON session.id = grade.session
                     WHERE session.session_token = $1
                     AND grade.taskgroup = $2";
960
961
962
963
964
965
        self.query_map_one(query, &[&session_token, &taskgroup_id], |row| Grade { taskgroup: row.get(0),
                                                                                  user: row.get(1),
                                                                                  grade: row.get(2),
                                                                                  validated: row.get(3) })
            .unwrap_or(None)
            .unwrap_or_default()
966
967
    }

968
    /* Warning: This function makes no use of rusts type safety. Handle with care when changeing */
969
970
    fn export_contest_results_to_file(&self, contest_id: i32, taskgroups: &[(i32, String)], filename: &str) {
        use std::fs::OpenOptions;
971
        let file = OpenOptions::new().write(true).create(true).truncate(true).open(filename).unwrap();
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
        let mut headers = vec!["id",
                               "username",
                               "logincode",
                               "oauth_foreign_id",
                               "oauth_provider",
                               "firstname",
                               "lastname",
                               "grade",
                               "sex",
                               "is_teacher",
                               "group_id",
                               "group_name",
                               "group_tag",
                               "teacher_id",
                               "teacher_firstname",
                               "teacher_lastname",
                               "teacher_oauth_foreign_id",
                               "teacher_oauth_provider",
                               "contest_id",
                               "start_date"];
992
993
994

        let mut select_part = String::new();
        let mut join_part = String::new();
995
996
997

        let mut join_params = gen_tosql_vector();

998
        join_params.push(&contest_id);
999
1000

        for (n, (id, name)) in taskgroups.iter().enumerate() {
1001
1002
1003
1004
1005
            select_part.push_str(&format!(",\n g{}.grade ", n));
            join_part.push_str(&format!("\n LEFT JOIN grade AS g{} ON session.id = g{}.session AND g{}.taskgroup = ${} ", n, n, n, n + 2));
            join_params.push(id);
            headers.push(&name);
        }
1006

1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
        let query = format!("SELECT session.id,
                                    session.username,
                                    session.logincode,
                                    session.oauth_foreign_id,
                                    session.oauth_provider,
                                    session.firstname,
                                    session.lastname,
                                    session.grade,
                                    session.sex,
                                    session.is_teacher,
                                    session.managed_by,
                                    usergroup.name,
                                    usergroup.tag,
                                    teacher.id,
                                    teacher.firstname,
                                    teacher.lastname,
                                    teacher.oauth_foreign_id,
                                    teacher.oauth_provider,
                                    participation.contest,
                                    participation.start_date
                                    {}
                             FROM participation
                             JOIN session ON participation.session = session.id
                             {}
                             LEFT JOIN usergroup ON session.managed_by = usergroup.id
                             LEFT JOIN session AS teacher ON usergroup.admin = teacher.id
1033
1034
                             WHERE participation.contest = $1",
                            select_part, join_part);
1035
1036

        use csv::Writer;
1037
        let mut wtr = Writer::from_writer(file);
1038
1039
        wtr.serialize(&headers).unwrap();
        wtr.flush().unwrap();
1040

1041
1042
        let file = wtr.into_inner().unwrap();
        let mut wtr = Writer::from_writer(file);
1043
1044
1045
1046
1047
1048

        self.query_map_many(&query, join_params.as_slice(), |row| {
                let mut points = Vec::new();
                for i in 20..20 + taskgroups.len() {
                    points.push(row.get::<_, Option<i32>>(i));
                }
1049
1050
                // Serialized as several tuples because Serde only supports tuples up to a certain length
                // (16 according to https://docs.serde.rs/serde/trait.Deserialize.html)
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
                wtr.serialize(((row.get::<_, i32>(0),
                                row.get::<_, Option<String>>(1),
                                row.get::<_, Option<String>>(2),
                                row.get::<_, Option<String>>(3),
                                row.get::<_, Option<String>>(4),
                                row.get::<_, Option<String>>(5),
                                row.get::<_, Option<String>>(6),
                                row.get::<_, i32>(7),
                                row.get::<_, Option<i32>>(8),
                                row.get::<_, bool>(9)),
                               (row.get::<_, Option<i32>>(10),
                                row.get::<_, Option<String>>(11),
                                row.get::<_, Option<String>>(12),
                                row.get::<_, Option<i32>>(13),
                                row.get::<_, Option<String>>(14),
                                row.get::<_, Option<String>>(15),
                                row.get::<_, Option<String>>(16),
                                row.get::<_, Option<String>>(17)),
                               row.get::<_, Option<i32>>(18),
1070
1071
                               row.get::<_, Option<self::time::Timespec>>(19)
                                  .map(|ts| self::time::strftime("%FT%T%z", &self::time::at(ts)).unwrap()),
1072
1073
1074
1075
                               points))
                   .unwrap();
            })
            .unwrap();
1076
        wtr.flush().unwrap();
1077
1078
    }

1079
    fn get_contest_list(&self) -> Vec<Contest> {
1080
        let query = "SELECT id, location, filename, name, duration, public, start_date, end_date, min_grade, max_grade,
1081
                            positionalnumber, requires_login, secret, message
1082
                     FROM contest
1083
                     ORDER BY positionalnumber";
1084
1085
1086
1087
1088
1089
1090
1091
        self.query_map_many(query, &[], |row| Contest { id: Some(row.get(0)),
                                                        location: row.get(1),
                                                        filename: row.get(2),
                                                        name: row.get(3),
                                                        duration: row.get(4),
                                                        public: row.get(5),
                                                        start: row.get(6),
                                                        end: row.get(7),
1092
1093
                                                        min_grade: row.get(8),
                                                        max_grade: row.get(9),
1094
                                                        positionalnumber: row.get(10),
1095
1096
                                                        requires_login: row.get(11),
                                                        secret: row.get(12),
1097
                                                        message: row.get(13),
1098
1099
                                                        taskgroups: Vec::new() })
            .unwrap()
1100
1101
1102
    }

    fn get_contest_by_id(&self, contest_id: i32) -> Contest {
1103
        let query = "SELECT location, filename, name, duration, public, start_date, end_date, min_grade, max_grade,
1104
                            requires_login, secret, message
1105
1106
                     FROM contest
                     WHERE id = $1";
1107
1108
1109
1110
1111
1112
1113
1114
        self.query_map_one(query, &[&contest_id], |row| Contest { id: Some(contest_id),
                                                                  location: row.get(0),
                                                                  filename: row.get(1),
                                                                  name: row.get(2),
                                                                  duration: row.get(3),
                                                                  public: row.get(4),
                                                                  start: row.get(5),
                                                                  end: row.get(6),
1115
1116
                                                                  min_grade: row.get(7),
                                                                  max_grade: row.get(8),
1117
                                                                  positionalnumber: None,
1118
1119
                                                                  requires_login: row.get(9),
                                                                  secret: row.get(10),
1120
                                                                  message: row.get(11),
1121
                                                                  taskgroups: Vec::new() })
1122
1123
1124
1125
1126
            .unwrap()
            .unwrap() // TODO: Should return Option?
    }

    fn get_contest_by_id_complete(&self, contest_id: i32) -> Contest {
1127
        let query = "SELECT contest.location, contest.filename, contest.name, contest.duration, contest.public,
1128
                            contest.start_date, contest.end_date, contest.min_grade, contest.max_grade,
1129
1130
1131
                            contest.requires_login, contest.secret, contest.message,
                            taskgroup.id, taskgroup.name,
                            task.id, task.location, task.stars
1132
1133
1134
1135
                     FROM contest
                     JOIN taskgroup ON contest.id = taskgroup.contest
                     JOIN task ON taskgroup.id = task.taskgroup
                     WHERE contest.id = $1
1136
                     AND taskgroup.active = $2
1137
                     ORDER BY taskgroup.positionalnumber";
1138
        let taskgroupcontest =
1139
            self.query_map_many(query, &[&contest_id, &true], |row| {
1140
1141
1142
1143
1144
1145
1146
1147
                    (Contest { id: Some(contest_id),
                               location: row.get(0),
                               filename: row.get(1),
                               name: row.get(2),
                               duration: row.get(3),
                               public: row.get(4),
                               start: row.get(5),
                               end: row.get(6),
1148
1149
                               min_grade: row.get(7),
                               max_grade: row.get(8),
1150
                               positionalnumber: None,
1151
1152
                               requires_login: row.get(9),
                               secret: row.get(10),
1153
                               message: row.get(11),
1154
                               taskgroups: Vec::new() },
1155
                     Taskgroup { id: Some(row.get(12)),
1156
                                 contest: contest_id,
1157
                                 name: row.get(13),
1158
                                 active: true,
1159
1160
                                 positionalnumber: None,
                                 tasks: Vec::new() },
1161
                     Task { id: Some(row.get(14)), taskgroup: row.get(12), location: row.get(15), stars: row.get(16) })