This commit is contained in:
2023-04-04 15:16:21 +02:00
parent 0bdd073d7f
commit cedaba5709
10 changed files with 453 additions and 28 deletions

View File

@ -2,17 +2,23 @@ use chrono::NaiveDate;
use serde::Serialize;
use sqlx::SqlitePool;
use self::planned_event::PlannedEvent;
use self::{
planned_event::{PlannedEvent, PlannedEventWithUser},
trip::{Trip, TripWithUser},
};
pub mod planned_event;
pub mod trip;
pub mod tripdetails;
pub mod user;
pub mod usertrip;
//pub mod users;
#[derive(Serialize)]
pub struct Day {
day: NaiveDate,
planned_events: Vec<PlannedEvent>,
planned_events: Vec<PlannedEventWithUser>,
trips: Vec<TripWithUser>,
}
impl Day {
@ -20,6 +26,7 @@ impl Day {
Self {
day,
planned_events: PlannedEvent::get_for_day(db, day).await,
trips: Trip::get_for_day(db, day).await,
}
}
}

View File

@ -2,7 +2,7 @@ use chrono::NaiveDate;
use serde::Serialize;
use sqlx::SqlitePool;
#[derive(Serialize)]
#[derive(Serialize, Clone)]
pub struct PlannedEvent {
id: i64,
name: String,
@ -15,10 +15,18 @@ pub struct PlannedEvent {
notes: Option<String>,
}
#[derive(Serialize)]
pub struct PlannedEventWithUser {
#[serde(flatten)]
planned_event: PlannedEvent,
cox: Vec<String>,
rower: Vec<String>,
}
impl PlannedEvent {
pub async fn get_for_day(db: &SqlitePool, day: NaiveDate) -> Vec<Self> {
pub async fn get_for_day(db: &SqlitePool, day: NaiveDate) -> Vec<PlannedEventWithUser> {
let day = format!("{}", day);
sqlx::query_as!(
let events = sqlx::query_as!(
PlannedEvent,
"
SELECT planned_event.id, name, planned_amount_cox, allow_guests, trip_details_id, planned_starting_time, max_people, day, notes
@ -30,7 +38,77 @@ WHERE day=?
)
.fetch_all(db)
.await
.unwrap() //TODO: fixme
.unwrap(); //TODO: fixme
let mut ret = Vec::new();
for event in events {
ret.push(PlannedEventWithUser {
planned_event: event.clone(),
cox: Self::get_all_cox_for_id(db, event.id).await,
rower: Self::get_all_rower_for_id(db, event.id).await,
})
}
ret
}
pub async fn rower_can_register(db: &SqlitePool, trip_details_id: i64) -> bool {
let amount_currently_registered = sqlx::query!(
"
SELECT COUNT(*) as count FROM user_trip WHERE trip_details_id = ?
",
trip_details_id
)
.fetch_one(db)
.await
.unwrap(); //TODO: fixme
let amount_currently_registered = amount_currently_registered.count as i64;
let amount_allowed_to_register = sqlx::query!(
"
SELECT max_people FROM trip_details WHERE id = ?
",
trip_details_id
)
.fetch_one(db)
.await
.unwrap(); //TODO: fixme
let amount_allowed_to_register = amount_allowed_to_register.max_people;
amount_currently_registered < amount_allowed_to_register
}
async fn get_all_cox_for_id(db: &SqlitePool, id: i64) -> Vec<String> {
let res = sqlx::query!(
"
SELECT (SELECT name FROM user WHERE cox_id = id) as name FROM trip WHERE planned_event_id = ?
",
id
)
.fetch_all(db)
.await
.unwrap(); //TODO: fixme
let mut ret = Vec::new();
for r in res {
ret.push(r.name);
}
ret
}
async fn get_all_rower_for_id(db: &SqlitePool, id: i64) -> Vec<String> {
let res = sqlx::query!(
"
SELECT (SELECT name FROM user WHERE user_trip.user_id = user.id) as name FROM user_trip WHERE trip_details_id = (SELECT trip_details_id FROM planned_event WHERE id = ?)
",
id
)
.fetch_all(db)
.await
.unwrap(); //TODO: fixme
let mut ret = Vec::new();
for r in res {
ret.push(r.name);
}
ret
}
pub async fn new(

109
src/model/trip.rs Normal file
View File

@ -0,0 +1,109 @@
use chrono::NaiveDate;
use serde::Serialize;
use sqlx::SqlitePool;
#[derive(Serialize, Clone)]
pub struct Trip {
id: i64,
cox_id: i64,
cox_name: String,
trip_details_id: Option<i64>,
planned_starting_time: String,
max_people: i64,
day: String,
notes: Option<String>,
}
#[derive(Serialize)]
pub struct TripWithUser {
#[serde(flatten)]
trip: Trip,
rower: Vec<String>,
}
impl Trip {
pub async fn get_for_day(db: &SqlitePool, day: NaiveDate) -> Vec<TripWithUser> {
let day = format!("{}", day);
let trips = sqlx::query_as!(
Trip,
"
SELECT trip.id, cox_id, user.name as cox_name, trip_details_id, planned_starting_time, max_people, day, notes
FROM trip
INNER JOIN trip_details ON trip.trip_details_id = trip_details.id
INNER JOIN user ON trip.cox_id = user.id
WHERE day=?
",
day
)
.fetch_all(db)
.await
.unwrap(); //TODO: fixme
let mut ret = Vec::new();
for trip in trips {
ret.push(TripWithUser {
trip: trip.clone(),
rower: Self::get_all_rower_for_id(db, trip.id).await,
})
}
ret
}
async fn get_all_rower_for_id(db: &SqlitePool, id: i64) -> Vec<String> {
let res = sqlx::query!(
"
SELECT (SELECT name FROM user WHERE user_trip.user_id = user.id) as name FROM user_trip WHERE trip_details_id = (SELECT trip_details_id FROM trip WHERE id = ?)
",
id
)
.fetch_all(db)
.await
.unwrap(); //TODO: fixme
let mut ret = Vec::new();
for r in res {
ret.push(r.name);
}
ret
}
pub async fn new_own(db: &SqlitePool, cox_id: i64, trip_details_id: i64) {
sqlx::query!(
"INSERT INTO trip (cox_id, trip_details_id) VALUES(?, ?)",
cox_id,
trip_details_id
)
.execute(db)
.await
.unwrap(); //TODO: fixme
}
/// Returns true if successfully inserted; false if not (e.g. because user is already
/// participant
pub async fn new_join(db: &SqlitePool, cox_id: i64, planned_event_id: i64) -> bool {
sqlx::query!(
"INSERT INTO trip (cox_id, planned_event_id) VALUES(?, ?)",
cox_id,
planned_event_id
)
.execute(db)
.await
.is_ok()
}
pub async fn delete(db: &SqlitePool, user_id: i64, planned_event_id: i64) {
let _ = sqlx::query!(
"DELETE FROM trip WHERE cox_id = ? AND planned_event_id = ?",
user_id,
planned_event_id
)
.execute(db)
.await
.is_ok();
}
//pub async fn delete(db: &SqlitePool, id: i64) {
// sqlx::query!("DELETE FROM planned_event WHERE id = ?", id)
// .execute(db)
// .await
// .unwrap(); //TODO: fixme
//}
}

View File

@ -1,3 +1,5 @@
use std::ops::Deref;
use argon2::{password_hash::SaltString, Argon2, PasswordHasher};
use rocket::{
async_trait,
@ -34,12 +36,37 @@ impl TryFrom<User> for AdminUser {
}
}
pub struct CoxUser {
user: User,
}
impl Deref for CoxUser {
type Target = User;
fn deref(&self) -> &Self::Target {
&self.user
}
}
impl TryFrom<User> for CoxUser {
type Error = LoginError;
fn try_from(user: User) -> Result<Self, Self::Error> {
if user.is_cox {
Ok(CoxUser { user })
} else {
Err(LoginError::NotACox)
}
}
}
#[derive(Debug)]
pub enum LoginError {
SqlxError(sqlx::Error),
InvalidAuthenticationCombo,
NotLoggedIn,
NotAnAdmin,
NotACox,
NoPasswordSet(User),
}
@ -181,6 +208,24 @@ impl<'r> FromRequest<'r> for AdminUser {
}
}
#[async_trait]
impl<'r> FromRequest<'r> for CoxUser {
type Error = LoginError;
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
match req.cookies().get_private("loggedin_user") {
Some(user) => {
let user: User = serde_json::from_str(&user.value()).unwrap(); //TODO: fixme
match user.try_into() {
Ok(user) => Outcome::Success(user),
Err(_) => Outcome::Failure((Status::Unauthorized, LoginError::NotAnAdmin)),
}
}
None => Outcome::Failure((Status::Unauthorized, LoginError::NotLoggedIn)),
}
}
}
#[cfg(test)]
mod test {
use crate::testdb;

27
src/model/usertrip.rs Normal file
View File

@ -0,0 +1,27 @@
use sqlx::SqlitePool;
pub struct UserTrip {}
impl UserTrip {
pub async fn new(db: &SqlitePool, user_id: i64, trip_details_id: i64) -> bool {
sqlx::query!(
"INSERT INTO user_trip (user_id, trip_details_id) VALUES(?, ?)",
user_id,
trip_details_id
)
.execute(db)
.await
.is_ok()
}
pub async fn delete(db: &SqlitePool, user_id: i64, trip_details_id: i64) {
let _ = sqlx::query!(
"DELETE FROM user_trip WHERE user_id = ? AND trip_details_id = ?",
user_id,
trip_details_id
)
.execute(db)
.await
.is_ok();
}
}