clean repo
This commit is contained in:
148
src/rest/mod.rs
148
src/rest/mod.rs
@ -1,148 +0,0 @@
|
||||
mod restday;
|
||||
mod restreg;
|
||||
mod restuser;
|
||||
|
||||
use std::ops::Deref;
|
||||
|
||||
use chrono::{Datelike, Duration, Local, NaiveDate};
|
||||
use rocket::{
|
||||
form::{self, Form, ValueField},
|
||||
fs::FileServer,
|
||||
http::{Cookie, CookieJar},
|
||||
request::FlashMessage,
|
||||
response::{Flash, Redirect},
|
||||
Build, Rocket, State,
|
||||
};
|
||||
use rocket_dyn_templates::{tera, Template};
|
||||
use sea_orm::{Database, DatabaseConnection};
|
||||
use sha3::{Digest, Sha3_256};
|
||||
|
||||
use super::models::{all::DayWithTrips, day, user};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct NaiveDateForm(NaiveDate);
|
||||
|
||||
impl<'v> rocket::form::FromFormField<'v> for NaiveDateForm {
|
||||
fn from_value(field: ValueField<'v>) -> form::Result<'v, NaiveDateForm> {
|
||||
let naivedate = chrono::NaiveDate::parse_from_str(field.value, "%Y-%m-%d").unwrap(); //TODO:
|
||||
//fixme
|
||||
Ok(NaiveDateForm(naivedate))
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for NaiveDateForm {
|
||||
type Target = NaiveDate;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[get("/?<all>")]
|
||||
async fn index(
|
||||
db: &State<DatabaseConnection>,
|
||||
user: user::Model,
|
||||
all: Option<String>,
|
||||
flash: Option<FlashMessage<'_>>,
|
||||
) -> Template {
|
||||
let mut data = Vec::new();
|
||||
|
||||
let mut show_next_n_days = 6;
|
||||
if all.is_some() && user.is_cox {
|
||||
let end_of_year = NaiveDate::from_ymd_opt(Local::now().year(), 12, 31).unwrap();
|
||||
show_next_n_days = end_of_year
|
||||
.signed_duration_since(Local::now().date_naive())
|
||||
.num_days();
|
||||
}
|
||||
|
||||
for i in 0..show_next_n_days {
|
||||
let date = (Local::now() + Duration::days(i)).date_naive();
|
||||
let day = day::Model::find_or_create_day(date, db.inner()).await;
|
||||
data.push(DayWithTrips::new(day, db.inner()).await);
|
||||
}
|
||||
|
||||
let mut context = tera::Context::new();
|
||||
|
||||
if let Some(msg) = flash {
|
||||
context.insert("flash", &msg.into_inner());
|
||||
}
|
||||
context.insert("data", &data);
|
||||
context.insert("user", &user);
|
||||
Template::render("index", context.into_json())
|
||||
}
|
||||
|
||||
#[get("/name")]
|
||||
fn name(flash: Option<FlashMessage<'_>>) -> Template {
|
||||
let mut context = tera::Context::new();
|
||||
|
||||
if let Some(msg) = flash {
|
||||
context.insert("flash", &msg.into_inner());
|
||||
}
|
||||
Template::render("name", context.into_json())
|
||||
}
|
||||
|
||||
#[derive(FromForm)]
|
||||
struct NameForm {
|
||||
name: String,
|
||||
pw: Option<String>,
|
||||
}
|
||||
|
||||
#[put("/name", data = "<name>")]
|
||||
async fn savename(
|
||||
name: Form<NameForm>,
|
||||
cookies: &CookieJar<'_>,
|
||||
db: &State<DatabaseConnection>,
|
||||
) -> Flash<Redirect> {
|
||||
let user = user::Model::find_or_create_user(&name.name, db.inner()).await;
|
||||
if let Some(pw) = user.pw {
|
||||
match &name.pw {
|
||||
Some(entered_pw) => {
|
||||
let mut hasher = Sha3_256::new();
|
||||
hasher.update(entered_pw);
|
||||
let entered_pw = hasher.finalize();
|
||||
|
||||
if hex::encode(entered_pw) == pw {
|
||||
log::info!("{} hat sich erfolgreich eingeloggt (mit PW)", name.name);
|
||||
cookies.add_private(Cookie::new("name", name.name.clone()));
|
||||
Flash::success(Redirect::to("/"), "Erfolgreich eingeloggt")
|
||||
} else {
|
||||
log::warn!("Somebody tried to login as {} with a WRONG pw", name.name);
|
||||
Flash::error(Redirect::to("/name"), "Falsches Passwort")
|
||||
}
|
||||
}
|
||||
None => {
|
||||
log::warn!(
|
||||
"Somebody tried to login as {}, w/o specifying a pw",
|
||||
name.name
|
||||
);
|
||||
Flash::error(Redirect::to("/name"), "Benutzer besitzt hat Passwort, du hast jedoch keines eingegeben. Bitte nochmal probieren")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log::info!("{} hat sich erfolgreich eingeloggt (ohne PW)", name.name);
|
||||
cookies.add_private(Cookie::new("name", name.name.clone()));
|
||||
Flash::success(Redirect::to("/"), "Name erfolgreich ausgewählt")
|
||||
}
|
||||
}
|
||||
|
||||
#[get("/logout")]
|
||||
fn logout(cookies: &CookieJar) -> Redirect {
|
||||
cookies.remove_private(Cookie::new("name", ""));
|
||||
Redirect::to("/")
|
||||
}
|
||||
|
||||
#[catch(401)] //unauthorized
|
||||
fn unauthorized_error() -> Redirect {
|
||||
Redirect::to("/name")
|
||||
}
|
||||
|
||||
pub async fn start() -> Rocket<Build> {
|
||||
rocket::build()
|
||||
.attach(Template::fairing())
|
||||
.manage(Database::connect("sqlite://db.sqlite").await.unwrap())
|
||||
.mount("/public", FileServer::from("static/"))
|
||||
.mount("/", routes![index, name, savename, logout])
|
||||
.mount("/day", restday::routes())
|
||||
.mount("/register", restreg::routes())
|
||||
.mount("/user", restuser::routes())
|
||||
.register("/", catchers![unauthorized_error])
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
use rocket::{form::Form, response::Redirect, Route, State};
|
||||
use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, Set};
|
||||
|
||||
use crate::models::day;
|
||||
|
||||
use super::NaiveDateForm;
|
||||
|
||||
#[derive(FromForm, Debug)]
|
||||
struct DayForm {
|
||||
day: NaiveDateForm,
|
||||
#[field(validate = range(0..20))]
|
||||
planned_amount_cox: i32,
|
||||
planned_starting_time: Option<String>,
|
||||
open_registration: bool,
|
||||
}
|
||||
|
||||
#[put("/", data = "<day>")]
|
||||
async fn create(db: &State<DatabaseConnection>, day: Form<DayForm>) -> Redirect {
|
||||
let new_day = day::ActiveModel {
|
||||
day: Set(*day.day),
|
||||
planned_amount_cox: Set(day.planned_amount_cox),
|
||||
planned_starting_time: Set(day.planned_starting_time.clone()),
|
||||
open_registration: Set(day.open_registration),
|
||||
};
|
||||
|
||||
let day: Option<day::Model> = day::Entity::find_by_id(*day.day)
|
||||
.one(db.inner())
|
||||
.await
|
||||
.unwrap();
|
||||
if let Some(day) = day {
|
||||
log::info!("{:?} got updated to {:?}", day, new_day);
|
||||
new_day.update(db.inner()).await.unwrap(); //TODO: fixme
|
||||
} else {
|
||||
log::info!("{:?} got inserted", new_day);
|
||||
new_day.insert(db.inner()).await.unwrap(); //TODO: fixme
|
||||
}
|
||||
|
||||
Redirect::to("/")
|
||||
}
|
||||
|
||||
pub fn routes() -> Vec<Route> {
|
||||
routes![create]
|
||||
}
|
@ -1,139 +0,0 @@
|
||||
use rocket::{
|
||||
form::Form,
|
||||
response::{Flash, Redirect},
|
||||
Route, State,
|
||||
};
|
||||
use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, Set};
|
||||
|
||||
use crate::models::{day, trip, user};
|
||||
|
||||
use super::NaiveDateForm;
|
||||
|
||||
#[derive(FromForm)]
|
||||
struct RegisterForm {
|
||||
day: NaiveDateForm,
|
||||
#[field(validate = len(3..))]
|
||||
name: String,
|
||||
time: Option<String>,
|
||||
cox_id: Option<i32>,
|
||||
}
|
||||
|
||||
#[put("/", data = "<register>")]
|
||||
async fn register(
|
||||
db: &State<DatabaseConnection>,
|
||||
register: Form<RegisterForm>,
|
||||
user: user::Model,
|
||||
) -> Flash<Redirect> {
|
||||
let day = day::Entity::find_by_id(*register.day)
|
||||
.one(db.inner())
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("There's no trip on this date (yet)");
|
||||
|
||||
if register.cox_id.is_none() && !day.open_registration && register.time.is_none() {
|
||||
log::error!("{} tried to register, even though the user it should not be possible to do so via UI -> manually crafted request?", user.name);
|
||||
return Flash::error(
|
||||
Redirect::to("/"),
|
||||
"Don't (try to ;)) abuse this system! Incident has been reported...",
|
||||
);
|
||||
}
|
||||
|
||||
if !user.add_different_user && user.name != register.name {
|
||||
log::error!("{} tried to register a different person, even though the user has no add_different_user flag and thus it should not be possible to do so via UI -> manually crafted request?", user.name);
|
||||
return Flash::error(
|
||||
Redirect::to("/"),
|
||||
"Don't (try to ;)) abuse this system! Incident has been reported...",
|
||||
);
|
||||
}
|
||||
|
||||
let user = user::Model::find_or_create_user(®ister.name, db.inner()).await;
|
||||
|
||||
if let Some(cox_id) = register.cox_id {
|
||||
let trip = trip::Entity::find_by_id(cox_id)
|
||||
.one(db.inner())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
if trip.user_id == user.id {
|
||||
log::warn!(
|
||||
"{} tried to register for his own trip ({})",
|
||||
user.name,
|
||||
trip.id
|
||||
);
|
||||
return Flash::error(
|
||||
Redirect::to("/"),
|
||||
"Du kannst an deinen eigenen Ausfahrten nicht teilnehmen...",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let day = format!("{}", day.day.format("%Y-%m-%d"));
|
||||
let trip = trip::ActiveModel {
|
||||
day: Set(day.clone()),
|
||||
user_id: Set(user.id),
|
||||
begin: Set(register.time.clone()),
|
||||
cox_id: Set(register.cox_id),
|
||||
..Default::default()
|
||||
};
|
||||
if trip.insert(db.inner()).await.is_ok() {
|
||||
log::info!("{} registered for {:?}", user.name, day);
|
||||
Flash::success(Redirect::to("/"), "Erfolgreich angemeldet!")
|
||||
} else {
|
||||
log::warn!(
|
||||
"{} tried to register for {:?}, but is already registered",
|
||||
user.name,
|
||||
day
|
||||
);
|
||||
Flash::error(Redirect::to("/"), "Du bist bereits angemeldet")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(FromForm)]
|
||||
struct DeleteForm {
|
||||
id: i32,
|
||||
}
|
||||
|
||||
#[delete("/", data = "<delete>")]
|
||||
async fn delete(
|
||||
db: &State<DatabaseConnection>,
|
||||
delete: Form<DeleteForm>,
|
||||
user: user::Model,
|
||||
) -> Flash<Redirect> {
|
||||
let trip = trip::Entity::find_by_id(delete.id)
|
||||
.one(db.inner())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
match trip {
|
||||
None => {
|
||||
log::error!("Tried to delete registration of non-existing trip (prob. hand crafted request (user.name = {})", user.name);
|
||||
return Flash::error(Redirect::to("/"), "Du bist gar nicht angemeldet!");
|
||||
}
|
||||
Some(trip) => {
|
||||
if trip.user_id != user.id {
|
||||
log::error!(
|
||||
"{} tried to delete a registration from user_id {} (probably hand-crafted request)",
|
||||
user.name,
|
||||
delete.id
|
||||
);
|
||||
return Flash::error(
|
||||
Redirect::to("/"),
|
||||
"Du kannst nur deine eigenen Anmeldungen löschen!",
|
||||
);
|
||||
}
|
||||
log::info!("User {} deleted the registration for {:?}", user.name, trip);
|
||||
trip::Entity::delete(trip::ActiveModel {
|
||||
id: Set(trip.id),
|
||||
..Default::default()
|
||||
})
|
||||
.exec(db.inner())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
Flash::success(Redirect::to("/"), "Abmeldung erfolgreich")
|
||||
}
|
||||
pub fn routes() -> Vec<Route> {
|
||||
routes![register, delete]
|
||||
}
|
@ -1,54 +0,0 @@
|
||||
use rocket::{form::Form, response::Redirect, Route, State};
|
||||
use rocket_dyn_templates::{context, Template};
|
||||
use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, Set};
|
||||
use sha3::{Digest, Sha3_256};
|
||||
|
||||
use crate::models::user;
|
||||
|
||||
#[get("/")]
|
||||
async fn index(db: &State<DatabaseConnection>, user: user::AdminUser) -> Template {
|
||||
let users = user::Entity::find().all(db.inner()).await.unwrap();
|
||||
|
||||
Template::render("user/index", context! {user, users})
|
||||
}
|
||||
|
||||
#[derive(FromForm)]
|
||||
struct UserEditForm {
|
||||
pw: Option<String>,
|
||||
is_cox: bool,
|
||||
add_different_user: bool,
|
||||
is_admin: bool,
|
||||
}
|
||||
|
||||
#[put("/<id>", data = "<data>")]
|
||||
async fn update(
|
||||
db: &State<DatabaseConnection>,
|
||||
id: i32,
|
||||
data: Form<UserEditForm>,
|
||||
_user: user::AdminUser,
|
||||
) -> Redirect {
|
||||
let mut new_user = user::ActiveModel {
|
||||
id: Set(id),
|
||||
is_cox: Set(data.is_cox),
|
||||
is_admin: Set(data.is_admin),
|
||||
add_different_user: Set(data.add_different_user),
|
||||
..Default::default()
|
||||
};
|
||||
if let Some(pw) = &data.pw {
|
||||
if !pw.is_empty() {
|
||||
let mut hasher = Sha3_256::new();
|
||||
hasher.update(pw);
|
||||
let entered_pw = hasher.finalize();
|
||||
|
||||
let pw = hex::encode(entered_pw);
|
||||
new_user.pw = Set(Some(pw));
|
||||
}
|
||||
}
|
||||
new_user.update(db.inner()).await.unwrap();
|
||||
|
||||
Redirect::to("/user")
|
||||
}
|
||||
|
||||
pub fn routes() -> Vec<Route> {
|
||||
routes![index, update]
|
||||
}
|
Reference in New Issue
Block a user