clean repo
This commit is contained in:
@ -1,11 +1,7 @@
|
||||
#[macro_use]
|
||||
extern crate rocket;
|
||||
|
||||
mod models;
|
||||
mod rest;
|
||||
|
||||
#[launch]
|
||||
async fn rocket() -> _ {
|
||||
env_logger::init();
|
||||
rest::start().await
|
||||
}
|
||||
|
@ -1,41 +0,0 @@
|
||||
use sea_orm::{ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter};
|
||||
use serde::Serialize;
|
||||
|
||||
use super::{day, trip, user};
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
pub struct TripWithUser {
|
||||
pub trip: trip::Model,
|
||||
pub user: user::Model,
|
||||
}
|
||||
|
||||
impl TripWithUser {
|
||||
fn new(trip: trip::Model, user: user::Model) -> Self {
|
||||
Self { trip, user }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
pub struct DayWithTrips {
|
||||
pub day: day::Model,
|
||||
pub trips: Vec<TripWithUser>,
|
||||
}
|
||||
|
||||
impl DayWithTrips {
|
||||
pub async fn new(day: day::Model, db: &DatabaseConnection) -> Self {
|
||||
let mut trips = Vec::new();
|
||||
|
||||
let trips_with_users: Vec<(trip::Model, Option<user::Model>)> = trip::Entity::find()
|
||||
.filter(trip::Column::Day.eq(day.day))
|
||||
.find_also_related(user::Entity)
|
||||
.all(db)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
for (trip, users) in trips_with_users {
|
||||
trips.push(TripWithUser::new(trip, users.unwrap()));
|
||||
}
|
||||
|
||||
Self { day, trips }
|
||||
}
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.0
|
||||
|
||||
use sea_orm::{entity::prelude::*, Set};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "day")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub day: chrono::NaiveDate,
|
||||
pub planned_amount_cox: i32,
|
||||
pub planned_starting_time: Option<String>,
|
||||
pub open_registration: bool,
|
||||
}
|
||||
|
||||
impl Model {
|
||||
pub async fn find_or_create_day(date: chrono::NaiveDate, db: &DatabaseConnection) -> Model {
|
||||
let day = Entity::find_by_id(date).one(db).await.unwrap();
|
||||
if let Some(day) = day {
|
||||
day
|
||||
} else {
|
||||
let new_day = ActiveModel {
|
||||
day: Set(date),
|
||||
..Default::default()
|
||||
};
|
||||
new_day.insert(db).await.unwrap()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(has_many = "super::trip::Entity")]
|
||||
Trip,
|
||||
}
|
||||
|
||||
impl Related<super::trip::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Trip.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
@ -1,9 +0,0 @@
|
||||
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.0
|
||||
|
||||
pub mod prelude;
|
||||
|
||||
pub mod all;
|
||||
|
||||
pub mod day;
|
||||
pub mod trip;
|
||||
pub mod user;
|
@ -1,5 +0,0 @@
|
||||
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.0
|
||||
|
||||
pub use super::day::Entity as Day;
|
||||
pub use super::trip::Entity as Trip;
|
||||
pub use super::user::Entity as User;
|
@ -1,58 +0,0 @@
|
||||
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.0
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "trip")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub day: String,
|
||||
pub user_id: i32,
|
||||
pub cox_id: Option<i32>,
|
||||
pub begin: Option<String>,
|
||||
pub created: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::day::Entity",
|
||||
from = "Column::Day",
|
||||
to = "super::day::Column::Day",
|
||||
on_update = "NoAction",
|
||||
on_delete = "NoAction"
|
||||
)]
|
||||
Day,
|
||||
#[sea_orm(
|
||||
belongs_to = "super::user::Entity",
|
||||
from = "Column::CoxId",
|
||||
to = "super::user::Column::Id",
|
||||
on_update = "NoAction",
|
||||
on_delete = "NoAction"
|
||||
)]
|
||||
Cox,
|
||||
#[sea_orm(
|
||||
belongs_to = "super::user::Entity",
|
||||
from = "Column::UserId",
|
||||
to = "super::user::Column::Id",
|
||||
on_update = "NoAction",
|
||||
on_delete = "NoAction"
|
||||
)]
|
||||
User,
|
||||
}
|
||||
|
||||
impl Related<super::day::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Day.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::user::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::User.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
@ -1,94 +0,0 @@
|
||||
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.0
|
||||
|
||||
use rocket::{
|
||||
http::Status,
|
||||
request::{self, FromRequest, Outcome},
|
||||
Request, State,
|
||||
};
|
||||
use sea_orm::{entity::prelude::*, Set};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "user")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub name: String,
|
||||
pub pw: Option<String>,
|
||||
pub is_cox: bool,
|
||||
pub add_different_user: bool,
|
||||
pub is_admin: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct AdminUser(Model);
|
||||
|
||||
impl Model {
|
||||
pub async fn find_or_create_user(name: &str, db: &DatabaseConnection) -> Model {
|
||||
let user = Entity::find()
|
||||
.filter(Column::Name.eq(name))
|
||||
.one(db)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
if let Some(user) = user {
|
||||
user
|
||||
} else {
|
||||
let user = ActiveModel {
|
||||
name: Set(name.into()),
|
||||
..Default::default()
|
||||
};
|
||||
log::info!("User {:?} created", user);
|
||||
user.insert(db).await.unwrap()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
NoCookieSet,
|
||||
NoAdmin,
|
||||
}
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for Model {
|
||||
type Error = Error;
|
||||
|
||||
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
||||
match req.cookies().get_private("name") {
|
||||
Some(name) => {
|
||||
let db = req.guard::<&'r State<DatabaseConnection>>();
|
||||
let name = name.value();
|
||||
let user = Model::find_or_create_user(name, db.await.unwrap().inner()).await;
|
||||
Outcome::Success(user)
|
||||
}
|
||||
None => Outcome::Failure((Status::Unauthorized, Error::NoCookieSet)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for AdminUser {
|
||||
type Error = Error;
|
||||
|
||||
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
||||
match req.cookies().get_private("name") {
|
||||
Some(name) => {
|
||||
let db = req.guard::<&'r State<DatabaseConnection>>();
|
||||
let name = name.value();
|
||||
let user = Model::find_or_create_user(name, db.await.unwrap().inner()).await;
|
||||
if user.is_admin {
|
||||
Outcome::Success(AdminUser(user))
|
||||
} else {
|
||||
Outcome::Failure((Status::Unauthorized, Error::NoAdmin))
|
||||
}
|
||||
}
|
||||
None => Outcome::Failure((Status::Unauthorized, Error::NoCookieSet)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
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