clean code with clippy

This commit is contained in:
philipp 2023-04-04 19:49:27 +02:00
parent ed1ee2e7e2
commit da31c36c70
10 changed files with 33 additions and 52 deletions

View File

@ -25,15 +25,13 @@ pub struct PlannedEventWithUser {
impl PlannedEvent { impl PlannedEvent {
pub async fn get_for_day(db: &SqlitePool, day: NaiveDate) -> Vec<PlannedEventWithUser> { pub async fn get_for_day(db: &SqlitePool, day: NaiveDate) -> Vec<PlannedEventWithUser> {
let day = format!("{}", day); let day = format!("{day}");
let events = sqlx::query_as!( let events = sqlx::query_as!(
PlannedEvent, PlannedEvent,
" "SELECT planned_event.id, name, planned_amount_cox, allow_guests, trip_details_id, planned_starting_time, max_people, day, notes
SELECT planned_event.id, name, planned_amount_cox, allow_guests, trip_details_id, planned_starting_time, max_people, day, notes
FROM planned_event FROM planned_event
INNER JOIN trip_details ON planned_event.trip_details_id = trip_details.id INNER JOIN trip_details ON planned_event.trip_details_id = trip_details.id
WHERE day=? WHERE day=?",
",
day day
) )
.fetch_all(db) .fetch_all(db)
@ -46,22 +44,20 @@ WHERE day=?
planned_event: event.clone(), planned_event: event.clone(),
cox: Self::get_all_cox_for_id(db, event.id).await, cox: Self::get_all_cox_for_id(db, event.id).await,
rower: Self::get_all_rower_for_id(db, event.id).await, rower: Self::get_all_rower_for_id(db, event.id).await,
}) });
} }
ret ret
} }
pub async fn rower_can_register(db: &SqlitePool, trip_details_id: i64) -> bool { pub async fn rower_can_register(db: &SqlitePool, trip_details_id: i64) -> bool {
let amount_currently_registered = sqlx::query!( let amount_currently_registered = sqlx::query!(
" "SELECT COUNT(*) as count FROM user_trip WHERE trip_details_id = ?",
SELECT COUNT(*) as count FROM user_trip WHERE trip_details_id = ?
",
trip_details_id trip_details_id
) )
.fetch_one(db) .fetch_one(db)
.await .await
.unwrap(); //TODO: fixme .unwrap(); //TODO: fixme
let amount_currently_registered = amount_currently_registered.count as i64; let amount_currently_registered = i64::from(amount_currently_registered.count);
let amount_allowed_to_register = sqlx::query!( let amount_allowed_to_register = sqlx::query!(
" "
@ -87,11 +83,8 @@ SELECT (SELECT name FROM user WHERE cox_id = id) as name FROM trip WHERE planned
.fetch_all(db) .fetch_all(db)
.await .await
.unwrap(); //TODO: fixme .unwrap(); //TODO: fixme
let mut ret = Vec::new();
for r in res { res.into_iter().map(|x| x.name).collect()
ret.push(r.name);
}
ret
} }
async fn get_all_rower_for_id(db: &SqlitePool, id: i64) -> Vec<String> { async fn get_all_rower_for_id(db: &SqlitePool, id: i64) -> Vec<String> {
@ -104,14 +97,11 @@ SELECT (SELECT name FROM user WHERE user_trip.user_id = user.id) as name FROM us
.fetch_all(db) .fetch_all(db)
.await .await
.unwrap(); //TODO: fixme .unwrap(); //TODO: fixme
let mut ret = Vec::new();
for r in res { res.into_iter().map(|x| x.name).collect()
ret.push(r.name);
}
ret
} }
pub async fn new( pub async fn create(
db: &SqlitePool, db: &SqlitePool,
name: String, name: String,
planned_amount_cox: i32, planned_amount_cox: i32,

View File

@ -23,7 +23,7 @@ pub struct TripWithUser {
impl Trip { impl Trip {
pub async fn get_for_day(db: &SqlitePool, day: NaiveDate) -> Vec<TripWithUser> { pub async fn get_for_day(db: &SqlitePool, day: NaiveDate) -> Vec<TripWithUser> {
let day = format!("{}", day); let day = format!("{day}");
let trips = sqlx::query_as!( let trips = sqlx::query_as!(
Trip, Trip,
" "
@ -43,7 +43,7 @@ WHERE day=?
ret.push(TripWithUser { ret.push(TripWithUser {
trip: trip.clone(), trip: trip.clone(),
rower: Self::get_all_rower_for_id(db, trip.id).await, rower: Self::get_all_rower_for_id(db, trip.id).await,
}) });
} }
ret ret
} }
@ -58,11 +58,8 @@ SELECT (SELECT name FROM user WHERE user_trip.user_id = user.id) as name FROM us
.fetch_all(db) .fetch_all(db)
.await .await
.unwrap(); //TODO: fixme .unwrap(); //TODO: fixme
let mut ret = Vec::new();
for r in res { res.into_iter().map(|x| x.name).collect()
ret.push(r.name);
}
ret
} }
pub async fn new_own(db: &SqlitePool, cox_id: i64, trip_details_id: i64) { pub async fn new_own(db: &SqlitePool, cox_id: i64, trip_details_id: i64) {

View File

@ -11,7 +11,7 @@ pub struct TripDetails {
} }
impl TripDetails { impl TripDetails {
pub async fn new( pub async fn create(
db: &SqlitePool, db: &SqlitePool,
planned_starting_time: String, planned_starting_time: String,
max_people: i32, max_people: i32,

View File

@ -121,11 +121,11 @@ WHERE name like ?
Ok(user) Ok(user)
} }
fn get_hashed_pw(pw: String) -> String { fn get_hashed_pw(pw: &str) -> String {
let salt = SaltString::from_b64("dS/X5/sPEKTj4Rzs/CuvzQ").unwrap(); let salt = SaltString::from_b64("dS/X5/sPEKTj4Rzs/CuvzQ").unwrap();
let argon2 = Argon2::default(); let argon2 = Argon2::default();
argon2 argon2
.hash_password(&pw.as_bytes(), &salt) .hash_password(pw.as_bytes(), &salt)
.unwrap() .unwrap()
.to_string() .to_string()
} }
@ -135,7 +135,7 @@ WHERE name like ?
match user.pw.clone() { match user.pw.clone() {
Some(user_pw) => { Some(user_pw) => {
let password_hash = Self::get_hashed_pw(pw); let password_hash = Self::get_hashed_pw(&pw);
if password_hash == user_pw { if password_hash == user_pw {
return Ok(user); return Ok(user);
} }
@ -167,7 +167,7 @@ FROM user
} }
pub async fn update_pw(&self, db: &SqlitePool, pw: String) { pub async fn update_pw(&self, db: &SqlitePool, pw: String) {
let pw = Self::get_hashed_pw(pw); let pw = Self::get_hashed_pw(&pw);
sqlx::query!("UPDATE user SET pw = ? where id = ?", pw, self.id) sqlx::query!("UPDATE user SET pw = ? where id = ?", pw, self.id)
.execute(db) .execute(db)
.await .await
@ -182,7 +182,7 @@ impl<'r> FromRequest<'r> for User {
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> { async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
match req.cookies().get_private("loggedin_user") { match req.cookies().get_private("loggedin_user") {
Some(user) => { Some(user) => {
let user: User = serde_json::from_str(&user.value()).unwrap(); //TODO: fixme let user: User = serde_json::from_str(user.value()).unwrap(); //TODO: fixme
Outcome::Success(user) Outcome::Success(user)
} }
None => Outcome::Failure((Status::Unauthorized, LoginError::NotLoggedIn)), None => Outcome::Failure((Status::Unauthorized, LoginError::NotLoggedIn)),
@ -197,7 +197,7 @@ impl<'r> FromRequest<'r> for AdminUser {
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> { async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
match req.cookies().get_private("loggedin_user") { match req.cookies().get_private("loggedin_user") {
Some(user) => { Some(user) => {
let user: User = serde_json::from_str(&user.value()).unwrap(); //TODO: fixme let user: User = serde_json::from_str(user.value()).unwrap(); //TODO: fixme
match user.try_into() { match user.try_into() {
Ok(user) => Outcome::Success(user), Ok(user) => Outcome::Success(user),
Err(_) => Outcome::Failure((Status::Unauthorized, LoginError::NotAnAdmin)), Err(_) => Outcome::Failure((Status::Unauthorized, LoginError::NotAnAdmin)),
@ -215,7 +215,7 @@ impl<'r> FromRequest<'r> for CoxUser {
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> { async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
match req.cookies().get_private("loggedin_user") { match req.cookies().get_private("loggedin_user") {
Some(user) => { Some(user) => {
let user: User = serde_json::from_str(&user.value()).unwrap(); //TODO: fixme let user: User = serde_json::from_str(user.value()).unwrap(); //TODO: fixme
match user.try_into() { match user.try_into() {
Ok(user) => Outcome::Success(user), Ok(user) => Outcome::Success(user),
Err(_) => Outcome::Failure((Status::Unauthorized, LoginError::NotAnAdmin)), Err(_) => Outcome::Failure((Status::Unauthorized, LoginError::NotAnAdmin)),

View File

@ -3,7 +3,7 @@ use sqlx::SqlitePool;
pub struct UserTrip {} pub struct UserTrip {}
impl UserTrip { impl UserTrip {
pub async fn new(db: &SqlitePool, user_id: i64, trip_details_id: i64) -> bool { pub async fn create(db: &SqlitePool, user_id: i64, trip_details_id: i64) -> bool {
sqlx::query!( sqlx::query!(
"INSERT INTO user_trip (user_id, trip_details_id) VALUES(?, ?)", "INSERT INTO user_trip (user_id, trip_details_id) VALUES(?, ?)",
user_id, user_id,

View File

@ -27,7 +27,7 @@ async fn create(
_admin: AdminUser, _admin: AdminUser,
) -> Flash<Redirect> { ) -> Flash<Redirect> {
//TODO: fix clones() //TODO: fix clones()
let trip_details_id = TripDetails::new( let trip_details_id = TripDetails::create(
db, db,
data.planned_starting_time.clone(), data.planned_starting_time.clone(),
data.max_people, data.max_people,
@ -37,7 +37,7 @@ async fn create(
.await; .await;
//TODO: fix clone() //TODO: fix clone()
PlannedEvent::new( PlannedEvent::create(
db, db,
data.name.clone(), data.name.clone(),
data.planned_amount_cox, data.planned_amount_cox,

View File

@ -44,14 +44,11 @@ async fn update(
_admin: AdminUser, _admin: AdminUser,
) -> Flash<Redirect> { ) -> Flash<Redirect> {
let user = User::find_by_id(db, data.id).await; let user = User::find_by_id(db, data.id).await;
let user = match user { let Ok(user) = user else {
Ok(user) => user,
Err(_) => {
return Flash::error( return Flash::error(
Redirect::to("/admin/user"), Redirect::to("/admin/user"),
format!("User with ID {} does not exist!", data.id), format!("User with ID {} does not exist!", data.id),
) )
}
}; };
user.update(db, data.is_cox, data.is_admin, data.is_guest) user.update(db, data.is_cox, data.is_admin, data.is_guest)

View File

@ -14,7 +14,7 @@ use sqlx::SqlitePool;
use crate::model::user::{LoginError, User}; use crate::model::user::{LoginError, User};
#[get("/")] #[get("/")]
async fn index(flash: Option<FlashMessage<'_>>) -> Template { fn index(flash: Option<FlashMessage<'_>>) -> Template {
let mut context = tera::Context::new(); let mut context = tera::Context::new();
if let Some(msg) = flash { if let Some(msg) = flash {
@ -59,7 +59,7 @@ async fn login(
} }
#[get("/set-pw/<userid>")] #[get("/set-pw/<userid>")]
async fn setpw(userid: i32) -> Template { fn setpw(userid: i32) -> Template {
Template::render("auth/set-pw", context!(userid)) Template::render("auth/set-pw", context!(userid))
} }
@ -77,14 +77,11 @@ async fn updatepw(
cookies: &CookieJar<'_>, cookies: &CookieJar<'_>,
) -> Flash<Redirect> { ) -> Flash<Redirect> {
let user = User::find_by_id(db, updatepw.userid).await; let user = User::find_by_id(db, updatepw.userid).await;
let user = match user { let Ok(user) = user else{
Ok(user) => user,
Err(_) => {
return Flash::error( return Flash::error(
Redirect::to("/auth"), Redirect::to("/auth"),
format!("User with ID {} does not exist!", updatepw.userid), format!("User with ID {} does not exist!", updatepw.userid),
) )
}
}; };
if updatepw.password != updatepw.password_confirm { if updatepw.password != updatepw.password_confirm {
@ -106,7 +103,7 @@ async fn updatepw(
} }
#[get("/logout")] #[get("/logout")]
async fn logout(cookies: &CookieJar<'_>, _user: User) -> Flash<Redirect> { fn logout(cookies: &CookieJar<'_>, _user: User) -> Flash<Redirect> {
cookies.remove_private(Cookie::named("loggedin_user")); cookies.remove_private(Cookie::named("loggedin_user"));
Flash::success(Redirect::to("/auth"), "Logout erfolgreich") Flash::success(Redirect::to("/auth"), "Logout erfolgreich")

View File

@ -20,7 +20,7 @@ struct AddTripForm {
#[post("/trip", data = "<data>")] #[post("/trip", data = "<data>")]
async fn create(db: &State<SqlitePool>, data: Form<AddTripForm>, cox: CoxUser) -> Flash<Redirect> { async fn create(db: &State<SqlitePool>, data: Form<AddTripForm>, cox: CoxUser) -> Flash<Redirect> {
//TODO: fix clones() //TODO: fix clones()
let trip_details_id = TripDetails::new( let trip_details_id = TripDetails::create(
db, db,
data.planned_starting_time.clone(), data.planned_starting_time.clone(),
data.max_people, data.max_people,

View File

@ -47,7 +47,7 @@ async fn join(db: &State<SqlitePool>, trip_details_id: i64, user: User) -> Flash
return Flash::error(Redirect::to("/"), "Bereits ausgebucht!"); return Flash::error(Redirect::to("/"), "Bereits ausgebucht!");
} }
if UserTrip::new(db, user.id, trip_details_id).await { if UserTrip::create(db, user.id, trip_details_id).await {
Flash::success(Redirect::to("/"), "Erfolgreich angemeldet!") Flash::success(Redirect::to("/"), "Erfolgreich angemeldet!")
} else { } else {
Flash::error(Redirect::to("/"), "Du nimmst bereits teil!") Flash::error(Redirect::to("/"), "Du nimmst bereits teil!")