Commit 5e0aba21 authored by Robert Czechowski's avatar Robert Czechowski
Browse files

rustfmt

parent 3c263651
Pipeline #210 failed with stage
in 5 minutes and 44 seconds
indent_style = "Visual"
use_small_heuristics = "Max"
fn_args_density = "Compressed"
fn_args_layout = "Compressed"
max_width = 120
newline_style = "Unix"
enum_discrim_align_threshold = 20
fn_single_line = true
where_single_line = true
\ No newline at end of file
where_single_line = true
use time;
use db_conn::MedalConnection;
use db_objects::{Grade, Group, Submission, Taskgroup};
use db_objects::SessionUser;
use db_objects::{Grade, Group, Submission, Taskgroup};
use helpers;
use oauth_provider::OauthProvider;
use webfw_iron::{json_val, to_json};
......@@ -563,9 +563,9 @@ pub fn group_csv<T: MedalConnection>(conn: &T, session_token: &str) -> MedalValu
Ok(("groupcsv".to_string(), data))
}
// TODO: Should creating the users and groups happen in a batch operation to speed things up?
pub fn upload_groups<T: MedalConnection>(conn: &T, session_token: &str, csrf_token: &str, group_data: &str) -> MedalResult<()> {
pub fn upload_groups<T: MedalConnection>(conn: &T, session_token: &str, csrf_token: &str, group_data: &str)
-> MedalResult<()> {
let session = conn.get_session(&session_token)
.ok_or(MedalError::AccessDenied)?
.ensure_logged_in()
......@@ -575,26 +575,35 @@ pub fn upload_groups<T: MedalConnection>(conn: &T, session_token: &str, csrf_tok
return Err(MedalError::CsrfCheckFailed);
}
println!("{}",group_data);
println!("{}", group_data);
let mut v: Vec<Vec<String>> = serde_json::from_str(group_data).or(Err(MedalError::AccessDenied))?; // TODO: Change error type
v.sort_unstable_by(|a, b| a[0].partial_cmp(&b[0]).unwrap());
let mut group_code = "".to_string();
let mut name = "".to_string();
let mut group =
Group { id: None, name: name.clone(), groupcode: group_code, tag: "".to_string(), admin: session.id, members: Vec::new() };
let mut group = Group { id: None,
name: name.clone(),
groupcode: group_code,
tag: "".to_string(),
admin: session.id,
members: Vec::new() };
for line in v {
if name != line[0] {
if name != "" {
conn.create_group_with_users(group);
}
}
name = line[0].clone();
group_code = helpers::make_group_code();
// TODO: check for collisions
group = Group { id: None, name: name.clone(), groupcode: group_code, tag: name.clone(), admin: session.id, members: Vec::new() };
group = Group { id: None,
name: name.clone(),
groupcode: group_code,
tag: name.clone(),
admin: session.id,
members: Vec::new() };
}
let mut user = SessionUser::group_user_stub();
......@@ -706,7 +715,16 @@ impl std::convert::Into<String> for ProfileStatus {
}
pub fn edit_profile<T: MedalConnection>(conn: &T, session_token: &str, user_id: Option<i32>, csrf_token: &str,
(firstname, lastname, street, zip, city, password, password_repeat, grade): (String, String,Option<String>,Option<String>,Option<String>,Option<String>,Option<String>,i32))
(firstname, lastname, street, zip, city, password, password_repeat, grade): (
String,
String,
Option<String>,
Option<String>,
Option<String>,
Option<String>,
Option<String>,
i32,
))
-> MedalResult<ProfileStatus>
{
let mut session = conn.get_session(&session_token)
......
......@@ -18,8 +18,7 @@ pub trait MedalConnection {
fn login(&self, session: Option<&str>, username: &str, password: &str) -> Result<String, ()>;
fn login_with_code(&self, session: Option<&str>, logincode: &str) -> Result<String, ()>;
fn login_foreign(&self, session: Option<&str>, foreign_id: &str, is_teacher: bool, firstname: &str,
lastname: &str)
fn login_foreign(&self, session: Option<&str>, foreign_id: &str, is_teacher: bool, firstname: &str, lastname: &str)
-> Result<String, ()>;
fn create_user_with_groupcode(&self, session: Option<&str>, groupcode: &str) -> Result<String, ()>;
fn create_group_with_users(&self, group: Group);
......
......@@ -11,12 +11,14 @@ use db_objects::*;
use helpers;
trait Queryable {
fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F) -> postgres::Result<Option<T>>
fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F)
-> postgres::Result<Option<T>>
where F: FnOnce(postgres::rows::Row<'_>) -> T;
}
impl Queryable for Connection {
fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F) -> postgres::Result<Option<T>>
fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F)
-> postgres::Result<Option<T>>
where F: FnOnce(postgres::rows::Row<'_>) -> T {
let rows = self.query(sql, params)?;
......@@ -134,10 +136,12 @@ impl MedalConnection for Connection {
let csrf_token = helpers::make_csrf_token();
let now = time::get_time();
self.execute("INSERT INTO session (session_token, csrf_token, last_activity, permanent_login, grade, is_teacher)
self.execute(
"INSERT INTO session (session_token, csrf_token, last_activity, permanent_login, grade, is_teacher)
VALUES ($1, $2, $3, FALSE, 0, FALSE)",
&[&session_token, &csrf_token, &now])
.unwrap();
&[&session_token, &csrf_token, &now],
)
.unwrap();
let id = self.query("SELECT lastval()", &[])
.unwrap()
......@@ -312,14 +316,14 @@ impl MedalConnection for Connection {
}
}
fn create_group_with_users(&self, mut group: Group) {
fn create_group_with_users(&self, mut group: Group) {
// 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
self.execute("INSERT INTO session (firstname, lastname, csrf_token, permanent_login, logincode, grade, is_teacher, managed_by) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", &[&user.firstname, &user.lastname, &csrf_token, &false, &login_code, &user.grade, &false, &group.id]).unwrap();
}
}
......@@ -887,8 +891,9 @@ impl MedalObject<Connection> for Contest {
conn.execute(
"INSERT INTO contest (location, filename, name, duration, public, start_date, end_date)
VALUES ($1, $2, $3, $4, $5, $6, $7)",
&[&self.location, &self.filename, &self.name,
&self.duration, &self.public, &self.start, &self.end]).unwrap();
&[&self.location, &self.filename, &self.name, &self.duration, &self.public, &self.start, &self.end],
)
.unwrap();
conn.query("SELECT lastval()", &[]).unwrap().iter().next().map(|row| -> i64 { row.get(0) }).unwrap()
as i32
}
......
......@@ -11,12 +11,14 @@ use db_objects::*;
use helpers;
trait Queryable {
fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn rusqlite::types::ToSql], f: F) -> rusqlite::Result<Option<T>>
fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn rusqlite::types::ToSql], f: F)
-> rusqlite::Result<Option<T>>
where F: FnOnce(&rusqlite::Row) -> T;
}
impl Queryable for Connection {
fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn rusqlite::types::ToSql], f: F) -> rusqlite::Result<Option<T>>
fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn rusqlite::types::ToSql], f: F)
-> rusqlite::Result<Option<T>>
where F: FnOnce(&rusqlite::Row) -> T {
let mut stmt = self.prepare(sql)?;
let mut rows = stmt.query(params)?;
......@@ -134,10 +136,12 @@ impl MedalConnection for Connection {
let csrf_token = helpers::make_csrf_token();
let now = time::get_time();
self.execute("INSERT INTO session_user (session_token, csrf_token, last_activity, permanent_login, grade, is_teacher)
self.execute(
"INSERT INTO session_user (session_token, csrf_token, last_activity, permanent_login, grade, is_teacher)
VALUES (?1, ?2, ?3, 0, 0, 0)",
&[&session_token, &csrf_token, &now])
.unwrap();
&[&session_token, &csrf_token, &now],
)
.unwrap();
let id = self.query_row("SELECT last_insert_rowid()", &[], |row| row.get(0)).unwrap();
SessionUser::minimal(id, session_token.to_owned(), csrf_token)
......@@ -300,7 +304,7 @@ impl MedalConnection for Connection {
_ => Err(()),
}
}
fn create_group_with_users(&self, mut group: Group) {
// Generate group ID:
group.save(self);
......@@ -308,7 +312,7 @@ impl MedalConnection for Connection {
for user in group.members {
let csrf_token = helpers::make_csrf_token();
let login_code = helpers::make_login_code(); // TODO: check for collisions
self.execute("INSERT INTO session_user (firstname, lastname, csrf_token, permanent_login, logincode, grade, is_teacher, managed_by) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", &[&user.firstname, &user.lastname, &csrf_token, &false, &login_code, &user.grade, &false, &group.id]).unwrap();
}
}
......@@ -534,8 +538,10 @@ impl MedalConnection for Connection {
}
fn get_contest_by_id(&self, contest_id: i32) -> Contest {
self.query_row("SELECT location, filename, name, duration, public, start_date, end_date FROM contest WHERE id = ?1", &[&contest_id], |row| {
Contest {
self.query_row(
"SELECT location, filename, name, duration, public, start_date, end_date FROM contest WHERE id = ?1",
&[&contest_id],
|row| Contest {
id: Some(contest_id),
location: row.get(0),
filename: row.get(1),
......@@ -545,8 +551,9 @@ impl MedalConnection for Connection {
start: row.get(5),
end: row.get(6),
taskgroups: Vec::new(),
}
}).unwrap()
},
)
.unwrap()
}
fn get_contest_by_id_complete(&self, contest_id: i32) -> Contest {
......@@ -860,8 +867,9 @@ impl MedalObject<Connection> for Contest {
conn.execute(
"INSERT INTO contest (location, filename, name, duration, public, start_date, end_date)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
&[&self.location, &self.filename, &self.name,
&self.duration, &self.public, &self.start, &self.end]).unwrap();
&[&self.location, &self.filename, &self.name, &self.duration, &self.public, &self.start, &self.end],
)
.unwrap();
conn.query_row("SELECT last_insert_rowid()", &[], |row| row.get(0)).unwrap()
}
};
......
......@@ -155,39 +155,40 @@ impl Contest {
impl SessionUser {
pub fn minimal(id: i32, session_token: String, csrf_token: String) -> Self {
SessionUser { id: id,
session_token: Some(session_token),
csrf_token: csrf_token,
last_login: None,
last_activity: None, // now?
// müssen die überhaupt außerhalb der datenbankabstraktion sichtbar sein?
permanent_login: false,
username: None,
password: None,
salt: None,
logincode: None,
email: None,
email_unconfirmed: None,
email_confirmationcode: None,
firstname: None,
lastname: None,
street: None,
zip: None,
city: None,
nation: None,
grade: 0,
is_teacher: false,
managed_by: None,
oauth_foreign_id: None,
oauth_provider: None,
// oauth_extra_data: Option<String>,
//pms_id: None,
//pms_school_id: None,
SessionUser {
id: id,
session_token: Some(session_token),
csrf_token: csrf_token,
last_login: None,
last_activity: None, // now?
// müssen die überhaupt außerhalb der datenbankabstraktion sichtbar sein?
permanent_login: false,
username: None,
password: None,
salt: None,
logincode: None,
email: None,
email_unconfirmed: None,
email_confirmationcode: None,
firstname: None,
lastname: None,
street: None,
zip: None,
city: None,
nation: None,
grade: 0,
is_teacher: false,
managed_by: None,
oauth_foreign_id: None,
oauth_provider: None,
// oauth_extra_data: Option<String>,
//pms_id: None,
//pms_school_id: None,
}
}
......@@ -219,8 +220,7 @@ impl SessionUser {
managed_by: None,
oauth_foreign_id: None,
oauth_provider: None,
}
oauth_provider: None }
}
pub fn is_alive(&self) -> bool {
......
......@@ -54,15 +54,13 @@ macro_rules! with_conn {
}
macro_rules! template_ok {
( $x:expr ) => {
{
let (template, data) = $x;
let mut resp = Response::new();
resp.set_mut(Template::new(&template, data)).set_mut(status::Ok);
Ok(resp)
}
};
( $x:expr ) => {{
let (template, data) = $x;
let mut resp = Response::new();
resp.set_mut(Template::new(&template, data)).set_mut(status::Ok);
Ok(resp)
}};
}
struct ErrorReporter;
......@@ -149,8 +147,15 @@ impl<'a, 'b> RequestSession for Request<'a, 'b> {
let new_session_key: String = thread_rng().sample_iter(&Alphanumeric).take(28).collect();
self.session().set(SessionToken { token: new_session_key }).unwrap();
Err(IronError { error: Box::new(SessionError { message: "No valid session found, redirecting to cookie page".to_string() }),
response: Response::with((status::Found, RedirectRaw(format!("/cookie?{}", self.url.path().join("/"))))) })
Err(IronError {
error: Box::new(SessionError {
message: "No valid session found, redirecting to cookie page".to_string(),
}),
response: Response::with((
status::Found,
RedirectRaw(format!("/cookie?{}", self.url.path().join("/"))),
)),
})
}
}
}
......@@ -539,7 +544,7 @@ fn group_post<C>(req: &mut Request) -> IronResult<Response>
//TODO: use result?
with_conn![core::modify_group, C, req, group_id, &session_token].aug(req)?;
Ok(Response::with((status::Found, Redirect(url_for!(req, "group", "groupid" => format!("{}",group_id))))))
}
......@@ -572,12 +577,11 @@ fn group_csv_upload<C>(req: &mut Request) -> IronResult<Response>
let (csrf_token, group_data) = {
let formdata = iexpect!(req.get_ref::<UrlEncodedBody>().ok());
(iexpect!(formdata.get("csrf_token"))[0].to_owned(),
iexpect!(formdata.get("group_data"))[0].to_owned())
(iexpect!(formdata.get("csrf_token"))[0].to_owned(), iexpect!(formdata.get("group_data"))[0].to_owned())
};
println!("{}",group_data);
println!("{}", group_data);
with_conn![core::upload_groups, C, req, &session_token, &csrf_token, &group_data].aug(req)?;
Ok(Response::with((status::Found, Redirect(url_for!(req, "groups")))))
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment